Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and Postgres "does not exist" when add new relation
Hi I'm havin some problems with Django and Postgres. Here's the model I'm working on: class UserMessage(models.Model): ... replied_by = models.ManyToManyField("users.User", related_name="replied_by_users", default=None, blank=True) When I add the field replied_by and perform the new migrations, all works but when I try to access to the model instances from database, it raised the following error: ProgrammingError at /admin/moments/usermoment/ relation "app_usermessage_replied_by" does not exist LINE 1: ...t"."event_id", "app_usermessage"."end_at" FROM "... And that's because there were already some instances before adding the replied_by field, but since I set the new field to None as default, it needs to ignore them. Here's a snippet of migration file: migrations.AddField( model_name='usermoessage', name='replied_by', field=models.ManyToManyField(blank=True, default=None, related_name='replied_by_users', to=settings.AUTH_USER_MODEL), ), How can I solve this problem without losing database data? Of course I'm in development mode, are there any good practice that I'm missing to handle database when you add a new relation. Thank you -
Can somebody help to fix this problem? im realy tired of trying
enter image description here class EmailVerificationView(TitleMixin, TemplateView): title = 'Store - Подтверждение электронной почты' template_name = 'users/email_verification.html' def get(self, request, *args, **kwargs): code = kwargs['code'] user = User.objects.filter(email=kwargs['email']) email_verifications = EmailVerification.objects.filter(user=user, code=code) if email_verifications.exists() and not email_verifications.first().is_expired(): user.is_verified_email = True user.save() return super(EmailVerificationView, self).get(request, args, **kwargs) else: return HttpResponseRedirect(reverse('index')) I already changed get to filter. Before i had get in user there was issue "get() returned more than one user -- it returned" Im trying to send email to verify acc. -
Django cannot find template, app is in installed_apps and backend DjangoTemplates is enabled
Inside of a page in my templates folder, I tried using an include statement in a for loop, like so: {% for model_othermodel in model.othermodels.all%} {% include othermodels.html with othermodel=model_othermodel %} {%endfor%} At first, I had the issue that it complained there was no key/value being sent to the other template, which was that othermodel=model_othermodel looked like other_model = model_othermodel. However, after that, I had the issue that it could not find the included html file (the file name is correct), for which the error problem would show me the base.html file that each page extends. (I will be using django_app to refer to the app folder) I got the error message: In template path\root\django_app\templates\base.html, error at line 0 No template names provided My base.html file is just a file for bootstrap that every other html file extends. My project structure looks like this: root/django_app root/django_project root/django_app/templates I tried adding the template path directly to 'DIRS' in TEMPLATES, such as so: DIRS = [os.path.join(BASE_DIR, django_app/templates/)] with variations such as django_app/templates, /templates/, /templates, etc. After that, I heard a suggestion to reorder my INSTALLED_APPS list, which is currently: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'django_app', ] to … -
Pythonanywhere deployment failure on the wsgi according to error log
I'm trying to deploy to Pythonanywhere and i believe i have followed all of the right steps. The latest error on the error log is: Error running WSGI application ModuleNotFoundError: No module named 'Project' File "/var/www/sizwe93_pythonanywhere_com_wsgi.py", line 17, in <module> application = get_wsgi_application() File "/home/sizwe93/.virtualenvs/mysite-virtualenv/lib/python3.10/site- packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) My WSGI file is on the Dashboard: from this # +++++++++++ DJANGO +++++++++++ # To use your own Django app use code like this: import os import sys # assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py' path = '/home/sizwe93/Project' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'Project.settings' ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() ###### or, for older Django <=1.4 #import django.core.handlers.wsgi #application = django.core.handlers.wsgi.WSGIHandler() I'm trying to deploy from my project on Github... I'm not sure what i'm missing, please help... -
print form value into the HttpResponseRedirect(HTML), Django
I'm filling in a reference number automatically when the form is loaded, now, i want to print this reference number to the HTML after the form is successfully submitted. !! views.py forms.py models.py HTML BTW, everything is working fine but the reference number never appeared !! please help -
How to use field variable of the model related with ForeignKey
I'm trying to create an Album model and a Song model which are both having a genre field. I want Song model's genre field is same with the Album model's by default. class Album(models.Model): genre = models.TextField() class Song(models.Model):` album = models.ForeignKey(Album, on_delete=models.CASCADE) genre = models.TextField() #The field I want to be same with its related model -
'ascii' codec can't decode byte 0xc3 in position 7: ordinal not in range(128)
Unicode error hint The string that could not be encoded/decoded was: Ubicación Getting error this spanish word in django standard translation. -
Django Web App Deployment on Render.com, Import Errors
I am currently trying to deploy my Django Web App to https://render.com/, but I got several problems, I am following this tutorial: https://www.youtube.com/watch?v=AgTr5mw4zdI, at 19:00 I have to import dj_database_url I have imported the Package in my Virtual Environment! This is what pip list says Here is my folder stucture: I think the problem is possibly because of the folder structure. Here is the Import -
Django form design
How can I make my form looks better? A few questions: How can I make the checkbox and buttons beside Favourite, Photo and Audio. And how can I change the design of the "Choose File" button to the same design as the "Save" and "Cancel" buttons? Can I show the image and audio after uploading it? BTW, I am using crispy form and Bootstrap 4. The html {% extends "base.html" %} {% block content %} <form method="POST" enctype="multipart/form-data"> <div class="mx-auto mt-4" style="width: 600px;"> {% csrf_token %} {{ form.as_p }} <div class="text-center"> <input type="submit" value="Save" class="btn btn-outline-info"> </div> </div> </form> {% if journal %} <div class="text-center"> <a href="{% url 'journal_detail' journal.id %}"><button type="button" class="btn btn-outline-info">Cancel</button></a> </div> {% else %} <div class="text-center"> <a href="{% url 'journal_list' %}"><button type="button" class="btn btn-outline-info">Cancel</button></a> </div> {% endif %} {% endblock %} -
Why does the form validation fail in this django formset?
I have been trying to make a django formset for giving feedback for assignments in a rubric style, where a form is generated for each criteria in an assignment, with the submissionID being automatically assigned, and the user selects what level the student has met a criteria to, and gives a comment about the criteria. Example: The problem I'm facing is that submitting the form does not do anything and just seems to refresh the current page, and I've tried everything I can think of to solve the problem, but the only thing I've managed to find out is where it is going wrong, which is at the line if form.is_valid(), which is returning false as it seems to be getting no forms passed to it for some reason. The expected result of the code is that when a post request is sent, it loops through the submitted forms, sets the submissionID, and saves the forms. So far I have tried doing some debugging by printing variables at different points of the code but mainly the line before it fails. Prints tried: formset: `(Hidden field TOTAL_FORMS) This field is required.(Hidden field INITIAL_FORMS) This field is required. ` Number of forms … -
Combine multiple django forms into one
I'm working with a django(4) project, Where I have two forms and want to combine them into one to display in my template with custom html not by sing {{form}} syntax. Here's my forms.py: class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email'] # Create a ProfileUpdateForm to update image. class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] How can I combine both of these forms into single one to display all the filed in HTML and submit as a single form? -
Why django translations don't work in celery task
I'm having problems with django text translations. My translation works fine in serializer, not in celery task. I have one "Person" model. There are 3 fields in the Person model. One of the fields is gender. The genders are defined in the "enums.py" file. In the serializer, the "get_gender_display()" method of the "Person" model works fine, but when I do the same in the celery task, it does not translate. It doesn't work even though I specify activate("tr") in the Celery task. I call the celery task from the serializer's create() method enums.py from django.utils.translation import gettext_lazy as _ class GenderTypeEnum: FEMALE = 1 MALE = 2 UNKNOWN = 3 types = ( (FEMALE, _("Female")), (MALE, _("Male")), (UNKNOWN, _("Unknown")) ) models.py from django.db import models from .enums import GenderTypeEnum from django.utils.translation import gettext_lazy as _ class PersonModel(models.Model): name = models.CharField( max_length=75, verbose_name=_('Name') ) last_name = models.CharField( max_length=75, verbose_name=_('Last Name') ) gender = models.PositiveIntegerField( choices=GenderTypeEnum.types, default=GenderTypeEnum.UNKNOWN, verbose_name=_('Gender') ) tasks.py from celery import shared_task from .models import PersonModel from django.utils.translation import gettext_lazy as _, activate, get_language @shared_task def test(): activate("tr") qs = PersonModel.objects.all() activate("tr") print(get_language()) # --> tr for obj in qs: print(obj.get_gender_display()) # --> always english, not translated serializers.py from rest_framework … -
Django debug toolbar not showing
My file directory system I have attached my file directory system. I have tried removing all *.pyc files as asked in some of the threads on the same topic, but the toolbar still doesn't show. The following is my webpage code: <html> <body> {% if name %} <h1>Hello {{ name }}!</h1> {%else%} <h1>Hello Dude!</h1> {% endif %} </body> </html> I tried adding mimetypes, adding the following code, and even editing the registry editor, but none of them are working. DEBUG_TOOLBAR_CONFIG = { "INTERCEPT_REDIRECTS": False, } No matter what I do, the browser console displays the following (though when I sometimes change the code the error doesn't get displayed, but neither does the toolbar). I'm using MS Edge, just in case it helps. Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec. toolbar.js:1 When I try importing django in my virtual env, it says that there is no module called 'django'. I've tried all methods possible, but nothing seems to be working. -
Django. Need to load initial data to a form
I need to load data from database to form, so user can update it, but can't find a way to do it. with method below i get <django.db.models.query_utils.DeferredAttribute object at 0x000001DB8861EAC0> instead of currency. How to get data before putting it to dictionary in init_supplier? Thanks Here is my view.py: def supplier_form(request): s_data = supplier.objects.all init_supplier = { 'currency' : supplier.currency } submitted = False if request.method == "POST": form = s_form(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/home?submitted=TRUE') else: sup_form = s_form(initial=init_supplier) if submitted in request.GET: submitted = True return render(request, 'forms/supplier_form.html', {'sup_form':sup_form, 'submitted':submitted, 's_data' : s_data}) So far tried with init in forms and filtering in wievs. -
ModuleNotFoundError: No module named 'projects'
I deleted my migrations watching tutorials and when I try to make migration this error occurs ModuleNotFoundError: No module named 'projects' please help I have added my models.py file. from django.db import models import uuid from django.db.models.deletion import CASCADE from users.models import Profile >! Create your models here. class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) featured_image = models.ImageField( null=True, blank=True, default="default.jpg") demo_link = models.CharField(max_length=2000, null=True, blank=True) source_link = models.CharField(max_length=2000, null=True, blank=True) tags = models.ManyToManyField('Tag', blank=True) vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title class Meta: ordering = ['-vote_ratio', '-vote_total', 'title'] @property def imageURL(self): try: url = self.featured_image.url except: url = '' return url @property def reviewers(self): queryset = self.review_set.all().values_list('owner__id', flat=True) return queryset @property def getVoteCount(self): reviews = self.review_set.all() upVotes = reviews.filter(value='up').count() totalVotes = reviews.count() ratio = (upVotes / totalVotes) * 100 self.vote_total = totalVotes self.vote_ratio = ratio self.save() class Review(models.Model): VOTE_TYPE = ( ('up', 'Up Vote'), ('down', 'Down Vote'), ) owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Meta: unique_together = [['owner', 'project']] def … -
How to create double nesting serializer in Django
While trying to create nested object, i'm getting this error. I may be using incorrect relationship here; need your expert guidance. Cannot assign "OrderedDict([('color', 'black), ('transmission', 'auto'), ('mileage', '20kmpl')])": "Vehicle.detail" must be a "Detail" instance Django==4.1.7 Python 3.9.13 Expecting { "auto_id": "some-uuid", "vehicle": [ { "manufacturer": "toyota", "year": 2020, "detail": { "color": "black", "transmission": "auto", "mileage": "20kmpl" } } ] } model class Auto(models.Model): auto_id = models.UUIDField(primary_key=True) class Detail(model.Model): color = models.CharField(max_length=10) transmission = models.CharField(max_length=10) mileage = models.CharField(max_length=10) class Vehicle(models.Model): manufacturer = models.CharField(max_length=10) year = models.PostiveIntegerField() auto = models.ForeignKey(Auto, related_name='vehicle', on_delete=models.cascade) detail = models.ForeignKey(Detail, on_delete=models.cascade) serializer class DetailSerializer(serializers.ModelSerializer): class Meta: model = Detail fields = ('color', 'transmission', 'mileage') class VehicleSerializer(serializers.ModelSerializer): detail = DetailSerializer() class Meta: model = Vehicle fields = ('manufacturer', 'year', 'detail') class AutoSerializer(serializers.ModelSerializer): vehicle = VehicleSerializer(many=True) class Meta: model = Auto fields = '__all__' def create(self, validated_data): vehicle_list = validated_data.pop('vehicle') auto = Auto.objects.create(**validated_data) for vehicle in vehicle_list: Vehicle.objects.create(auto=auto, **vehicle) return auto Could you please guide me, where i can convert the ordered dict for detail instance. -
Migration fails when using GeoDjango's PointField in a model
I have defined a Model like this (note the I have to specify the schema it should be created on during migration): from django.db import models from django.contrib.gis.db import models as gis_models class MyModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... geometry = gis_models.PointField() class Meta: db_table = 'gis"."my_model' I make the migration and all seems well. When I run the migration though, I have this error: psycopg2.errors.SyntaxError: syntax error at or near "." LINE 1: CREATE INDEX "gis"."my_model_geometry_id" ON "... (Yes, the error message is truncated like this.) It seems it wants to create an index for the geometry id and fails doing so. I tried to look for this error, but couldn't find anything helpful for this specific case. How can I fix this issue ? -
How to upload a video from django through FileField
I tried to upload a video from django through FileField, but I couldn't download it. urls.py urlpatterns = [ path('api/', include('api.urls')), path("admin/", admin.site.urls), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") models class Correctpic(models.Model): uid = models.AutoField(primary_key=True) picturefilename = models.FileField(db_column='pictureFileName', max_length=255, upload_to='doctor/', blank=True) doctorid = models.ForeignKey(Doctor, models.DO_NOTHING, db_column='doctorId') class Meta: managed = False db_table = 'correctPic' views.py form.picturefilename = request.FILES.get('video', None) form.save() request enter image description here Originally, the video should be saved with a 'media' folder under the project folder, but it is not. How can we solve this? -
How can I allow user to submit a form
When I try to submit Table model to the database using create_table view, it throws me an error: NOT NULL constraint failed: audioApp_table.user_id after I do my own research I found out it was because I didn't add user to the form, so I try to add it by adding: table = Table(user=request.user), but it is not working, how can we allow user to submit this form, I knew how to do that in class base view using instance.user = self.request.user, but for function base view I'm failed. def create_table(request): columns = Column.objects.filter(user=request.user) fields = {} for column in columns: if column.field_type.data_type == 'number': fields[column.name] = forms.IntegerField() elif column.field_type.data_type == 'character': fields[column.name] = forms.CharField(max_length=20) elif column.field_type.data_type == 'decimal': fields[column.name] = forms.DecimalField(max_digits=20, decimal_places=10) elif column.field_type.data_type == 'image': fields[column.name] = forms.ImageField() elif column.field_type.data_type == 'boolean': fields[column.name] = forms.BooleanField() elif column.field_type.data_type == 'date': fields[column.name] = forms.DateField() TableForm = type('TableForm', (forms.Form,), fields) if request.method == 'POST': form = TableForm(request.POST, request.FILES) if form.is_valid(): table = Table() for column in columns: setattr(table, column.name, form.cleaned_data[column.name]) table.save() return redirect('Table') else: form = TableForm() return render (request, 'create_table.html', {'form':form}) class Table(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) number = models.IntegerField(blank=True, null=True) decimal = models.DecimalField(max_digits=20, decimal_places=10, blank=True, null=True) image = models.ImageField(upload_to='table-image', blank=True, … -
update photo and remove current photo option from bootstrap modal dialog in Django
I am trying to build a book browse web application where in the timeline page, profile picture, username and list of uploaded book photos will be shown. User can update profile pic and remove current profile pic. I used the bootstrap modal(dialog) where these two options (update photo and remove current photo) was given. Can anyone tell me what will be the logic in views.py file to update profile pic and remove the profile pic? should I use forms.py instead of using tag in the timeline.html file? if yes, what will be there in the forms.py file? books/timeline.html {% extends 'books/base.html' %} {% block content %} <!-- Welcome Area Start --> <section class="welcome-area"> <div> <!-- Single Slide --> <div class="single-welcome-slide bg-img bg-overlay"> <div class="container h-100"> <div class="row h-100 align-items-center"> <!-- Welcome Text --> <!-- Our Team Area Start --> <div class="container"> </div> <div class="row"> <div class="col-12"> <div class="section-heading text-center wow fadeInUp" data-wow-delay="100ms"></div> </div> </div> <div class="row"> <!-- Team Member Area --> <div class="col-md-4 col-xl-4"> <div class="team-content-area text-center mb-30 wow fadeInUp" data-wow-delay="300ms"> <div class="member-thumb"> <a href="#" data-toggle="modal" data-target="#profilePictureModal"> <img src="{{ user.profile_picture.url }}"/> </a> </div> <br> </div> </div> <div class="col-12 col-lg-8 col-xl-8"> <div class="welcome-text"> <h2 data-animation="bounceInDown" data-delay="900ms"> {{ user.username }} </h2> <div … -
pyodbc is not working on mac but working on windows
I am a new macbook user. I am trying to running my django project (which I created on windows machine) on my new macbook pro m2. Everything is working but while connecting to azure sql server, I am getting the following error: raise ImproperlyConfigured("Error loading pyodbc module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading pyodbc module: dlopen(/Users/abdullah_13af/.local/share/virtualenvs/airtable-70OjLi3O/lib/python3.10/site-packages/pyodbc.cpython-310-darwin.so, 0x0002): symbol not found in flat namespace '_SQLAllocHandle' I've installed the ODBC Driver but still getting this error. here is the full error message: python manage.py runserver ─╯ Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/abdullah_13af/.local/share/virtualenvs/airtable-70OjLi3O/lib/python3.10/site-packages/mssql/base.py", line 16, in <module> import pyodbc as Database ImportError: dlopen(/Users/abdullah_13af/.local/share/virtualenvs/airtable-70OjLi3O/lib/python3.10/site-packages/pyodbc.cpython-310-darwin.so, 0x0002): symbol not found in flat namespace '_SQLAllocHandle' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.10/3.10.10_1/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.10/3.10.10_1/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/Users/abdullah_13af/.local/share/virtualenvs/airtable-70OjLi3O/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/abdullah_13af/.local/share/virtualenvs/airtable-70OjLi3O/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/abdullah_13af/.local/share/virtualenvs/airtable-70OjLi3O/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/abdullah_13af/.local/share/virtualenvs/airtable-70OjLi3O/lib/python3.10/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/Users/abdullah_13af/.local/share/virtualenvs/airtable-70OjLi3O/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/abdullah_13af/.local/share/virtualenvs/airtable-70OjLi3O/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/abdullah_13af/.local/share/virtualenvs/airtable-70OjLi3O/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() … -
I am getting questions.models.Question.DoesNotExist: Question matching query does not exist. when ever i press on the save button in a quiz app
Here is the traceback i get Traceback (most recent call last): File "/home/kali/django-test-app/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 56, in inner response = get_response(request) File "/home/kali/django-test-app/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in \_get_response response = wrapped_callback(request, \*callback_args, \*\*callback_kwargs) File "/home/kali/django-test-app/src/django-test-app/testapp/quizes/views.py", line 46, in save_quiz_view question = Question.objects.get(text=k) File "/home/kali/django-test-app/venv/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(\*args, \*\*kwargs) File "/home/kali/django-test-app/venv/lib/python3.10/site-packages/django/db/models/query.py", line 650, in get raise self.model.DoesNotExist( questions.models.Question.DoesNotExist: Question matching query does not exist. \[01/Apr/2023 13:30:02\] "POST /3/save/ HTTP/1.1" 500 76917 i was using request.is_ajax() then i realised that it was removed so i changed it to if request.headers.get('x-requested-with') == 'XMLHttpRequest': it didn't work, i also tried creating a check function def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' and used if request.is_ajax(): still getting questions.models.Question.DoesNotExist: Question matching query does not exist. **Here is my views.py ** from django.shortcuts import render from .models import Quiz from django.views.generic import ListView from django.http import JsonResponse from questions.models import Question, Answer from results.models import Result from django.shortcuts import HttpResponse from django.shortcuts import get_object_or_404 class QuizListView(ListView): model = Quiz template_name = 'quizes/main.html' def quiz_view(request, pk): quiz = Quiz.objects.get(pk=pk) return render(request, 'quizes/quiz.html', {'obj': quiz}) def quiz_data_view(request, pk): quiz = Quiz.objects.get(pk=pk) questions = \[\] for q in quiz.get_questions(): answers = \[\] for a in q.get_answers(): answers.append(a.text) questions.append({str(q): … -
Django formset not working with dual selector widget
I have learnt using django formset especially with dual selector widget: #forms.py class TestExamForm(forms.ModelForm): topics = models.ModelMultipleChoiceField( queryset=Topic.objects.all(), widget=DualSelector(search_lookup='name__icontains', group_field_name='subject',), ) class Meta: model = Exam4Fin fields = '__all__' #views.py def detail(request): context = {} # create a formset for Books BookFormSet = modelformset_factory(Exam4Fin, form=TestExamForm, extra=1) if request.method == 'POST': # validate formset and save data formset = BookFormSet(request.POST, queryset=Topic.objects.none()) if formset.is_valid(): instances = formset.save(commit=False) for instance in instances: instance.save() return #redirect('book_author') else: # display empty formset formset = BookFormSet(queryset=Topic.objects.none()) context = { 'formset': formset, # 'authors': authors } #return render(request, 'book_author.html', context) return render(request, "testexam.html", context) #html template <form method="POST"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form.as_p }} {% endfor %} <button type="submit">Save</button> </form> Everything working well...but the html page looks weird: The layout looks strange. upon inspecting element getting error like this: Uncaught Error: Attempt to initialize <django-selectize> outside <django-formset> at new d (chunk-EVLKIONU.js:1:278) at new h (DualSelector-NEQ42NHO.js:1:294) at HTMLSelectElement.connectedCallback (DualSelector-NEQ42NHO.js:1:12262) at django-formset.js:25:31235 Can someone plz help I am clueless.... -
Django Admin Interface doesn't log in super users
I'm trying to log in with superuser but Django admin interface doen't login any superuser. app_name = 'accounts' I'm using Djoser, here is my models.py: class User(AbstractUser): email = models.EmailField(max_length=254, unique=True) is_superuser = models.BooleanField() REQUIRED_FIELDS = ('first_name', 'last_name', 'username', ) USERNAME_FIELD = 'email' def __str__(self): return self.first_name + ' ' + self.last_name settings: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) AUTH_USER_MODEL = 'accounts.User' Why can't log in, although the user is super user? I'm sure that user.is_superuser == True -
404 bad request with Django send blob to server side using MediaStreamRecorder.js
I am using MediaStreamRecorder.js to make an audio recording. After recording, it will save it to the database. However, I receive a 404 bad request . When I try to print the blob value in views.py, it gives me none. I tried many solutions but still cannot fix it. I really need some help. The first thing I used to send blob is xhr var csrftoken = getCookie('csrftoken'); var xhr = new XMLHttpRequest(); console.log(xhr) xhr.open('POST', '/record-audio/', true); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.setRequestHeader("MyCustomHeader", "Put anything you need in here, like an ID"); xhr.send(blob); Currently I am using fetch but still getting the same error. chat_script.html -> with js functions function sendData(blob) { const csrf_token = getCookie('csrftoken') fetch('/record-audio/', { headers: {"X-CSRFToken": csrf_token}, method: 'POST', body: blob, }); console.log('success') } sendData(blob) For the '/record-audio/' in xhr.open('POST', '/record-audio/', true); and fetch('/record-audio/', I actually type in only '/record-audio', but it keeps giving me the error Not Found: /record-audio/record-audio/ urls.py path('record-audio/',views.record_audio,name="record_audio"), record.html {% load static %} {% block content %} <h1>Recorder</h1> <section class="experiment" > <br> <h3> Send Message: Speech to text </h3> <form method="post" enctype="multipart/form-data" action="{% url 'record_audio' %}"> {% csrf_token %} <button id="start-recording">Start</button> <button id="pause-recording" disabled>Pause</button> <button id="resume-recording" disabled>Resume</button> <button id="stop-recording" disabled>Stop</button> <!-- <input type="submit" value="save file"> …