Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I convert python's datetime.utcnow() to Javascript's Date.UTC?
I want to pass date value from Django View ( Python ) to Django template in which I'm using Javascript: Python: my_date = datetime.utcnow() <-- output: 2019-11-12 18:23:30.239216 Javascript: var date = new Date( Date.UTC( {{ my_date }} ) ); Tried this: my_date= my_date.strftime( '%Y, %m, %d' ) <-- this doesn't work correctly since Date.UTC expects month index not month number How can I make the conversion and why Javascript method is using month index and not the number of the month which is more natural ? -
How to open webcam in browser using django?
I am working on a project in django where I need to create a training set of face images of the users when they register to the site. Now I want to open webcam in browser to detect face and capture them so that I can process the further. I want to open webcam in browser so that I can capture users faces. -
Error "__init__() got an unexpected keyword argument 'tcp_nodelay'" on python 2.7
I am here again guys, I am running a django app on MacOS and when I star the server everything goes well but when I try to access to http://127.0.0.1:8000/admin/login/?next=/admin/ I got: __init__() got an unexpected keyword argument 'tcp_nodelay' Request Method: POST Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 1.11 Exception Type: TypeError Exception Value: __init__() got an unexpected keyword argument 'tcp_nodelay' I am using python 2.7 and Django 1.11 I tried recreating my virtualenv but it didn't work -
Django password reset flow without UIDB64
A team at our company is working on a new app. This app will consist of a javascript frontend and a Django backend (using graphql to communicate between the two). I am working on the Django backend and I'm the sole backend developer of the project. We are currently working on the 'reset_password' functionality, which will follow the familiar pattern of clicking a button, receiving an email with a password reset link that will lead to the an 'reset_password' form. Though the frontend will render all of the forms, it's the backend thats handling the logic. The code that I've written is borrowing heavily from the default django.contrib.auth views / forms. The link in the email consists both of an token (created with a PasswordResetTokenGenerator().make_token(user) call) and a uid (created with a urlsafe_base64_encode(force_bytes(user.pk)) call). However, my frontend colleagues asked me if it would be possible to forgo using the uid (of any other fields that can be used to identify the user) and instead 'work backwards' from the token to the user. Now I know that the token is generated with the user (as its provided as an argument in the create token call: PasswordResetTokenGenerator().make_token(user)) But so far it seems … -
Fetch results based on drop down values in a form
I am new to Django/Python and creating a self-learning project I have a page with 5 different input select fields 1. brand 2. Model 3. Mileage 4. Price_Range 6.Year_of_Make I have a model called Products with all the fields above. My html has following fields <div class="form-group"> <select class="form-control from-control-sm" id="body" name="bodystyle" value="{{ request.Get.bodystyle }}"> <option>Body</option> <option>Compact</option> <option>Convertible</option> <option>Coupe</option> <option>Off-road</option> <option>Sedan</option> </select> </div> <div class="form-group"> <select class="form-control" id="product_make" name="product_make" value="{{ request.Get.product_make }}"> <option>Ford</option> <option>Tata</option> <option>Hyundai</option> <option>Kia</option> <option>Honda</option> <option>Skoda</option> </select> </div> Here is my views.py from django.shortcuts import render from products.models import Products from django.db.models import Q # Create your views here. def select(request): q1 = request.GET.get('product_make') q2 = request.GET.get('model_name') q3 = request.GET.get('bodystyle') cars = Products.object.filter(Q(bodystyle__icontains=q3)&Q(product_make__icontains=q1)&Q(model_name__icontains=q2)) return render(request, 'search/search.html', {'cars': cars}) When I click on the Enter Button: The URL changes to http://127.0.0.1:8000/select/?bodystyle=Sedan&product_make=Ford but no result is displayed. My urls.py from django.conf.urls import url from django.contrib import admin from pages.views import home_view from search.views import search from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', home_view, name='home'), url(r'^home/', home_view, name='home'), url(r'^search/', search, name='search'), url(r'^select/', search, name='select'), url('ajax/home_view/',home_view, name='ajax_load_models'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I want {% for item in cars %} to be populated so I can show results. -
Find a string in the entire table (all fields, all columns, all rows) in Django
I have a module (table) in my Django app with 24 fields (columns), and I want to search a string in it. I want to see a list that show me which one of the rows has this string in its fields. Please have a look at this example: +-----+------+------+---------+------------+------------+------------+-----+-------------+ | id | name | year | country | attribute1 | attribute2 | attribute3 | ... | attribute20 | +-----+------+------+---------+------------+------------+------------+-----+-------------+ | 1 | Tie | 1993 | USA | Bond | Busy | Busy | ... | Free | +-----+------+------+---------+------------+------------+------------+-----+-------------+ | 2 | Ness | 1980 | Germany | Free | Busy | Both | ... | Busy | +-----+------+------+---------+------------+------------+------------+-----+-------------+ | 3 | Both | 1992 | Sweden | Free | Free | Free | ... | Busy | +-----+------+------+---------+------------+------------+------------+-----+-------------+ | ... | ... | ... | ... | ... | ... | ... | ... | ... | +-----+------+------+---------+------------+------------+------------+-----+-------------+ | 24 | Lex | 2001 | Russia | Busy | Free | Free | ... | Both | +-----+------+------+---------+------------+------------+------------+-----+-------------+ What I am looking to get (by using filters, etc.) is something like this: (When I filter the records base on the word "Both" in the entire table and all … -
Invalid variable in HTML page
I want to program a specific layout for a survey: On the left side the questions, on the right side 5 possible choices to "pick" (they are all normalized, so ranging from "I strongly agree" to "I strongly disagree". This is part of my code Models.py: from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range ) import random def make_field_5point(label): return models.IntegerField( choices=[ [1, ''], [2, ''], [3, ''], [4, ''], [5, '']], label=label, widget=widgets.RadioSelect, blank=False ) def make_field_5point_reversed(label): return models.IntegerField( choices=[ [5, ''], [4, ''], [3, ''], [2, ''], [1, '']], label=label, widget=widgets.RadioSelect, blank=False ) class Constants(BaseConstants): name_in_url = 'survey' players_per_group = None num_rounds = 1 class Player(BasePlayer): Con1 = make_field_5point('works in-depth') Ext1 = make_field_5point('is communicative, sociable') The questions are in Class Player(BasePlayer) Pages.py: from django import forms import random from random import shuffle from ._builtin import Page, WaitPage from .models import Constants class StartSurvey(Page): pass class Personality(Page): form_model = 'player' form_fields = ['Con1', 'Ext1'] def get_form_fields(self): fields = self.form_fields random.shuffle(fields) class End(Page): pass return fields page_sequence = [ StartSurvey, Personality, End,] HTML {% extends "global/Page.html" %} {% load otree static %} {% block title %} {% endblock %} {% block content %} Please … -
Django project , Convert color image to Black & white
I Want to make a project using Django, Project is to convert color-image to Black&White. Firstly, I want to upload an image through an HTML(upload.html) page that image will be stored in the System(Django media file) after that, Open that image and perform an operation to convert that image in B&W. After converting image Want to show that image in HTML(show_image.html) page. How can I make this project give an idea? -
How to bind start of Django server to button in VS Code?
When debugging Django project I can start the server by one click. There is a button "Run Python File in Terminal" (green "play" button), but it runs only one file. In this topic only python manage.py runserver command is mentioned. Could I config "Run Python File in Terminal" to start a server or start it by one click another way? I know that it's possible to use up arrow + enter in terminal, but it's not comfortable for me. -
Django, Iterate over OnetoMany relationships
I am trying to get all data for a specific row in a mysql table, all data from related tables associated with that rows data (via foreignkey, manytoone and onetomany) and also iterate over those related rows I have a mysql database of about 100 tables. I am starting with one identifier "activity_id" in a table "activites" and am trying to find all data associated with that activity_id. There is data for that activity_id in the activities table and also in tables that are related via the activity_id and also related through other fields in the activities table. These relationships are ManytoOne and OnetoMany (reverse ManytoOne). The model file is already set up and defines these relationships. The attached script is capable of iterating over all of the ManytoOne relationships, but does not pull out the data in the reverse direction (OnetoMany). def serialize(x): a = [] def serial_model(modelobj): opts = modelobj._meta.fields key = (modelobj._meta.db_table) modeldict = model_to_dict(modelobj) value = modeldict.copy() a.append({key:value}) for m in opts: if m.is_relation: foreignkey = getattr(modelobj, m.name) if foreignkey: try: modeldict[m.name] = serial_model(foreignkey) except: pass serial_model(x) b = [i for n, i in enumerate(a) if i not in a[n + 1:]] return(b) where x is … -
VueJs page gives 404 on refresh with django
I build VueJs app and copy all static files to django static folder and copy vuejs index.html to django templates folder but when refresh page it raise 404 here is my index.html <!DOCTYPE html> <html> <head> <meta charset=utf-8> <title>FMS</title> <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name=viewport> <link rel=stylesheet href=https://use.fontawesome.com/releases/v5.8.1/css/all.css integrity=sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf crossorigin=anonymous> <link href=https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css rel=stylesheet> <link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css> <link rel=stylesheet href=https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css integrity=sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u crossorigin=anonymous> <head> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel=stylesheet> <link href="{% static "/css/app.6c7cbd2b6c8e41a0245180734aee4192.css" %}" rel=stylesheet> </head> </head> <script src=/socket.io/socket.io.js></script> <body class="skin-blue sidebar-mini"> <div id=app></div> <script>if (window.navigator.userAgent.indexOf("Edge") > -1) { window.fetch = undefined; }</script> <script type=text/javascript src=./src/main.js></script> <script src=https://code.jquery.com/jquery-3.3.1.slim.min.js integrity=sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo crossorigin=anonymous></script> <script src=https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js integrity=sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1 crossorigin=anonymous></script> <script src=https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js integrity=sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa crossorigin=anonymous></script> <script src=https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js></script> <script src=https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.2/socket.io.js></script> <script type=text/javascript src="{% static "/js/manifest.e9739da6f5c27d585419.js" %}"></script> <script type=text/javascript src="{% static "/js/vendor.7deff2a26292e503ec19.js" %}"></script> <script type=text/javascript src="{% static "/js/app.bc1afe162faeb2a6bfa3.js" %}"></script> </body> </html> -
Read large XMLTYPE column in Django
I'm trying to create a custom XML model field in Django 2.2. My backend is Oracle 12c. The python-oracle driver cx_Oracle 7.2 can only read XML less than 4k. For such records I can get the XML with no problems using a models.TextField field in my model. BUT for records with XML greater than 4k I get ORA-19011: Character string buffer too small. How can I write a custom field that applies a database function like XMLTYPE.GETCLOBVAL() to the XML column? Using an annotation won't work because I will still get the ORA-19011 error on the original column. Thanks for your help! -
How to query across schemas with Django?
I have many schemas in my postgres database. I want to get a queryset across all of my schemas (UNION ALL). I'm using Django 2.2 , python 3.6 and postgres 9.7. I've tried to define a specific DBManager like: class UnionManager(models.Manager): def get_queryset(self): return super().get_queryset().using("db1") | super().get_queryset().using("db2") class Account(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) label = models.CharField(max_length=100, null=True) objects = models.Manager() union_manager = UnionManager() and with the following database configuration : config = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'databasename', 'USER': bdd_user, 'PASSWORD': db_pwd, 'PORT': bdd_port, 'HOST': host_writer, }, 'db1': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=db1,extensions' }, 'NAME': 'databasename', 'USER': bdd_user, 'PASSWORD': db_pwd, 'PORT': bdd_port, 'HOST': host_writer, }, 'db2': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=db2,extensions' }, 'NAME': 'databasename', 'USER': bdd_user, 'PASSWORD': db_pwd, 'PORT': bdd_port, 'HOST': host_writer, } } ...and it doesn't work ! Any suggestions ? -
Creating a model object in django using my uploaded file corrupts the file
I have a model which uploads a file from an ImageField. In my view I get this value from a jpg file I get via POST. View code: if request.method == "POST": errorID = request.POST.get("errorid") emailAddress = request.POST.get("toemail") imageAttach = request.FILES['snapshot'] phoneNum = request.POST.get("number") timeStamp = datetime.now() imageAttach.name = str(errorID) + '.jpg' ticket = UserTicket.create(errorID, emailAddress, phoneNum, imageAttach, timeStamp) ticket.save() Model Code: class UserTicket(models.Model): ErrorID = models.CharField(max_length=255, primary_key=True, unique=True, db_column='Error ID') EmailAddress = models.CharField(max_length=255, db_column='Email Address', blank=True) PhoneNumber = models.CharField(max_length=255, db_column='Phone Number', blank=True) Snapshot = models.ImageField(upload_to='images', blank=True, null = True, db_column='Image') Timestamp = models.DateTimeField(blank=True, db_column='Date/Time Submitted') @classmethod def create(cls, eID, eAddress, pNumber, img, tStamp): userTicket = cls( ErrorID = eID, EmailAddress = eAddress, PhoneNumber = pNumber, Snapshot = img, Timestamp = tStamp) return userTicket I have this data set to send out an email with the details in UserTicket, with the image file as an attachment. For some reason when I send the data direct from the POST, the image attachment is perfect. But when I try to send the data after I've created the object, the file is 200 bytes and windows doesn't know what to do with the file. -
How to query django app for multi Input search if we have multiple models sharing same primary key
I have 20 large models sharing the same primary key created using this database structure. CREATE TABLE table1 ( id uuid PRIMARY KEY, -- 1599 more columns ); CREATE TABLE table2 ( id uuid PRIMARY KEY REFERENCES table1 (id), -- 1599 more columns ); CREATE TABLE table3 ( id uuid PRIMARY KEY REFERENCES table1 (id), -- 1599 more columns ); I want to have a search page in my Django app, where it can search from the join of all these tables and give me 2 required fields user asked from the search bar. Can anyone guide me on how to query the whole database and get specific details? Any kind of help will be appreciated. -
How to access Django based website from different local machines?
In the cmd , after receiving my Ipv4 address using ipconfig , I have added it to the ALLOWED_HOSTS in the settings.py file . Then to run the website , in cmd I ran the following command : python manage.py runserver 192.168.x.x:8000 where 192.168.x.x is my ipaddress . I am able to to access my website from my own local machine , however on other local machines : 192.168.x.x:8000/ isn't responding. -
Django Haystack - select related with load all not getting all sub queries
I'm using the .load_all() method to get all select_related models on my auto query. However when I'm running debug toolbar I can still see I have 25 duplicate queries. views.py # create null query object sqs = None # does the query contain a seperator if ":" in query.lower(): search = query.lower().split(':') # set the correct Model name model = None model_search = search[0] if model_search == 'device': model = Device elif model_search == 'device circuit': model = DeviceCircuitSubnets elif model_search == 'site': model = Site elif model_search == 'site circuit': model = SiteCircuits # if we have a supported model search that model only if model: print('model search for {}'.format(str(model))) sqs = SearchQuerySet().models(model).filter(content=AutoQuery(search[1])).load_all() else: sqs = SearchQuerySet().filter(content=AutoQuery(query)).load_all() else: # were not looking for anything else so search the DB sqs = SearchQuerySet().filter(content=AutoQuery(query)).load_all() in my template I do some regrouping to sort out the results into sections: {% regroup results|dictsort:"model_name" by model_name as grouped_objects %} {% for ct in grouped_objects %} <div class="col-12 col-md-6 col-lg-3"> <h3 class="text-capitalize">{{ ct.grouper|friendly_search_name }}</h3> <div class="table-responsive"> <ul id="pager_{{ ct.grouper }}" class="pagination-sm pagination-separate pagination-curved synchronized-links mt-1"></ul> </div> <div id="pager_content_{{ ct.grouper }}"> {% for result in ct.list %} <div class="col-12 results item"> <div class="pt-4 border-bottom"> <a class="page-url … -
.get_object() showing dataset rather than field data from model
I'm building a website that displays recipes from cookbooks on a page. Here is what I have so far models.py class cookbook(models.Model): title = models.CharField(max_length=255,unique=True) class ingredient (models.Model): name = models.CharField(max_length=255,unique=True) class recipesteps(models.Model): ingredient = models.ForeignKey(ingredient,on_delete=models.CASCADE) instructions = models.TextField() time = models.IntegerField(default=0) class recipe(models.Model): name = models.CharField(max_length=255,unique=True) cookbook = models.ForeignKey(cookbook,on_delete=models.CASCADE) ingredient_used = models.ManyToManyField(ingredient) recipe_steps = models.ForeignKey(recipesteps,on_delete=models.CASCADE) def __str__(self): return 'name={} cookbook={} `'.format(self.name,self.cookbook) views.py from django.views.generic import DetailView class RecipeDetailView(DetailView): model = recipe def get_context_data(self, **kwargs): context = super(RecipeDetailView, self).get_context_data(**kwargs) context['instructions'] = totalcontent.objects.filter(recipe=self.get_object()) return context template.html <!DOCTYPE html> <html> <head> </head> <body> <h2>{{ object.cookbook }}</h2> <h2> Recipe Name = {{ object.name }} </h2> <h2> Steps To Make:</h2> {{ instructions }} </body> </html> The output of the {{ instructions }} variable in the template is : <QuerySet [<recipesteps: name=Tomato cookbook=Cooking with tomato >, <recipesteps: name=Lettuce cookbook= Cooking with lettuce >]> Is there a way I can show just the name of the ingredient at one point in the template and also show the cookbook at another point without the ? -
docker-compose ignores installed django, virtualenv
docker-compose ignores installed virtual environment I am trying to dockerize my existing django app. Also I am new to docker, so please forgive me, if this is some sort of "just read the instructions" thing. Question 51490937 seems to be somewhat related, but I am not sure about that. My app runs apache with a pip install mod-wsgi and it already deploys well to a native ubuntu 18 and 19 vm. I run win10 and I am using a linux container with Docker version 19.03.4, build 9013bf5 and I run a python:3.7 base image. My problem: Running my installed image fails when I use docker-compose up, but succeeds when I run the same manually. I first assumed, I have a caching problem, but trying all the things as suggested by https://forums.docker.com/t/how-to-delete-cache/5753 did not help. Also the time stamp of my local project folder is identical to the time stamp of the manually run container and the one returned by the Dockerfile. So now I assume there is something wrong with my docker-compose.yml, or I activated some branching, that I am not aware of. (files are attached at the end) For debugging I removed the postgress service and now run the … -
ImportError: cannot import name 'product_delete_view' from 'products.views'
Can anyone help with this i am learning django please? My Code: My Error: My HTML: URLS.py: -
Django "You have 1 unapplied migration(s)" but last last migration is applied
So I had to reorganize my models ( had to do manual migrations) and in the end I had to rename some models and then I got an error, when I was running `manage.py migration: The field Collect_data.Players.Team was declared with a lazy reference to 'xx.old_name', but app 'xxx' doesn't provide model 'old_name'. the migration file: migrations.RenameModel( old_name='Old_name', new_name='new_name', ), Now if look to the db, everything seems to be ok(renaming has been done) and all the connections are ok. If I open django shell, I can get the models with new names. Only problem is that I get this warning when I run server: "You have 1 unapplied migration(s)." and if I try to migrate, then I get a error that table already exists. If I run makemigartion I get same error as the first one said ( lazy reference... ). In migrations list I can see that the last migration doesn't have "X" on it's box. So how can I tell Django that everything is fine? -
Serialize ManyToMany field drf haystack
I'm trying to serialise a field that contains a many to many relationship with another model. I use drf-haystack to serialize the results by haystack (elasticsearch). Normally, I would include a m2mfield serializer for the m2mfield in the modelsearchserializer, but somehow when I rebuild the index afterwards, the serialization gives an error saying it is unable to serialise. Indexed Model: class ModelIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='title', boost=2.5) model_id = indexes.IntegerField(model_attr='id') m2mfield = indexes.MultiValueField() date = indexes.DateField(model_attr='date') site_id = indexes.IntegerField() def get_model(self): return Model def prepare_m2mfield(self, obj): return [m2mfield for m2mfield in obj.m2mfield.all()] def prepare_site_id(self, obj): return obj.site.id def index_queryset(self, using=None): # Used when the entire index for model is updated. return self.get_model().objects.all().filter(date__lte=datetime.datetime.now()).prefetch_related('m2mfield') Serializer: class ModelSearchSerializer(HaystackSerializer): /* Tried including a serializer for m2mfield here, but didnt work */ class Meta: index_classes = [ModelIndex] fields = ['title', 'text', 'date', 'm2mfield', 'model_id'] -
How to add slug in Django Web-application
Here is the problem: I'm trying to 'fresh' my django web blog, so instead of having /post/2/ I want to have slugged link that's exactly like my title (smth like this: /post/today-is-friday Here is some code, I've tried couple of things, but there is nothing working: models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.template.defaultfilters import slugify class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) categories = models.ManyToManyField('Category', related_name='posts') image = models.ImageField(upload_to='images/', default="images/None/no-img.jpg") slug= models.SlugField(max_length=500, unique=True, null=True, blank=True) def save(self, *args, **kwargs): self.url= slugify(self.title) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name urls.py from django.urls import path from django.conf.urls import include, url from . import views from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView urlpatterns = [ #Blog section path("", PostListView.as_view(), name='blog-home'), path("user/<str:username>", UserPostListView.as_view(), name='user-posts'), path("post/<int:pk>/", PostDetailView.as_view(), name='post-detail'), path("post/new/", PostCreateView.as_view(), name='post-create'), path("post/<int:pk>/update/", PostUpdateView.as_view(), name='post-update'), path("post/<int:pk>/delete/", PostDeleteView.as_view(), name='post-delete'), path("about/", views.about, name="blog-about"), path("<category>/", views.blog_category, name="blog_category"), ] -
How to override form submit to create any M2M entries that don't exist?
I am new to Django and I'm trying to figure out how to handle this situation. The site is designed to be a bookmark manager, so you can tag each bookmark with any number of tags and they don't have to exist already. I'm using a ModelForm and the tags field is a Select2TagWidget, currently when you submit the form you will get an error message that says " is not a valid value" (See here). Before pressing submit I had "reddit" as a tag, but then it returns the error. Instead of this being an error any new tag should just be added to the database. Here is my form: class AddLinkForm(forms.ModelForm): class Meta: model = Link fields = ['title', 'url', 'description', 'tags'] widgets = { 'tags': Select2TagWidget(attrs={ 'class': 'tagging' }), } Here is my view: class LinkCreate(LoginRequiredMixin, CreateView): model = Link form_class = AddLinkForm success_url = reverse_lazy('user-links') def form_valid(self, form): obj = form.save(commit = False) obj.added = timezone.now() obj.user_id = self.request.user obj.save() form.save_m2m() return HttpResponseRedirect(reverse('user-links')) I've tried to use the debugger to step into form_valid, but I never get to that if there is an error. I was able to see the invalid tag name when stepping into … -
Django Mixin behavior depending on Class overridden methods
I can't find the exact words to explain the problem, so I'll do it the simplest way I can think of The Scenario The Mixin class MyMixin: def form_valid(self, form): print('Mixin form_valid') response = super().form_valid(form) # do some stuff return response def form_invalid(self, form): print('Mixin form_invalid') response = super().form_invalid(form) # do some stuff return response The View with no overrides class MyView1(MyMixin, UpdateView) model = Model1 The View with form_valid and form_invalid methods overridden class MyView2(MyMixin, UpdateView): model = Model2 def post(self, request, *args, **kwargs): # do some stuff if form.is_valid(): return super().form_valid(form) else: return super().form_invalid(form) def form_valid(self, form): print('View form_valid') form.save() # do some stuff return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form): print('View form_invalid') # do some stuff return self.render_to_response(self.get_context_data(form=form)) The Goal As shown, I have 2 situations where I need the following: When the form_valid and form_invalid methods in the view are overridden (like MyView1), MyMixin should call the UpdateView's corresponding methods. When the form_valid and form_invalid methods in the view are not overridden (like MyView2), MyMixin should call the MyView2's corresponding methods. I would also appreciate if someone knows a better or simpler way to accomplish this Many thanks in advance.