Custom django form that has fields populated from database - python

I am new to Django. I have a custom form that uses forms.Modelform to create a custom form from my model. I have some data in my database already that I manually input for testing.
However, the user and course field shows up as dropdowns. But they do not have any data in the dropdown list. How can I have django to pull data from the database and display the information into each dropdown on my form?
models.py:
class Student(models.Model):
user = models.OneToOneField(User)
course = models.ForeignKey(Course)
view.py:
def home(request):
if request.method == 'GET':
form = StudentForm()
else:
form = StudentForm(request.POST)
if form.is_valid():
pass
return render(request, "request.html", {'form': form}, context_instance=RequestContext(request))
forms.py:
class StudentForm(forms.ModelForm):
class Meta:
model = Student
Update
Actually found out that the changes weren't saved to my DB. They are now loading into the form. However in the dropdown list, it is showing up as "Student Object", and "Course Object"
How can I make it so they show up with proper names?

I would advocate that you move away from doing this if this is testing, and instead follow the guidelines for testing as outlined in the django tutorials, i.e. it creates a fake database for you and you create Users and Courses via Users.objects.create(username=...)

Related

Creating two different profiles in one application

I am building a BlogApp App and I have two different sections, One is Blog Section and another is Article Section.
AND i am trying to create two different profiles for them.
When a user register or signup then a Profile is successfully creating for Blog Section ( NOT Article section ). BUT i am trying to do :- When user click on Article section after signup then there will be option of creating another Profile for Article Section and both will be different profile. ( AND there will be no relation between Blog Profile and Article Profile BUT user will same )
Blog Profile is successfully creating BUT I am trying to make Article Profile.
models.py
class ArticleProfile(models.Model):
user = models.ForeignKey(User,default='',null=True,on_delete=models.CASCADE)
full_name = models.CharField(max_length=30,default='')
views.py
def create_profile(request):
if request.method == 'POST':
form = ArticleProfileForm(request.POST,request.FILES,instance=request.user)
if form.is_valid():
custom_form = form.save(False)
custom_form.save()
messages.success(request, "Article Profile is Created")
return redirect('dating:DatingSection')
else:
form = ArticleProfileForm(instance=request.user)
context = {'form':form}
return render(request, 'dating/create_profile.html', context)
BUT when i create profile using this form then it is not saving in Admin.
Any help would be Appreciated.
Thank You in Advance.
I think the problem is here:
form = ArticleProfileForm(request.POST,request.FILES,instance=request.user)
^^^^^^^^^^^^
You are passing User as instance where the ArticleProfileForm creates ArticleProfile instance. So you need to remove that part of the code. And update the code like this:
form = ArticleProfileForm(request.POST,request.FILES)
if form.is_valid():
custom_form = form.save(False)
custom_form.user = request.user # change here
custom_form.save()
If still the problem persists, try renderning the form errors to pin point what is exactly wrong here.

Django: Create a form for another other user existing in DB. ('Users' object has no attribute 'get')

I'm creating a cloud panel for our cloud Database, and I'm having some issues by creating a form for other users and rendering it.
This is my forms.py
from django.forms import ModelForm
from main.models import Users
class UsersForm(ModelForm):
class Meta:
model = Users
fields = '__all__'
exclude = ['last_login']
And then inside the views.py, I'm trying to create a form for other user with:
form = UsersForm(model)
return render(request, 'service_desk/ticket_list_edit.html', {'form': form})
I'm trying to pass in the user model to the form, but as you can see I'm getting an error

Save filled form data in Django if user is not logged in?

