Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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"> … -
Thumbnail of Videos not loading on Server | Django
I am fairly new to Django and currently I'm making a Youtube Clone to understand Django in depth. So the problem I'm facing right now is that I can't seem to get the thumbnail to appear in homepage when I run the server. I've spent a lot of time trying but can't seem to find an answer! I'll provide what I think relates to my problem; 1) Templates homeview.html: `{% block body %} {% for video in most_recent_video %} <div class="video-card"> <img src="/get_thumbnail/{{ video.thumbnail.path }}" alt="{{ video.title }} thumbnail"> <h5>{{ video.title }}</h5> <p>Uploaded By {{ video.user }} on {{ video.datetime }}</p> <p>{{ video.description }}</p> <p><a href="/video/{{ video.id }}">Watch Video</a></p> </div> {% endfor %} {% endblock %}` thumbnail.html: `{% block body %} <div class="header-bar"> <h2>Thumbnail View</h2> <hr> </div> <div class="main-body"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_p }} </table> <button type="submit">Upload Thumbnail</button> </form> {% if errors %} <div class="errors"> <h3>Errors:</h3> <ul> {% for field_errors in errors.values %} {% for error in field_errors %} <li>{{ error }}</li> {% endfor %} {% endfor %} </ul> </div> {% endif %} </div> {% endblock %}` 2) views.py `class ThumbnailView(View): template_name = 'base/thumbnail.html' def get(self, request): if not request.user.is_authenticated: return HttpResponseRedirect('/login/') form = ThumbNailForm() … -
Exception Type : ValueError with The 'image' attribute has no file associated with it in Django
Geting error ValueError at / The 'image' attribute has no file associated with it. when I try to post a image from a user not having admin access then i am getting this error and the picture doesnot display. index.html <div class="container m-auto"> <!--<h1 class="lg:text-2xl text-lg font-extrabold leading-none text-gray-900 tracking-tight mb-5"> Feed </h1>---> <div class="lg:flex justify-center lg:space-x-10 lg:space-y-0 space-y-5"> <!-- left sidebar--> <div class="space-y-5 flex-shrink-0 lg:w-7/12"> <!-- post 1--> {% for post in posts reversed %} <div class="bg-white shadow rounded-md -mx-2 lg:mx-0"> <!-- post header--> <div class="flex justify-between items-center px-4 py-3"> <div class="flex flex-1 items-center space-x-4"> <!-- <a href="#"> <div class="bg-gradient-to-tr from-yellow-600 to-pink-600 p-0.5 rounded-full"> <img src="{% static 'assets/images/avatars/avatar-2.jpg' %}" class="bg-gray-200 border border-white rounded-full w-8 h-8"> </div> </a> --> <span class="block capitalize font-semibold "> {{post.user}} </span> </div> <div> <a href="#"> <i class="icon-feather-more-horizontal text-2xl hover:bg-gray-200 rounded-full p-2 transition -mr-1 "></i> </a> <div class="bg-white w-56 shadow-md mx-auto p-2 mt-12 rounded-md text-gray-500 hidden text-base border border-gray-100 " uk-drop="mode: hover;pos: top-right"> <ul class="space-y-1"> <!-- <li> <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md "> <i class="uil-share-alt mr-1"></i> Share </a> </li> <li> <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md "> <i class="uil-edit-alt mr-1"></i> Edit Post </a> </li> <li> <a href="#" class="flex items-center … -
How to prevent datatable search and pagination rows from repeating when pressing previous or forward buttons?
I am experiencing an issue with JQuery Datatables. Indeed, I am working on a django and Htmx project that has a base template. Inside of it, I initialize datatables like this: $(document).ready(function() { $('#datatable').DataTable({ }); }) Now, given that I am using HTMX, I have a #main-content id on an html element where I replace the content that is returned when Htmx issues an Hx-get request. Each time a request is made, I have to reinitialize the table in the returned template inside a <script><script/> tag using the same code as above and everything works perfectly fine. However, when I press the previous or next browser buttons, the datatable search and pagination rows get repetead multiple times, when there is data in my table, but it doesn't when there is no data. Thank you for helping me. I've tried to destroy the table using the destroy() method inn Javascript, but I still had the same issue. -
Django - Insert data into child table once the parent record is created
I am using Django REST Framework and facing a problem during inserting data into the child table. There are 2 models named Card and ContactName that have the following fields. The Card has a relation with ContactName via a foreign key field name card. models.py: class Card(models.Model): image = models.ImageField(upload_to='images', max_length=255, null=True, blank=True) filename = models.CharField(max_length=255, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.filename class ContactName(models.Model): first_name = models.CharField(max_length=255, null=True, blank=True) last_name = models.CharField(max_length=255, null=True, blank=True) confidence = models.FloatField(default=0) card = models.ForeignKey(Card, on_delete=models.CASCADE, related_name='contact_name') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.first_name My serializers.py file: class ContactNameSerializer(serializers.ModelSerializer): class Meta: model = ContactName fields = ['id', 'first_name', 'last_name', 'confidence', 'card', 'created_at', 'updated_at'] class CardSerializer(serializers.ModelSerializer): contact_name = ContactNameSerializer(many=True, read_only=True) class Meta: model = Card fields = ['id', 'image', 'filename', 'contact_name', 'created_at', 'updated_at'] In my ViewSet once the card record is created, I also want to add the following ContactName JSON data into the child table, set the reference (card_id) as an id of that card, and return the newly added record in the response. e.g. [ { "first_name": "John", "last_name": "Doe", "confidence": 0.9 }, { "first_name": "John", "last_name": "Doe", "confidence": 0.9 } ] views.py: class CardViewSet(viewsets.ModelViewSet): … -
Is there an option for alter table in django?
I have a very complicated cyclic dependency issue and I can't use late initialization (encapsulating the table name in quotations) because of some other dependencies on the table so the only logical solution to solve cyclic dependency at this point is to delay the creation of the foreign key through an alter table migration but i can't seem to find a way. just for clarification I want a way in django to execute the SQL command ALTER TABLE, please don't try to solve my cyclic dependency issue some other way i have exhausted every other option. I know there is a way for it in laravel and most major backend frameworks i just can't find anyway to achieve it in django. -
Django : How to filter in between 2 same objects in 2 different models?
I have integrated Microsoft Graph API with my django project and after login in successfully, I am storing both access and refresh token in 2 different models. the models are ModelA and ModelB. Assume that microsoft organisation account holders get their access and refresh token saved in ModelA. The ModelA includes the following attributes: class ModelA(models.Model): active = models.BooleanField(null = True , blank = True) for_user = models.ForeignKey(ModelX, null=True, blank=True, on_delete=models.CASCADE) for_firm = models.ForeignKey(ModelMain, related_name="microsoft_for_firm", null=True, blank=True, on_delete=models.CASCADE) access_token = models.TextField(null=True, blank=True) refresh_token = models.TextField(null=True, blank=True) and microsoft personal accounts holders get their access and refresh tokens saved in ModelB. The ModelB includes the following attributes: class ModelB(models.Model): active = models.BooleanField(null = True , blank = True) for_user = models.ForeignKey(ModelX, null=True, blank=True, on_delete=models.CASCADE) for_firm = models.ForeignKey(ModelMain, related_name="microsoft_for_personal", null=True, blank=True, on_delete=models.CASCADE) access_token = models.TextField(null=True, blank=True) refresh_token = models.TextField(null=True, blank=True) What I want to Achieve? I want to open a docx file using either microsoft organisation or personal account. before opening the file, I want to let the user open the file according to their account type. If a account type is personal, then it should use ModelB's access_token or refresh_token. If an account type is organisation then it should use the … -
How to filter a QuerySet based on whether the objects in it are present in another model?
I have a QuerySet called time_slots which contains objects of model class TimeSlot. time_slots = <QuerySet [ <TimeSlot: Room: Number: 1, category: Regular, capacity: 4, advance: 12, manager: anshul, from: 01:00:00, till: 02:00:00>, <TimeSlot: Room: Number: 1, category: Regular, capacity: 4, advance: 12, manager: anshul, from: 04:07:00, till: 06:33:00>, <TimeSlot: Room: Number: 1, category: Regular, capacity: 4, advance: 12, manager: anshul, from: 09:22:00, till: 10:55:00> ]> models,py class Room(models.Model): class Meta: ordering = ['number'] number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], primary_key=True ) CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models. CASCADE ) class TimeSlot(models.Model): class Meta: ordering = ['available_from'] room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() """class used when a user books a room slot.""" class Booking(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) check_in_date = models.DateField() timeslot = models.ForeignKey(TimeSlot, on_delete=models. CASCADE) Each time slot can be either booked or vacant. In order to find if it is booked or vacant, I do the following- if request.session['occupancy'] == '': for time_slot in time_slots: try: Booking.objects.get(check_in_date=request.session['date'], timeslot=time_slot) time_slot.occupancy = … -
Django ManyToMany field is not saved
I need to update ManyToMany field on object save. I've tried to override save method, but it doesn't update m2m. There is my authors field authors = models.ManyToManyField( to='author.Author', blank=True ) And save method is def save(self, *args, **kwargs): super(Album, self).save(*args, **kwargs) sounds = self.sounds.all() authors = [author for sound in sounds for author in sound.authors.all()] self.authors.set(authors) print(self.authors.all()) In output <QuerySet [<Author: Slick Killa>, <Author: 6feetdeep>]>, but database have not changed I will be glad of any help :) -
AttributeError: 'WSGIRequest' object has no attribute 'get' Internal Server Error: /
This is the code in modules.py class Payment(models.Model): cardnumber = CardNumberField(('card number') , default='Card Number') cardexpiry = CardExpiryField(('expiration date')) CVV = SecurityCodeField(('security code'), default='cvv') card_type = models.CharField(max_length=30 , default='Card Type') def __str__(self): return self.cardnumber + self.cardexpiry + self.CVV + self.card_type This is the code in forms.py from django.forms import ModelForm from .models import Payment class paymentForm(ModelForm): class Meta: model = Payment fields = \['cardnumber', 'cardexpiry', 'CVV' ,'card_type'\] This is the code in views.py from django.shortcuts import render from .forms import paymentForm def payment(request): if request.method == 'POST': form = paymentForm(request.POST) if form.is_valid(): \# Save the form data to the database form = paymentForm(request) else: form = paymentForm() return render(request, 'payment.html', { 'form': form }) i just want to display the forms in html page + save the update to database -
How can i install dlib in my azure web application
It requires cmake but how can i install it using azure because when i just use "pip install cmake" it doesnt work even in my local host but when i install the exe file it starts to work in my local host so how am i supposed to install it on a azure web application this is the error [06:40:02+0000] Building wheel for dlib (setup.py): started [06:40:02+0000] Building wheel for dlib (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [8 lines of output] running bdist_wheel running build running build_py package init file 'tools/python/dlib/init.py' not found (or not a regular file) running build_ext ERROR: CMake must be installed to build dlib [end of output] I tried installing it using azure power shell but it still didn't work as i said earlier -
Django - Generic detail view DailyForecastDetailView must be called with either an object pk or a slug in the URLconf
Can someone assist me with this? I am new to Django and am apparently missing a connection between my code somewhere. I already tried some of the sollutions mentioned on SOF for this problem, but I can't get it working. I get the error: Generic detail view DailyForecastDetailView must be called with either an object pk or a slug in the URLconf On my local url with date (http://127.0.0.1:8000/forecast/narnia/2023-03-26/) and without the date parameter (http://127.0.0.1:8000/forecast/narnia/) ** models.py**: from django.conf import settings from django.db import models from django.utils.text import slugify User = settings.AUTH_USER_MODEL # Create your models here. class DefaultProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") bio = models.TextField() def __str__(self): return f"{self.__class__.__name__} object for {self.user}" class Location(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(unique=True) country = models.CharField(max_length=255) region = models.CharField(max_length=255, blank=True, null=True) lat = models.DecimalField(max_digits=9, decimal_places=6) lon = models.DecimalField(max_digits=9, decimal_places=6) timezone_id = models.CharField(max_length=255) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name class Meta: verbose_name_plural = "locations" # class CurrentWeather(models.Model): class Forecast(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="forecasts") created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class DailyForecast(Forecast): date = models.DateField() date_epoch = models.IntegerField() maxtemp_c = models.DecimalField(max_digits=5, decimal_places=2) maxtemp_f = models.DecimalField(max_digits=5, decimal_places=2) mintemp_c = models.DecimalField(max_digits=5, decimal_places=2) mintemp_f = models.DecimalField(max_digits=5, decimal_places=2) …