5π
Your views, may looks like that:
def your_view(request):
form = YourForm(request.POST or None)
if form.is_valid():
your_object = form.save(commit=False)
your_object.user = request.user
your_object.save()
return redirect('your_success_url')
context = {'form': form}
return render(request, 'your_template.html', context)
You need to adapt some parts, but in the general the should be your view. You need to pay attention to that this view needs a login_required
decorator in order to not allow non-logged users to create objects.
π€Luan Fonseca
0π
Use the request.user
. I donβt know how your app works but when creating, do this:
model = ModelName(user = request.user)
model.save()
I used ModelName
because it is best practise to start a class name with a capital, which is not fulfilled in your create
model. I suggest you change this.
There also seems to be a mistake in your view, it should be request
not reques
.
Your view could be like so:
def index(request):
form = FormName(request.POST or None)
if form.is_valid():
form.save()
return render(request, "path/to/template", {"form": form})
And your template could be:
<form method="POST" action="">
{{ form }}
<input type="submit">
</form>
π€monte
- [Django]-Sending notification to one user using Channels 2
- [Django]-How to do a syncdb with django, when migrations are also involved
0π
So i solved my problem
in my model.py
class SetdistributorProfile(models.Model):
user=modelss.foreignkey(settings.AUTH_USER_MODEL,null=True,unique=True)
views.py
def SetDistribution(request):
if not requested.user.is_authenticated:
return redirect('app_name:url_name)
if request.method === 'POST':
dis = MymodelForm(request.POST or None)
if dis.is_valid():
instance=dis.save(commit=False)
instance.user=request.user
instance.save()
return redirect('myappname:urlname')
else:
instance=MymodelFomr()
context={'intance':intance}
return render(request,'page.hmtl',context)
π€Scofield
- [Django]-Missing staticfiles manifest entry in Django deployment using Heroku
- [Django]-AttributeError: 'module' object has no attribute 'Datefield'
- [Django]-Django-python how to convert text to pdf
- [Django]-'ContentType' object has no attribute 'model_class' in data migration
- [Django]-Django exclude query, can i pass multiple parameters?
0π
Another way to solve this in your views.py
if request.method == "POST":
yourModel = YourModel(user_id = request.user.id)
form = YourModelForm(request.POST, request.FILES, instance=yourModel)
if form.is_valid():
form.save()
π€medz
- [Django]-Django β How to redirect differently using LoginRequired and PermissionRequired?
- [Django]-Django β designing models with virtual fields?
Source:stackexchange.com