I search Django-way to do some non tipical feature (I think). My env is Django 2.0.2, PostgreSQL 9.6 and Python 3.6.4. So, I have model and form like:
# ./app/models.py
from users.models import User # custom user model
class SubscribeModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
phone = models.CharField(max_length=80)
# ./app/forms.py
class SubscribeForm(forms.Form):
phone = forms.EmailField(label='Phone Number', max_length=100)
Also, my view for this model like:
# ./app/views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from users.models import User
class SubscribeView(LoginRequiredMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to'
template_name = 'app/subscribe.html'
form_class = SubscribeForm
def post(self, request):
user = get_object_or_404(User, id=request.user.id)
form = self.form_class(request.POST, instance=user)
if form.is_valid():
form.save()
return redirect('/')
return render(request, self.template_name, {'client': user, 'form': form})
Would be great to understand what to do that logic after save form:
Anonymous user fill the form and click Save;
He is redirecting to login page (because LoginRequiredMixin);
After enter to the site, all data which he filled — saved to his account (automatically).
This feature we can see when online shopping: we choose goods, add to
our cart and only later, site ask us for login to site, if we are not (for save our order).
I think, my question solve saving data to request.session and re-save to DB after logged in, but I have no idea how to do that on my code and is this correctly? I am newbie in Django... yet!
Actually using request.session to store the data without saving it to the database is one approach, you can eighter save it to the localStorage or sessionStorage if you are developing mainly javascript AJAX frontent. But if you render every view with django then is using request.session better for you. Consider storing ids of the objects in the request.session in array and then use it as you want, remember to seralize it to JSON (json.dumps(list of ids)) before assigning it to the request.session.

Django Admin - Custom Inline Form

I'm attempting to use a custom inline form within the django admin.
admin.py --
class EmpInline(admin.StackedInline):
model = Emp
form = UpdateYearlyForm
show_change_link = True
class CompanyAdmin(admin.ModelAdmin):
list_display = ('companyname','companyid','get_active', 'get_updated')
inlines = [EmpInline]
When the Company name is clicked on, the company details are shown along with a formset for all the related employees.
This works in regards to displaying the form however one of the fields is a custom choice field which indirectly updated a model field. Which, in the normal user view (this form needs to be used both by an admin for all records and for users for the records pertaining to them) the custom field is handled as below.
I've only shown a snippet of the view as it is quite long.
views.py --
if formset.is_valid():
for form in formset.forms:
if form.is_valid():
obj = form.save(commit=False)
data = form.cleaned_data
if data['updatefield'] == 'accident':
obj.years += 1
else data['updatefield'] == 'free':
obj.years += 1
obj.save()
Is there a way of handling the form (and the custom field) in the same way when used as an inlineform in the admin?
If it helps anyone - overriding the save() function on the form itself sorted this problem and it probably better practice therefore I changed to using this on both the User and Admin side.

django newbie. Having trouble with ModelForm

i'm trying to write a very simple django app. I cant get it to show my form inside my template.
<form ...>
{{form.as_p}}
</form>
it shows absolutely nothing. If I add a submit button, it only shows that.
Do I have to declare a form object that inherits from forms.Form ? Cant it be done with ModelForms?
[UPDATE]Solved! (apologize for wasting your time)
In my urls file I had:
(r'login/$',direct_to_template, {'template':'register.html'}
Switched to:
(r'login/$','portal.views.register')
And yes, I feel terrible.
Background:
I have a Student model, and I have a registration page. When it is accessed, it should display a textfield asking for students name. If the student completes that field, then it saves it.
#models.py
class Student(models.Model):
name = models.CharField(max_length =50)
#forms.py
class StudentForm (forms.ModelForm):
class Meta:
model = Student
So, here is my view:
def register(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
return render_to_response('/thanks/')
else:
student = Student()
form = StudentForm(instance =student)
return render_to_response('register.html',{'form':form})
The problem is in your view. You will have no existing student object to retrieve from the database. The following code sample will help you implement an "create" view.
As a side note, you might like using the direct_to_template generic view function to make your life a bit easier.
def add_student(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
new_student = form.save()
return HttpResponseRedirect('/back/to/somewhere/on/success/')
else:
form = StudentForm()
return direct_to_template(request,
'register.html',
{'form':form})

Categories

Resources