how to insert data to database without forms.py in django - django

This method works fine for me can some one say how to add file or images like this
def insert_students(request);
name = request.POST['name']
class = request.POST['class']
student = studentsmodels(name=name, class=class)
student.save()
return redirect('/')
return render(request, "insertpage.html")

Using Django forms would make your life so much easier, frankly. However, you can still create objects without forms and add files to them. Instead of request.POST the files are stored in request.FILES the documentation goes into detail about how files are uploaded:
https://docs.djangoproject.com/en/4.0/topics/http/file-uploads/

def submit_form(request):
if request.method == POST:
name = request.POST["name"]
class = request.POST["class"]
if Mymodel.objects.filter(name=name, class=class).exist():
messages.infor("class and name already exist")
else:
MyModel.objects.create(name=name, class=class)
return render(request, "submit_form.html)
submit_form.html
<form action="{% url 'submit_form' %}" method="post">
{%csrf_token%}
<input name="name" placeholder="Enter Name" type="text">
<input name="class" type="text" placeholder="Enter Class">
<button class="button is-success is-fullwidth is-medium mt-5"
type="submit">submit
</button>
</form>

Related

tags will not store in database in django

Tags will not store in database in Django
def addque(request):
if request.method == "POST":
user = request.user
if user.is_anonymous:
return redirect('addquery')
if user.is_active:
question = request.POST['question']
body = request.POST['body']
tags = request.POST['tags']
aquuid = request.user.aquuid
addquery = Question(question=question, user_id=aquuid, que_body=body, tags=tags)
addquery.save()
return redirect('addquery')
else:
return render(request, 'question/ask.html')
After giving the input the data is stored in the tags field but, not saving in the database. I can manually insert data through the admin panel successfully but not as a non-staff user. I have installed taggit and placed it in the installed_apps in settings.py. What is the issue with the code?
Tags are Many-to-Many objects and you can't add those to an object until the object has been saved. The documentation shows that you need to use .add() to add tags to a model instance. Your code should be:
addquery = Question(question=question, user_id=aquuid, que_body=body)
addquery.save()
addquery.tags.add(tags)
As an aside, you might be better served by a ModelForm which can handle the tags and all of this stuff that you're doing:
question = request.POST['question']
body = request.POST['body']
tags = request.POST['tags']
https://django-taggit.readthedocs.io/en/latest/forms.html
Use model form
In html use id of forms like this
HTML
<form action="{% url 'addquery' %}" method="post">
{% csrf_token %}
<div class="psrelative">
<input id="id_question" name="question" type="text" maxlength="300" tabindex="100" placeholder="e.g. Is there an R function for finding the index of an element in a vector?" class="s-input js-post-title-field" value="" data-min-length="15" data-max-length="150" autocomplete="off" required>
</div>
<textarea name="que_body" id="id_que_body" class="textarea-body"></textarea required>
<div class="psrelative">
<input id="id_tags" name="tags" type="text" maxlength="300" tabindex="100"
placeholder="e.g. (ruby-on-rails vba spring)" class="s-input js-post-title-field" value="" data-min-length="15" data-max-length="150" autocomplete="off" required>
</div>
<button class="review-question-btn" type="submit" tabindex="120"> Submit your question
</button>
</form>
Forms.py
from django import forms
from .models import Question
class Addqueform(forms.ModelForm):
class Meta:
model = Question
fields = ['question','que_body','tags']
Views.py
from .forms import Addqueform
def addque(request):
queform = Addqueform(request.POST)
if request.method == "POST":
user = request.user
if user.is_anonymous:
return redirect('addquery')
if user.is_active:
if queform.is_valid():
aquuid = request.user.aquuid
question = queform.cleaned_data['question']
body = queform.cleaned_data['que_body']
tags = queform.cleaned_data['tags']
addquery = Question(question=question, user_id=aquuid, que_body=body)
for tag in tags:
addquery.tags.add(tag)
addquery.save()
return redirect('addquery')
else:
queform = Addqueform()
return render(request, 'question/ask.html', {'form': queform})
else:
return render(request, 'question/ask.html', {'form': queform})
I think It will Work

Difference between two methods in django

What's difference between two methods and which is better for long run ? Is there any advantage one over other?
To add a staff:
(1st Method)
views.py
def add_staff(request):
return render(request, 'hod_template/add_staff_template.html')
def add_staff_save(request):
if request.method != 'POST':
return HttpResponse('Method not allowed')
else:
first_name = request.GET.get('first_name')
last_name = request.GET.get('last_name')
username = request.GET.get('username')
email = request.GET.get('email')
password = request.GET.get('password')
address = request.GET.get('address')
try:
user = CustomUser.objects.create_user(username=username, password=password, email=email, last_name=last_name, first_name=first_name, user_type=2)
user.staffs.address = address
user.save()
messages.success(request, 'Staff Added Successfully')
return HttpResponseRedirect('/add_staff')
except:
messages.error(request, 'Failed to Add Staff')
return HttpResponseRedirect('/add_staff')
urls.py
path('add_staff/', add_staff),
path('add_staff_save/', add_staff_save),
add_staff.html
<form role="form" action="/add_staff_save">
{% csrf_token %}
<div class="card-body">
<div class="form-group">
<label>Email address</label>
<input type="email" class="form-control" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<!-- same for first_name, last_name, username, address -->
<div class="card-footer">
<button type="submit" class="btn btn-primary btn-block">Add Staff</button>
</div>
</div>
</form>
(2nd Method)
make a form in forms.py of all fields first_name, last_name, username, address
and then call in view and validate it.
forms.py
class StaffForm(forms.ModelForm):
class Meta:
model = Staff
fields = ('first_name', 'last_name', 'username', 'address')
views.py
def add_staff(request):
if request.method == 'POST':
form = StaffForm(data=request.POST)
if form.is_valid():
messages.success(request, 'Staff Added Successfully')
form.save()
else:
form = StaffForm()
return render(request, 'staff.html', {'form':form})
urls.py
path('add_staff/', add_staff),
staff.html
<form role="form" action="/">
{% csrf_token %}
{{ form.as_p }} <!-- render form as paragraph -->
</form>
Both methods work well and staff model have all the required field.
Sorry for long question since its getting too long I'm not adding staff model. If you need plz let me know.
of course the second method is much way better than the first one
because you should do cleaning and validation in other files like forms.py in each individual section
and also you can add more options and other things that maybe will be useful after a time
and you should be aware of that and predict some changes for improvement too!
and with making forms and use generics , you will write less code than doing it by yourself in hardcode in views.
so don't hesitate and choose method2
2nd method is better than 1st one. 2nd method give more flexibility you only have to make a form in forms.py and you can use it in different locations while for 1st method you have to use 2 urls just to show form and save it . Also you can use filters like crispy_forms_tags on form as {{ form|crispy }}. So obviously in long run 2nd method is better.

django the way to access data from input form

My symptom is when I click the modify button and then I write down the information on new window that is implemented by bootstrap div part. However, my database doesn't change at all. Please ignore ... in codes, I delete attributes that looks messy. Codes can have typo, because I wrote it down manually to find a bug, but I didn't find.
I tried in view.py, address_modify makes return Httpresponse(street), but It returned None.
view.py
def address_modify(request, adid):
cat = get_object_or_404(Address, adid=adid)
if request.method == "POST":
old_adid = adid
email = request.user.email
street = request.POST.get("street", None)
city = request.POST.get("city", None)
...
Address.objects.filter(adid=adid).update(..., street=street, city=city, state=state, ...)
return redirect('/address/')
return redirect('/address/')
template ( I name it address.html)
<button class="btn btn-success" data-toggle="modal" data-target="#modify">MODIFY</button>
<div class ="model fade" id="modify" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<from action="" method="POST">{% csrf_token %}
</div>
<div class="modal-body">
<input type="text" name="street">
<input type="text" name="city">
...
...
<input type="text" name="zipcode">
</div>
<div class="modal-footer">
<a href="{% url 'address_modify' i.adid %}">{% csrf_token %}
<button type="button" class="btn btn-primary">Save Change</button></a>
<div></form>
urls.py
url(r'^address_modify/(?P<adid>[0-9]+)/$', MyAppView.address_modify, name='address_modify'),
In django the best practice is to create a forms.py file to handle forms, its really easy you can read the doumentation on it, basically the form will ensure that all your data are read.
That is not how you implement form and form submit. Your link is not submitting anything, it's just opening a link. This is the standard form syntax:
<form method="POST">
{% csrf_token %}
... your form input fields here ...
<input type="submit" value="Save changes">
</form>
You must submit the form. Note type="submit" there.
Next to that, Django has forms feature. Use it. Create forms.py as #Saumel-Omole suggested. Form for model Address would look like this:
class AddressForm(forms.ModelForm):
class Meta:
model = Address
fields = '__all__'
Then you modify your view to use the form like:
def address_modify(request, adid):
cat = get_object_or_404(Address, adid=adid)
form = AddressForm(instance=cat)
if request.method == 'POST':
form = AddressForm(request.POST, instance=cat)
if form.is_valid():
form.save()
return redirect('/address/')
else:
print(form.errors) # change to logging
return render(request, 'address.html', {'form': form})
Go over the official Django tutorial. These basics are all there. Maybe it is going to take you a day or two to get through it, but long-term that's going to be far less than guessing and googling around for days for basic stuff.

Django Custom Template Form and {{next}}

I'm stuck on creating form, looks like {{ forms.as_p }}.
I need to login to website using this form. Uing forms.as_p it everything works perfectly, but I need to create my own customized form.
Problem is, that after reading lot's of website's and documentation I still can't understand, how to create custom form with my css class and input fields.
I tried this one:
action="", method ="post"
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" required="">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" required="">
</div>
<input type="submit" class="btn btn-primary block full-width m-b" value="Log In" />
But it doesn't work.
What fields, I've missed.
Also I have another question: Is it possible to custom "next" variable to redirect after login on my custom page? And how I can do it?
Normally you use your forms.py to create a form that you can use in your HTML-Code via Jinja.
Your forms.py could look like this:
from django import forms
class ProfileForm(forms.Form):
name = forms.CharField(label='Your name', max_length=100)
age = forms.IntegerField(label='Your age')
Then you would do some cleaning to make sure the data passed to the form has the right format.
def clean_name(self):
name = self.cleaned_data.get('name')
if not name:
raise forms.ValidationError('You have to type in a name.')
return name
In your views.py:
def some_view(request):
form = ProfileForm(request.POST or None)
if form.is_valid():
name = form.cleaned_data.get('name')
//do something with the name
user = User.objects.get(username=username)
user.username = name
user.save()
return redirect('to_profile_of_user')
return render(request, 'change_profile.html', {'form':form})
Here it is very important that you pass the form to your template(HTML).
Your change_profile.html:
<form action="" method="POST" enctype="multipart/form-data">
{{form.as_p}} //That is the form you passed
<input type="submit" value="Change" />
</form>
I hope my answer gives you a little bit of advice. Now you have seen a complete roundtrip. Maybe you should have a closer look at the Django documentation. It is very helpful.
The code is written on the fly and not tested. But it is enough for an overview. You should not forget to import the things you need. I did not do that.

Django CSRF verification failed. Request aborted

I have a model:
class Tour(models.Model):
owner_id = models.ForeignKey(User)
name = models.CharField(max_length=50)
location = models.ManyToManyField(Location)
subscribers = models.ManyToManyField(User, related_name="sub")
tour_date = models.DateField(null=True)
description = models.CharField(max_length=300, null=True)
And a template that includes this form:
<form method="post" action="/mytours/">
{% csrf_token %}
<input name="name" value="{{ name }}" class="pull-left" type="text" placeholder="Type the tour name... "></br>
<input name="tour_date" value="{{ tour_date }}" type="text" id="datepicker" placeholder="Pick a tour date..."/>
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</form>
And in my views I am trying to add to my database what is filled in the form:
if request.method == 'POST':
location = Location.objects.get(id=1)
name = request.POST.get('name', '')
tour_date = request.POST.get('tour_date', '')
tour = Tour()
tour.owner_id = user.pk
tour.name = name
tour.tour_date = tour_date
tour.location = location
tour.save()
c = {'name':name, 'tour_date':tour_date, 'tour':tour}
c.update(csrf(request))
return render_to_response("myTours.html", c)
I am new in django and I don't know where is the problem.
You're misunderstanding what to do with the CSRF token. You're creating it on POST, but the point is to create it for the original display of the form on the GET request. It is checked by the middleware on POST, so you don't need to add it there.
You should use the render call as recommended by surfeurX, but on the call that displays the form in the first place.
What I do when I implement forms in django is writing a form class and creating an instance of it in the view. Then pass the instance to the template.
# form class eg. in models.py
from django import forms
class TourForm(forms.Form):
name = forms.CharField(max_length=50)
# in the view
if request.method == 'POST':
form = TourForm(request.POST)
if form.is_valid():
# do your stuff here with form data
else:
form = TourForm() # An unbound form
return render(request, 'myTours.html', {
'form': form,
})
in your template you can display the generated form like this:
<form action="/mytours/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" class="btn btn-primary" />
</form>
for further information just look inside the official django forms documentation
You probably need to add django.middleware.csrf.CsrfViewMiddleware to MIDDLEWARE_CLASSES and add a RequestContext to your response:
return render_to_response("myTours.html", c, context_instance=RequestContext(request))
https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/
How do you render your template ??? I think your csrf_token doesn't print any hidden input, add "request" in your template context like:
return render(request, "template.html", {"var": var})
https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render