Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Styling an .IntegerField() to make it a star-rating system?
My ultimate end-goal is to get a 5-star rating system going for my website in Django. I am approaching it with a form that is linked to my model. Here's the model for my review: class review(models.Model): ONE_TO_FIVE_RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) BOOK_RATING_CHOICES = ( (1, '$'), (2, '$$'), (3, '$$$'), (4, '$$$$'), ) ATTENDANCE_RATING_CHOICES = ( (1, 'Not Required'), (2, 'Required'), ) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=0) course = models.ForeignKey(listing) slug = models.SlugField(unique=True, default=None) pub_date = models.DateTimeField('date published') user_name = models.CharField(max_length=100) title = models.CharField(max_length=140) review_content = models.TextField() difficulty_rating = models.IntegerField(choices=ONE_TO_FIVE_RATING_CHOICES) workload_rating = models.IntegerField(choices=ONE_TO_FIVE_RATING_CHOICES) book_rating = models.IntegerField(choices=BOOK_RATING_CHOICES) attendance_rating = models.IntegerField(choices=ATTENDANCE_RATING_CHOICES) And here's the form: class ReviewForm(forms.ModelForm): class Meta: model = review fields = [ 'difficulty_rating', 'workload_rating', 'book_rating', 'attendance_rating', 'title', 'review_content', ] My question is, how do I style this with CSS? I want to transform this into radio inputs that I can then cover with star icons (from FontAwesome) and still retain the functionality of being able to send these inputs to my database. Is there an easy way? Or is this a difficult thing? -
extend a user profile in django to include profile photo
I am trying to extend a user profile in django so that user can add profile photo and birthday date and I am using django-allauth for my user authentication. I am currently following a reference but for the reference a new user registration was used without involving django-allauth. I have thus implemented the codes but stock on one point where I can not figure out where to place this particular line of code # Create the user profile profile = Profile.objects.create(user=new_user) below is the profile Edit code Model class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField( upload_to= upload_location, null = True, blank = True, height_field = "height_field", width_field = "width_field") def __str__(self): return 'Profile for user {}'.format(self.user.username) Form.py class UserEditForm(forms.ModelForm): username = forms.CharField(required=True) email = forms.EmailField(required=True) first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email'] class ProfileEditForm(forms.ModelForm): """docstring for ProfileEditForm.""" class Meta: model = Profile fields = ['date_of_birth', 'photo'] View def edit(request): if request.method == 'POST': user_form = UserEditForm(instance = request.user, data = request.POST) profile_form = ProfileEditForm(instance = request.user.profile, data = request.POST, files = request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() else: user_form = UserEditForm(instance= request.user) profile_form = … -
DJango Models & Apps
Good afternoon, I am new to Django and having trouble conceptualizing how to lay out some of my apps in a project. I get the obvious apps for "ActivityTracking" & "GameStats" Where I am struggling is the glue that ties all of this together - the Person. I was helped yesterday on importing the Person model into apps to use a Foreign Key of the models (Using DJango Models across Apps) but I am struggling at where to put my PersonModel (what app?) There are three scenarios in my app. The AppAdmin who will create / delete / import / move between departments of users (among other items of overall administration such as onboarding data sources). A particular user will be able to manage his own Person object to update information and see his/her own statistics, and a team leader will be able to see his departments performance. Where would this Person model go to appropriately be positioned for these three use cases? Sorry if I am not asking this well, but I am having a hard to conceptualizing where to place this central piece of the overall application. Thank you for your insight. -
How can you grab user input on a search and "append" it on the end of an HTM url in <a> tags?
So I have a basic search functionality using Django and HTML. <input type="text" name="searchterms" id="pubsearch" style="width: 90%"/> <br> <input type="submit" value="Search"/> I want to take the searchterms and append it to the end of a pagination URL which the user has the option to click, specifically where I've written the word "HERE". {% if pubs.has_next %} <a href="?page={{ pubs.next_page_number }}&&searchterms= HERE ">next</a> {% endif %} How does one go about doing this? Do I need to catch the user input variable in javascript and then pass it along? Not sure how to go about it, any help would be appreciated. Thank you! -
Django Permisos en un template personalizado
Español: Hola buen día mi inquietud es la siguiente me gustaría saber como realizar un formulario el cual contenga los permisos algo similar a lo del panel admin pero en una template plantilla personalizada algo como un picklist. Gracias Ingles : Hello, my question is the following I would like to know how to make a form which contains the permissions something similar to the admin panel but in a custom template, something like a picklist. Thank you -
Django accepting Chinese pseudo letters in email fields
There is a set of letters (A-Za-z), which Chinese users sometimes input where we expect ascii letters - but those are actually special characters defined in Unicode. Take a look at this sample email address: from django.core.validators import validate_email email = u'dummy@raysfirst.com' try: validate_email(email) except ValidationError as e: print "oops! wrong email" else: print "hooray! email is valid" Sure, we can read the address. However, such an email address makes a lot of trouble in various scenarios. Typical email servers appear not to be able to handle such characters. Is this a Django bug? What's the best way to detect such letters in Python? Or better even, is there a flag for Django in order to forbid such letters in validate_email? -
django haystack with elasticsearch - Searchqueryset not found
I've implemented search in my django project with haystack and elastic search. But searching with with a string across a Model that has a GenericForeignKey. For the model I've used index_queryset in search index that filters w.r.t to a field.And the rebuild index can be seen indexing only the filtered count. But when search happens the Haystack queryset shows: Object could not be found in database for SearchResult SearchResult: xxxxx.xxxxxx (pk=u'218933') The above mentioned id was not actually indexed.But haystack has it in it's query. django==1.10 haystack =2.6 aws elasticsearch == 2.3 With reference to https://github.com/django-haystack/django-haystack/issues/932, this can be a case of nodes being out of sync. Will this arise in aws elasticsearch. Please help. Thanks. -
Improperly Configured database backend django and mysql
I've just cloned a repo and when I try to run my python app I get the following error: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/Library/Python/2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Python/2.7/site-packages/django/core/checks/model_checks.py", line 28, in check_all_models errors.extend(model.check(**kwargs)) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 1172, in check errors.extend(cls._check_long_column_names()) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 1587, in _check_long_column_names connection = connections[db] File "/Library/Python/2.7/site-packages/django/db/utils.py", line 212, in __getitem__ backend = load_backend(db['ENGINE']) File "/Library/Python/2.7/site-packages/django/db/utils.py", line 135, in load_backend raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: No module named sql_server.pyodbc.base I'm not sure what I've missed setting this up. I'v checked on mysql and the database exists in there mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | mydb | | sys | +--------------------+ 5 rows in set (0.00 sec) And my settings file looks like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydb', 'USER': 'dbuser', 'PASSWORD': 'dbpassword', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS' : { 'sql_mode': 'ANSI', "init_command": "SET … -
Django No Reverse Match Error
I've been working on this error for the better part of a week and I am giving up. I'm trying to learn Django, but not new to programming. This is the error I keep receiving: NoReverseMatch at /practice/practice/1 Reverse for 'car_edit' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['practice/practice/(?P\d)/edit/$'] I've simplified the code to what are the relevant parts of the error, I think. The idea is to have a list page of cars and when you click on the car link you can edit the Sale History of the vehicle. Eventually I'll setup formsets for this part, but babysteps. Here's the relevant code: models.py class Car(models.Model): car_name = models.CharField(max_length=200) color = models.CharField(max_length=200) age = models.CharField(max_length=200) def get_asbolute_url(self): return reverse('practice:car_detail',kwargs={'pk':self.pk}) def __str__(self): return '%s' %(self.car_name) class SaleInfo(models.Model): car_name = models.ForeignKey(Car, on_delete=models.CASCADE,) price = models.CharField(max_length=100) date = models.CharField(max_length=100) comments = models.CharField(max_length=200) def __str__(self): return '%s' %(self.car_name) def get_absolute_url(self): return reverse('practice:car_detail',kwargs={'pk':self.pk}) views.py class IndexView(generic.ListView): template_name = 'practice/carlist.html' context_object_name = 'latest_car_list' def get_queryset(self): return Car.objects.all() class DetailView(generic.DetailView): model = Car form_class = CarForm template_name = 'practice/car_detail.html' class UpdateView(generic.UpdateView): model = Car form_class = CarFormEdit class SaleInfoUpdateView(generic.UpdateView): model = SaleInfo form_class = SaleInfoFormEdit template_name = 'practice/saleinfo_form.html' urls.py urlpatterns = [ url(r'^$', … -
Django. TemplateDoesNotExist in case of a custom widget
I'm trying to create a custom widget in Django admin. I created a class: class FroalaWYSIWYGTextareaWidget(django.forms.widgets.Textarea): template_name = 'froala_wysiwyg.html' Then a simple model form: class ArticleForm(django.forms.ModelForm): class Meta: fields = '__all__' model = Article widgets = { 'content': FroalaWYSIWYGTextareaWidget(), } Here are my settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_PATH, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.i18n', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Usualy everything works fine and Django can find templates in my /templates/ directory but in case of this widget I have a 500 Error: TemplateDoesNotExist at /admin/article/article/1/change/ froala_wysiwyg.html Request Method: GET Request URL: http://127.0.0.1:8000/admin/article/article/1/change/ Django Version: 1.11.4 Exception Type: TemplateDoesNotExist Exception Value: froala_wysiwyg.html Exception Location: /home/username/.virtualenvs/sitename/lib/python3.5/site-packages/django/template/engine.py in find_template, line 148 Python Executable: /home/username/.virtualenvs/sitename/bin/python Python Version: 3.5.2 I debugged django.filesystem.loader and found out that usually Loader.engine.dirs is a list: ['/home/username/python/sitename/templates'] so Loader.get_template_sources() works great but in case of this custom widget this loader.engine.dirs contains only: ['/home/username/.virtualenvs/sitename/lib/python3.5/site-packages/django/forms/templates'] So it just ignores DIRS option from settings and uses forms/templates instead. Is it a bug of Django or I have to change something in settings? Thanks. -
How can I allow a user to filter models dynamically and export only certain fields?
I've been asked to design a way for people to search through multiple models on criteria they enter and allow them to export any number of fields they select. Example: User enters "Teacher" as a term for Job Title and "Google" for a Work Site Location but want to export "Employee ID", "First Name", "Last Name", "Date of Birth" I'm sure this is possible, but I'm at a complete loss for where to start. My models (for reference) are here: import datetime from django.conf import settings from django.db import models from django.db.models import Q from django.utils import timezone class Classification(models.Model): name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Classification Name') def __str__(self): return '{}'.format(self.name) class Meta: db_table = 'Classification' verbose_name = 'Classification' verbose_name_plural = 'Classifications' class Location(models.Model): name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Name') aeries_id = models.CharField(max_length=25, blank=True, null=True, verbose_name='Aeries ID') county_id = models.CharField(max_length=25, blank=True, null=True, verbose_name='County ID') def __str__(self): return '{}'.format(self.name) class Meta: db_table = 'Location' verbose_name = 'Location' verbose_name_plural = 'Locations' ordering = ['name'] class Person(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) current_identity = models.ForeignKey('PersonIdentity', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Current Identity', related_name='current_identity') employee_id = models.CharField(max_length=255, null=False, blank=False, verbose_name='Employee ID') birthdate = models.DateField(blank=True, null=True, verbose_name='Birthdate') original_hire_date = models.DateField(blank=True, null=True, verbose_name='Original Hire Date') def __str__(self): … -
Django User Management: how to avoid that each user sees content and data from other users?
In my small Django project, users can sign up and by filling in some ModelForms they can populate the existing Models with their own data. The problem is that upon logging in, any user can see not only their own data, but also the data created by other users. I need to avoid that. Every user should be able to see, modify and interact exclusively with their own data. Every Model has the attribute user which is a ForeignKey linked to User. Am I possibly missing something in the views? They're just class based views that do no refer to User, they just have the LoginRequiredMixin decorator. For the login views I'm using Django standard, and for register view I have created a UserFormView. #register page url(r'^register/$', views.UserFormView.as_view(), name='register'), #login page url(r'^accounts/login/$', auth_views.LoginView.as_view(), name='login'), Is there a correct procedure to be implemented to keep each user separated from the others? Thank you in advance for the help. -
Text appearing under svg in Django
I'm trying to get an SVG (in an object element) to sit within a button element. However, I think there may be something wrong with my code, in that the image has text from my code underneath it. In the included screenshot, " height="50px"> is included under the image. However, if I remove that part of the code, the image goes back to its original size, meaning the code actually is doing what it is intended to do, but with this weird unintended consequence. The relevant code is below, as is a screenshot of how the SVG loads right now. <button id="Button2" class="OrangeButton"><object type="image/svg+xml" data="{% include "Enterprise/BillAuditingIcon.svg" %}" height="50px"></object></button> SVG Image Error Thanks! -
Django reports referer or CSRF checking error but lets user in
I am quite new to Django, and have just started writing my first tests, and I fail to understand the situation I've discovered. My site has a login page, which makes use of CSRF token: <form id="login-form" method="post" action="/login"> <input type='hidden' name='csrfmiddlewaretoken' value='2QXxnB5yTqOnEdsFVwgWfCbBam6JOvl49mnXk29mBgxVP1tvf7VWy0VvxzYtR3OT' /> <table> <tr> <td><input id="id_username" name="username" type="text"></td> </tr> <tr> <td><input id="id_password" name="password" type="password"></td> </tr> <tr><td colspan="2"> <input type="submit" value="Enter" class="btn" /> <input type="hidden" name="next" value="/home" /> </td></tr> </table> </form> This form works fine. Without passing it I cannot access "secret" data, after login I can access it. In my tests, I have created a login() function, used to test access to restricted access data. def login(self): url = PRFX + '/login' login_data = {'username': settings.TEST_USERNAME, 'password': settings.TEST_PASSWORD} headers = {'referer': url} r = self.session.post(url, data=login_data, headers=headers) self.assertEqual(r.status_code, 200) return r Here starts the interesting part. Although the CSRF token is not passed in this function, it still works fine: my site tells me the test user is logged in (I get an email about it, and Axes logs every login event). I do get an email about the CSRF verification error: [Django] WARNING (EXTERNAL IP): Forbidden (CSRF token missing or incorrect.): /login but the site still allows … -
ModelForm Django 1.11 overwrite error messages
How can I overwrite the default form error messages in ModelForm in Django 1.11, Such as 'Enter a valid value.' or something like that? In the official documentation has this example, but it does not show how to override other types of error messages than this one. https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#validation-on-a-modelform from django.forms import ModelForm from django.core.exceptions import NON_FIELD_ERRORS class ArticleForm(ModelForm): class Meta: error_messages = { NON_FIELD_ERRORS: { 'unique_together': "%(model_name)s's %(field_labels)s are not unique.", } } -
Django Rest Framework does not show content from StreamField
I have a model class with ModelChooserBlock inside StreamField and If I open my Django Rest Framework I don't get a satisfactory result. Specifically "Ingredient" should have a link to ingredients or directly Database. HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "id": 1, "meta": { "type": "cultinadb.Menu", "detail_url": "http://127.0.0.1:8000/api/v2/menu/1/" }, "title": "", "Ingredient": [ { "type": "zutaten", "value": 2, "id": "647d762f-ec26-4c78-928a-446344b1cb8a" }, { "type": "zutaten", "value": 1, "id": "6ab4e425-5e75-4ec0-ba63-8e7899af95e2" } ], } Here is my model: from django.db import models from wagtail.api import APIField from wagtailmodelchooser import register_model_chooser from wagtailmodelchooser.blocks import ModelChooserBlock @register_model_chooser class Ingredient(models.Model): name = models.CharField(max_length=255) picture_url = models.URLField(blank=True) translate_url = models.URLField(blank=True) def __str__(self): return self.name @register_model_chooser class Menu(models.Model): Ingredient = StreamField([ ('zutaten', ModelChooserBlock('kitchen.Ingredient')) ], null=True, verbose_name='', blank=True) panels = [ MultiFieldPanel( [ StreamFieldPanel('Ingredient') ], heading="Zutaten", classname="col5" ), ] def __str__(self): return self.title api_fields = [ APIField('Ingredient'), ] I tried to add it as shown here with serializer, but then I got errors. I created serializer.py and added this code class MenuRenditionField(Field): def get_attribute(self, instance): return instance def to_representation(self, menu): return OrderedDict([ ('title', menu.Ingredient.name), ('imageurl', menu.Ingredient.picture_url), ('imageurl', menu.Ingredient.translate_url), ]) Then i changed my api_fields like this api_fields = [ APIField('Ingredient', serializer=MenuRenditionField()), ] The … -
Django Auth Views Password Reset URL
I using Django Password reset in my project. I have and namespace called "users" and inside this app (yes, it an app too), I build my urls. But when I use Django Password Reset of auth_views, they send a url like this: http://localhost:8000/auth/reset/NA/4ou-XXXXXXXXXXXXXX/ But my reset url is like this: http://localhost:8000/users/reset/NA/4ou-XXXXXXXXXXXXXX/ How I change URL of Django Auth Views? -
How can I change a null=True field to a null=False field if it already has null values in some places?
django.db.utils.OperationalError: cannot ALTER TABLE "news_article" because it has pending trigger events So, I have the following problem: I have a Django class, Article, which contains several Char- and TextFields. They were set to blank=True AND null=True which is... unfortunate. Oh well, no I need to fix that. So after I deleted null=True and set default='', I wrote the following thing into my migration: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import languagefields.utils from languagefields.utils import LANGUAGES from django.utils.translation import activate from news.models import Article def null_migrations(apps, schema_editor): activate('en') fields = ['short_title', 'description'] for p in Article.objects.all(): for l in LANGUAGES: for f in fields: if p.get_language(l, f) is None: p.set_localized(l, f, '') p.save() class Migration(migrations.Migration): dependencies = [ ('news', '0001_initial'), ] operations = [ migrations.RunPython(null_migrations), migrations.AlterField(.... The fields are custom fields, based on the default Char-/TextFields, which enable translation. So there is a bunch of them. For every field you create there will be 5, a description in english, german and so on... So yeah, the little function works fine, I ran it on the server and cleaned the db entries manually, but that doesn't stop the exception above. So I thought I'd … -
django rest framework two different modelserializers in one viewset
I want show two different models data in one viewset. ex. class A(models.Model): name = models.TextField() class B(models.Model): description = models.TextField() class ASerializers(serializers.ModelSerializer): class Meta: model = A fields = ['name'] class BSerializers(serializers.ModelSerializer): class Meta: model = B fields = ['description'] class ABViewSet(viewsets.ReadOnlyModelViewSet): """ This view-set contains all APIs related to a booking. """ queryset = A.objects.filter(active=True) # I want queryset objects for both modelel serializer_class = [ASerializers, BSerializers] is there any way to have multiple modelserializres in one viewset. I want output like "results": [ "a_data" : [{ "name": "abc", }, { "name": "pqr", } ], "b_data" : [{ "description": "abcdesc", }, { "description": "pqrdesc", } ] ] I want this type of output in one viewset only. Any help would be appreciated. -
Can you explain social auth flow? (Django)
Social Auth in all-auth is not clear to me. And I'm seeking for an explanation of its overall flow. I'm building my Django RESTful Framework to retrieve and post data for Mobile. I'm using djang-rest-auth (which is just all-auth with RESTful functionality; more info: http://django-rest-auth.readthedocs.io/en/latest/). Use Case 1: Unregistered User User Login with Facebook on Mobile Mobile gets facebook token from Facebook SDK Mobile sends token to our DRF Backend server URL which is '/rest-auth/facebook' And what happens? Can you complete this Use Case? <- This is my question My guess (I may delete these once you answer): all-auth automatically create new user for facebook user token and return new token? Then, it saves created user to settings.AUTH_USER_MODEL? Or...? I found 'social account' in Django admin. Are we saving User in this account..? -
Does django automatically set primary key?
Does django automatically set primary key for models it creates first? Tell me answer in Yes or No. -
Django processing
Set up a webhook with a telegraph. All is well received answers, the bot responds, but it takes one hour or less, in idle time, after a regular bot command, it recreates the processes. log -
dealing with forms same data django python
I have a trouble with forms. I am creating a booking reservation for hotels in django. For example i have a hotel that has 2 type of rooms. In a template i have two forms for each room, depending on rate (standart rate and discounted rate). The client can select a qty of room desired from a select html. Two things: The forms are made directly in template, because the inputs hidden have to take values renderized in the template, and i need to treat each block of code from input name="hotel" to select name="qty" as separated forms, because when the client select a qty 3 for example in one form, i need to take the corresponding rate. Can you give please any idea of how make this? <form method="POST"> <input type="hidden" name="hotel" value="{{ hotel.id }}" > <input type="hidden" name="room" value="{{ room.id }}" > <input type="hidden" name="rate" value="743.80" > <select name="qty"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> </select> <input type="hidden" name="hotel" value="{{ hotel.id }}" > <input type="hidden" name="room" value="{{ room.id }}" > <input type="hidden" name="rate" value="669.32" > <select name="qty"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> </select> <input type="submit" value="Enviar"> </form> -
Implement a multi-part 5 star rating system in Django 1.11
I'm totally new to Stack Overflow and pretty new to Django/Python. I don't have much background in coding (started learning python less than a month ago) but I wanted to learn it and give it a try. I know HTML and CSS enough to get what I want done, but Python/Django, that's still uncharted territory for me. So far, I have a pretty basic website, and I'm trying to implement a multi-part 5-star rating system that's customizable and works with my database. So here's my model: class listing(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length = 100, default="Class Title") slug = models.SlugField(unique=True) draft = models.BooleanField(default=False) publish = models.DateField(auto_now=False, auto_now_add=False) description = models.TextField(default="Class Description") prerequisite = models.TextField(default="Class Prerequisites") university = models.CharField(max_length = 100, default="Choose A University") department = models.CharField(max_length = 100, default="Choose A Department") last_updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) image = models.FileField( upload_to=upload_location, null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("listings:detail", kwargs={"slug": self.slug}) Basically, I want to have the ability to give users the option to rate each individual class based on 4 custom criteria that I define. So for example, difficulty_rating, workload_rating, book_rating, attendance_rating. I would ideally like to have this done where the user … -
Save formset in an UpdateView
I have the models Entry and Meaning below with many-to-many relation. I need to create an update form/view to edit Entry and Meaning objects at the same time. I have also to be able to add more Meaning objects to an Entry object while editing it. I tried to use UpdateView and modelformset_factory as below. I can see the forms, but my view doesn't save the Meaning changes. I have two questions: How do I save the Meaning changes? How do I add or delete a Meaning object in this form/view? Models class Entry(models.Model): title = models.CharField(max_length=70) slug = models.SlugField('slug', max_length=100, unique=True) class Meaning(models.Model): title = models.CharField(max_length=70) language = models.CharField(max_length=5, choices=LANGUAGE_CHOICES) entry = models.ManyToManyField( Entry, related_name='meaning', related_query_name='meanings', through='MeaningRelation') class MeaningRelation(models.Model): entry = models.ForeignKey(Entry, on_delete=models.CASCADE) meaning = models.ForeignKey(Meaning, on_delete=models.CASCADE) Forms class EntryForm(forms.ModelForm): class Meta: model = models.Entry fields = ['title', 'slug'] MeaningFormSet = modelformset_factory(models.Meaning, fields=('title', 'language')) View class EntryUpdateView(UpdateView): model = models.Entry form_class = forms.EntryForm formset_class = forms.MeaningFormSet template_name = 'edit.html' def get_context_data(self, **kwargs): context = super(EntryUpdateView, self).get_context_data(**kwargs) qs = models.Meaning.objects.filter(entry=self.get_object()) formset = forms.MeaningFormSet(queryset=qs) context['meaning_formset'] = formset return context Template # edit.html <form action="" method="post"> {% csrf_token %} {{ form.as_table }} {{ meaning_formset.management_form }} {% for meaning_form in meaning_formset %} {{ …