Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to give a user an authentication token with DRF to use in APIs based only off their username found in headers (no password)
To reach this token generating API on the web the user will have to first authenticate with Oauth2 with their company username/password. This username is now in the header as USERINFO-cn and I can access it with user = request.META['USERINFO-cn'] I want to take the username and assign that user a unique token. I've tried following the example in the django-rest-framework documentation on generating tokens with a customized version of obtain_auth_token. This code gives an error since Token.objects.get_or_create(user=user) is obviously expecting more than just a username. from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.response import Response class CustomAuthToken(ObtainAuthToken): def get(self, request, *args, **kwargs): user = request.META['USERINFO-cn'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user': user }) I know this method may be confusing but basically I want internal users at my company to be able to use other APIs without exposing their password (just a token) but I will at least be able to determine which users are calling APIs based off the token. -
render deploy error return: Not Found: /static/ (folder)
I am working on a web page. I have done two deployments in Render. In one deployment I can't see the images, not load images but yes load css and bootstrap. And in the second deployment it does not detect the static folder, so the site works showing the images but I cannot see css or bootstrap working. Not Found: /static/proyectowebapp/vendor/bootstrap/js/bootstrap.bundle.min.js 127.0.0.1 - - [13/Dec/2023:22:28:21 +0000] "GET /static/proyectowebapp/vendor/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 3385 "https://service-new-2mtd.onrender.com/blog/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" Not Found: /static/proyectowebapp/css/gestion.css 127.0.0.1 - - [13/Dec/2023:22:28:21 +0000] "GET /static/proyectowebapp/css/gestion.css HTTP/1.1" 404 3301 "https://service-new-2mtd.onrender.com/blog/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" What am I doing wrong? I want to deploy my django project on the render page -
Django filter from the model field
I want to make a filter on the site by author for example, I made a language filter like this: models.py CATEGORIES = ( (1, 'Russian'), (2, 'English') ) class Book(models.Model): title = models.CharField(max_length=300) lang_category = models.IntegerField(choices=CATEGORIES, default=1, db_index=True) views.py def index(request, tag_slug=None): books = Book.objects.filter(is_active=True) form = BookFilterForm(request.GET) filtered_queryset = BookFilter(request.GET, queryset=books) if form.is_valid(): if form.cleaned_data['lang_category']: books = books.filter(lang_category__icontains=form.cleaned_data['lang_category']) forms.py class BookFilterForm(forms.Form): LANG_CHOICES = [ ('', 'All languages''), (1, 'Russian'), (2, 'English') ] lang_category = forms.ChoiceField(required=False, choices=LANG_CHOICES, widget=forms.Select(attrs={'class': 'form-select'}), label='Select a language') this works for me, but there is another field that I want to filter by: models.py class Book(models.Model): title = models.CharField(max_length=300) lang_category = models.IntegerField(choices=CATEGORIES, default=1, db_index=True) **author_book = models.CharField(max_length=300)** tell me how you can filter by this type of field I tried this and of course it didn't work: forms.py author_book = forms.ChoiceField(choices=Book.author_book, required=False, widget=forms.Select(attrs={'class': 'form-select'}), label='Author') -
Unable to Run Python HTTP Server on Port 8001 - Need Help in Creating a Minimal, Reproducible Example
Question: I'm encountering an issue while trying to run a Python HTTP server on port 8001 using the command python -m http.server 8001. The server starts, but I'm unable to access it. I've ruled out common problems like port availability and firewall settings. Here's what I've tried: Ensured that port 8001 is not in use by another process. Checked firewall settings to allow traffic on port 8001. Double-checked network configuration. Despite these checks, the issue persists. I'd like to seek help on Stack Overflow, and I want to follow the guidelines for creating a minimal, reproducible example. Can someone guide me on how to structure my question effectively? I want to provide a clear and concise example that others can easily understand and use to help me troubleshoot this problem. Thanks in advance! -
Submit button has no action in Django
I have 3 models in my project and no form is showing any action when the submit button is pressed after putting all the inputs of the form. forms.py class BlogForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'slug', 'thumbnail', 'body', 'status', 'is_subsriber', 'meta', 'author'] models.py class BlogPost(models.Model): author = models.ForeignKey(Author, on_delete = models.CASCADE) title = models.CharField(max_length = 999, unique = True) slug = models.SlugField(max_length = 999, unique = True) thumbnail = ProcessedImageField(upload_to='article', format='JPEG', options={'quality': 60}) body = CKEditor5Field(config_name='extends') meta = models.TextField() status = models.CharField(max_length = 10, choices = blogstatus, default = "DF") is_subsriber = models.BooleanField(default = False) created_on = models.DateTimeField(auto_now_add = True) published_on = models.DateField(auto_now = True) modified_on = models.DateField(auto_now = True) views.py def article_form(request): if request.method == "POST": form = BlogForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("home") else: form = BlogForm() return render(request, 'article/post-form.html', {"form":form}) index.html <form class="form" method="post"> {% csrf_token %} {{form.as_p}} <button type="submit">Publish</button> </form> This is just one model and its form. I've tried using action in the html form but it still doesn't work. -
Add like count to a social network
I am almost done with my project, I completed every step and now I am stuck at the very least, I am not able to show the like count per post in my project. views.py def index(request): posts = Post.objects.all().order_by("date").reverse() paginator = Paginator(posts, 10) number = request.GET.get('page') currentPosts = paginator.get_page(number) likeList = [] try: for like in likes: if like.userLiking.id == request.user.id: likeList.append(like.postLiked.id) except: likeList = [] return render(request, "network/index.html", { "currentPosts": currentPosts }) index.js function like(id, likeList) { if (likeList.indexOf(id) >= 0) { fetch(`/remove/${id}`) .then(response => response.json()) .then(result => { console.log(result), window.location.reload() }) } else { fetch(`/add/${id}`) .then(response => response.json()) .then(result => { console.log(result), window.location.reload() }) } } index.html <div> <ul style="list-style: none"> {% for post in currentPosts %} <li><a href="{% url 'profile' post.user.id %}"> From: {{ post.user }}</a></li> <li><h5 id="description{{ post.id }}">{{ post.description }}</h5></li> <li>{{ post.date }}</li> {% if user.is_authenticated and user == post.user %} <button id="editButton{{ post.id }}" onclick="edit({{ post.id }})">Edit</button><br> <div id="text{{ post.id }}"></div> <div id="save{{ post.id }}"></div> {% endif %} {% if user.is_authenticated %} {% if post.id not in likeList %} <button class="likebtn" id="{{ post.id }}" onclick="like({{ post.id }}, {{ likeList }})">Like</button><br> {% else %} <button class="unlikebtn" id="{{ post.id }}" onclick="like({{ post.id }}, {{ likeList … -
error when return serializer data in Django rest framework
when i try send data with this code: class MeterData1(APIView): def get(self, request, formate=None): queryset = PowerMeter.objects.all(id=10) serializer = PowerMeterSerializer(data=queryset,many=True) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I encounter this error: { "non_field_errors": [ "Invalid data. Expected a dictionary, but got QuerySet." ] } and this is my serializer : class PowerMeterSerializer(serializers.ModelSerializer): class Meta: model = PowerMeter fields = '__all__' and model: class PowerMeter(models.Model): meter_id = models.CharField(max_length=127) State = models.ForeignKey(State, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True, blank=True) VII1 = models.PositiveIntegerField(default=0, blank=True) VII2 = models.PositiveIntegerField(default=0, blank=True) VII3 = models.PositiveIntegerField(default=0, blank=True) VII_avg = models.PositiveIntegerField(default=0, blank=True) Vln1 = models.PositiveIntegerField(default=0, blank=True) Vln2 = models.PositiveIntegerField(default=0, blank=True) Vln3 = models.PositiveIntegerField(default=0, blank=True) Vln_avg = models.PositiveIntegerField(default=0, blank=True) I1 = models.PositiveIntegerField(default=0, blank=True) I2 = models.PositiveIntegerField(default=0, blank=True) I3 = models.PositiveIntegerField(default=0, blank=True) I_avg = models.PositiveIntegerField(default=0, blank=True) P1 = models.PositiveIntegerField(default=0, blank=True) P2 = models.PositiveIntegerField(default=0, blank=True) P3 = models.PositiveIntegerField(default=0, blank=True) P_total = models.PositiveIntegerField(default=0, blank=True) Q1 = models.PositiveIntegerField(default=0, blank=True) Q2 = models.PositiveIntegerField(default=0, blank=True) Q3 = models.PositiveIntegerField(default=0, blank=True) Q_total = models.PositiveIntegerField(default=0, blank=True) S1 = models.PositiveIntegerField(default=0, blank=True) S2 = models.PositiveIntegerField(default=0, blank=True) S3 = models.PositiveIntegerField(default=0, blank=True) S_total = models.PositiveIntegerField(default=0, blank=True) PF1 = models.PositiveIntegerField(default=0, blank=True) PF2 = models.PositiveIntegerField(default=0, blank=True) PF3 = models.PositiveIntegerField(default=0, blank=True) PF_totalMax_Demand_import = models.PositiveIntegerField(default=0, blank=True) Max_Demand_export = models.PositiveIntegerField(default=0, blank=True) Current_Demand = models.PositiveIntegerField(default=0, blank=True) Frequency = models.PositiveIntegerField(default=0, … -
main.models.Flashcard.DoesNotExist: Flashcard matching query does not exist. Even though it does
def deleteCard(request): user = request.user print(request.POST) if request.method == "POST": header = request.POST.get("header") question = request.POST.get("question") answer = request.POST.get("answer") print(header, question) subject = Internal_Subject.objects.get(name="Economics") set = Flashcard_set.objects.get(subject=subject, name="Topic 1") try: flashcard = Flashcard.objects.get(set=set, header=header, question=question, answer=answer) flashcard.delete() print("delete was successful") except Flashcard.DoesNotExist: print("this is not working") flashcardView(request) The object does exist, I've seen it in the admin panel, the parameters are the exact same as the ones used for querying. When I refresh the page the card is still there. There are no duplicates of this model. I've tried filter().first that said nonetype object does not have property delete(), even though the card does exist. Please help I really don't know what I'm doing wrong here. -
Django form doesn't take request.POST values
I have a problem with my project. When i click on the submit button of the form i can see the correct data in request.POST (debug mode), but the function "form.is_valid" return an error. Infact if i skip the function e write only form.save it will raise "NOT NULL constraint failed: fatture_viaggio.distanza_km". Here is my code: def clienti(request): clienti_list = Cliente.objects.all().order_by('nome').exclude(nome='Inalca') viaggi_list = Viaggio.objects.all().order_by('-data_viaggio') if request.method == 'POST': if 'Aggiungi_Cliente' in request.POST: formC = ClienteForm(request.POST) if formC.is_valid(): nuovo_cliente = formC.save() return redirect('clienti') formV = ViaggioForm(request.POST) #if formV.is_valid(): nuovo_viaggio = formV.save() return redirect('clienti') else: formC = ClienteForm() formV = ViaggioForm() return render(request, 'fatture/clienti.html', {'formC': formC, 'formV': formV, 'clienti': clienti_list, 'viaggi': viaggi_list}) The FormC works fine, only the formV has this problem. -
Cannot issue ssl certificate via acm companion from dockerfile
I have a site that should be launched from docker and obtain an SSL certificate for itself, and at the time of launch I receive the following error: nginx-proxy-acme | [Wed Dec 13 17:50:52 UTC 2023] Using CA: https://acme-v02.api.letsencrypt.org/directory nginx-proxy-acme | [Wed Dec 13 17:50:52 UTC 2023] Creating domain key nginx-proxy-acme | [Wed Dec 13 17:50:53 UTC 2023] The domain key is here: /etc/acme.sh/default/admin.innodih.com.ua/admin.innodih.com.ua.key nginx-proxy-acme | [Wed Dec 13 17:50:53 UTC 2023] Single domain='admin.innodih.com.ua' nginx-proxy-acme | [Wed Dec 13 17:50:53 UTC 2023] Getting domain auth token for each domain nginx-proxy-acme | [Wed Dec 13 17:50:55 UTC 2023] Getting webroot for domain='admin.innodih.com.ua' nginx-proxy-acme | [Wed Dec 13 17:50:55 UTC 2023] Verifying: admin.innodih.com.ua nginx-proxy-acme | [Wed Dec 13 17:50:59 UTC 2023] admin.innodih.com.ua:Verify error:185.69.153.243: Fetching http://admin.innodih.com.ua/.well-known/acme-challenge/ietg6hf8EmIOhAh2Z7AJHdrcprTem64hYqxqRlcqOlk: Connection refused nginx-proxy-acme | [Wed Dec 13 17:50:59 UTC 2023] Please check log file for more details: /dev/null nginx-proxy-acme | Sleep for 3600s I've been looking through a lot of problems and couldn't find a specific solution for me, sticking my docker compose: version: "2" services: db: image: postgres:15 container_name: db volumes: - ~/.pg/pg_data/ic:/var/lib/postgresql/data env_file: - .env ports: - "127.0.0.1:15432:5432" web: image: web:latest container_name: web depends_on: - db volumes: - static_volume:/ic/static - media_volume:/ic/media env_file: - .env environment: … -
How to make django file changes that can reflect it on the main server
I have made a change in the django default auth model template. I have added a new column in existing default auth table. So from my project's models.py, I have made change in the django auth model which is present in django.contrib.auth.modela.py So now the changes are stored in migrations file which is present in my local file as comtrib.auth/migration folder is present locally. Now the problem is it is reflecting correctly on my local pc once make migrations and migrate cmds are executed, but when I want to export the code, ofcourse this migration file will not be pushed, and the main server does not run this 2 cmds as it reads it automatically from migration files to avoid any future loss so how do I put it on the main server so that it can be implemented and people can start seeing the change. Thank You 🙌🏻 The only thing is server does not run any cmds like makemigrations and migrate and also manually storing file at particular location doesn't help either. -
IndexError while performing Subqueries on django
I have a post list for which I am trying to retrieve some data from its related models, to display in a post list. The data I need is the latest comment made, the user, the user group and the date and text of the comment. I am trying to achieve this result with this complex annotate query: all_posts=Post.objects.all() posts = all_posts.annotate( comment_count=Count('comment'), g_origin=Coalesce(Subquery( PostGroup.objects.filter(post=OuterRef('pk')).values('group') ), Value(0)), latest_comment_author=Coalesce(Subquery( PostComment.objects.filter(post=OuterRef('pk')).values('user__user') ), Value(''), latest_comment_created=Coalesce(Subquery( PostComment.objects.filter(post=OuterRef('pk')).order_by('-created').values('created') ), Value('')), latest_comment_text=Coalesce(Subquery( PostComment.objects.filter(post=OuterRef('pk')).order_by('-created').values('text') ), Value('')) ) But this is just resulting in IndexError: list index out of range, but looks like the error is being originated within Django's internal files. Some posts could have no comments, no user or no data, but I used to think I could solve that with Coalesce(x, default_value, but it's still giving the error) I also tried to reduce it to just all_posts=Post.objects.all() posts = all_posts.annotate( comment_count=Count('comment') ) or to all_posts=Post.objects.all() posts = all_posts.annotate( g_origin=Coalesce(Subquery( PostGroup.objects.filter(post=OuterRef('pk')).values('group') ), Value(0)), ) But still, it's giving the error. What could the problem be? -
Django time zone issue in my project dash board
I can't get the today_entries,week_entries and month_entries in the following code : class DashBoardView(APIView): def get(self, request): # Count the number of users total_users = User.objects.count() total_workers = User.objects.filter(role='worker').count() total_credits = Decimal(0.00) total_debits = Decimal(0.00) wallet_entries = AdminWallet.objects.all() print("wallet entries",wallet_entries) today = timezone.now() print("today",today) start_of_week = today - timezone.timedelta(days=today.weekday()) print("start_of_week",start_of_week) start_of_month = today.replace(day=1) print("start of the month",start_of_month) start_of_year = today.replace(month=1, day=1) print("start of the year",start_of_year) for entry in wallet_entries: total_credits += entry.credit total_debits += entry.debit total_balance = total_credits - total_debits print("total balance",total_balance) week_entries = wallet_entries.filter(created_at__gte=start_of_week) print("week entries",week_entries) month_entries = wallet_entries.filter(created_at__gte=start_of_month) print("month entries",month_entries) year_entries = wallet_entries.filter(created_at__gte=start_of_year) print("year entries",year_entries) total_revenue_week = sum(entry.credit for entry in week_entries) - sum(entry.debit for entry in week_entries) total_revenue_month = sum(entry.credit for entry in month_entries) - sum(entry.debit for entry in month_entries) total_revenue_year = sum(entry.credit for entry in year_entries) - sum(entry.debit for entry in year_entries) Pending_Bookings = Appointment.objects.filter(status='Pending').count() Accepted_Bookings = Appointment.objects.filter(status='Accepted').count() Cancelled_Bookings = Appointment.objects.filter(status='Cancelled').count() Rejected_Bookings = Appointment.objects.filter(status='Rejected').count() today_entries = wallet_entries.filter(created_at__date=today) print("today entries",today_entries) total_revenue_today = sum(entry.credit - entry.debit for entry in today_entries) seven_days_ago = today - timezone.timedelta(days=7) daily_Bookings_data = [] daily_revenue_data = [] for i in range(7): day_start = seven_days_ago + timezone.timedelta(days=i) day_end = day_start + timezone.timedelta(days=1) Appointments_on_day = Appointment.objects.filter(date1__gte=day_start, date1__lt=day_end).count() revenue_on_day = wallet_entries.filter(created_at__date=day_start).aggregate( total_credit=Sum('credit'), total_debit=Sum('debit') ) print("revenue on day",revenue_on_day) … -
Django display any querry as html table
I want to display a simple query in my database as an HTML table. But i a missing something either in the template or general logic of data management in Django. First i am creating a model like that : class Book(models.Model): title = models.CharField(max_length=128, unique =True) quantity = models.IntegerField(default=1) Then making a view with a context containing both the column's names of the query and the query object such as : def books(request): context = {"rows":Book.objects.all(),"fields" : Book._meta.get_fields()} return render(request,"blog/books.html",context) Finally i am trying to iterate over the value of the query in my template so i can put them in a HTML table: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Our Books</title> </head> <body> <table border="1"> <thead> <tr> {% for field in fields %} <th>{{ field.verbose_name }}</th> {% endfor %} </tr> </thead> <tbody> {% for row in rows %} <tr> {% for field in fields %} <td>{{ row[field] }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> </body> </html> Adding the header of the table works fine but this part is not working : {% for row in rows %} <tr> {% for field in fields %} <td>{{ row[field] }}</td> {% endfor %} </tr> {% endfor %} … -
Django Admin Search - returning duplicates when search_field includes many-to-many
I'm receiving multiple duplicate objects when using Django Admin search. I have two models involved. Organisation and OrgAlias(Organisation Alias). Each Organisation may have multiple aliases and each alias may be attached to multiple Organisations. The models: class OrgAlias(models.Model): name = models.CharField(max_length=255,unique=True) def __str__(self): return self.name class Organisation(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) aliases = models.ManyToManyField(OrgAlias) ... My Django Admin class: class OrganisationAdmin(admin.ModelAdmin): search_fields = ['aliases__name'] ... I've tried overriding the ModelAdmin get_search_results function with various strategies. e.g. def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super().get_search_results(request, queryset, search_term) queryset = queryset.distinct() return queryset, use_distinct The result is always the same. If I have 3 aliases attached to and organisation. The organisation will appear 3 times in the search results. Similar queries work fine in the shell. It's just in django admin the problem appears. Is there a simple fix or workaround for this? -
Why is my Jquery autocomplete not working on my search bar?
I have a search bar that should be visible in all my pages in django, however the autocomplete is not working. my bse.html has the following: <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> this is my search bar: <div class="sbar "> <div class="row-search "> <div class="col-6"> <form action="{% url 'search' %}" method="get"> <div class="input-size input-group mb-3"> <input type="text" name="q" id="searchBox" class="form-control" placeholder="Search..."> <button class="btn btn-primary" type="submit">Search</button> <div id="search-suggestions-dropdown"></div> <!-- Add this line --> </div> </form> </div> </div> </div> this is my script inside my base.html: <script> $(document).ready(function(){ $('#searchBox').autocomplete({ source: function(request, response) { console.log("Making AJAX request with query:", request.term); $.ajax({ url: "{% url 'search' %}", dataType: 'json', data: { 'q': request.term }, success: function(data) { console.log("Received data:", data); var suggestions = []; data.forEach(function(item) { suggestions.push({ label: item.label, value: item.value }); }); response(suggestions); } }); }, minLength: 2, select: function(event, ui) { console.log("Selected item:", ui.item); window.location.href = ui.item.value; } }); }); </script> this is from my views.py: class SearchView(View): def get(self, request, *args, **kwargs): query = request.GET.get('q') print("Received query:", query) # Print the received query if query: infos = Info.objects.filter(Q(firstName__icontains=query) | Q( middleName__icontains=query) | Q(lastName__icontains=query)) files = Files.objects.filter(fileName__icontains=query) results = list(infos.values('firstName', 'middleName', 'lastName', 'orphanID')) + list(files.values('fileName', 'fileID')) results = [ { 'label': … -
Insert the row to the Queryset manually
I have objects and filter, which get the label value pair from database. results = (m.Drawing.objects. annotate(label=F('update_user__name'),value=F('update_user')). values('label','value'). annotate(dcount=Count('update_user__name')). order_by()) print(results) serializer = s.SearchChoiceSerializer(instance=results, many=True) Results is like this,print(results) <SafeDeleteQueryset [{'label': 'admin', 'value': 1, 'dcount': 13}, {'label': 'demouser1', 'value': 2, 'dcount': 13}]> Now, I want to insert this {'label':'myuser', 'value':2,'dcount':23} to SafeDeleteQuerySet manually before sending to the serializer. I it possible? -
Problem with Error 502 in simple django method
I have a strange problem with django. I'm taking my first steps in Python, so maybe this question is stupid - if so, I apologize in advance :) I have 2 methods: def method1(self): url = settings.PAYMENT_GATEWAY_URL + "payments/" + self.bank_account_nr + "/" + settings.PAYMENT_POS_ID + "/function1/" ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE data = urllib.request.holiday(url, context=ctx) contents = data.read().decode('utf-8') # content = '{"amount_sum": "120.00"}' data = json.loads(contents) data = data.get("amount_sum") return data def method2(self): url = settings.PAYMENT_GATEWAY_URL + "payments/" + self.bank_account_nr + "/" + settings.PAYMENT_POS_ID + "/function2/" ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE data = urllib.request.holiday(url, context=ctx) contents = data.read().decode('utf-8') data = json.loads(contents) return data function2 return : {"status": "OK", "paymentsA": 1, "paymentsCt": 1, "paymentsD": 0} function1 return {"amountsum": "120.00"} When calling method 1 - everything works fine, in the case of method 2 the application takes a very long time and throws error 502, Both links load quickly in the browser. Both web addresses are on 1 server and are 1 application -
How to create Django Rest Framework translate mixin?
I'm trying to write a django translate mixin for my project. I configured the settings.py file, created a model, view, serializer and mixin. when I run the application an error occurs: "TranslationFieldMixin.get_field_names() missing 2 required positional arguments: 'declared_fields' and 'info'". This error occurred after I added this code to my serializer: def to_representation(self, instance): language = get_language() self.fields = self.get_field_names(language=language) return super().to_representation(instance) How can I solve this problem? SETTINGS.PY INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'parler', 'rest_framework', 'store', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'en-us' LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGES = [ ('en', _('English')), ('es', _('Spanish')), ('fr', _('French')), ('ru', _('Russian')), ] TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True MODELS.PY from django.utils.translation import gettext_lazy as _ class Article(models.Model): title = models.CharField(_('title'), max_length=100) content = models.TextField(_('content')) def __str__(self): return self.title VIEWS.PY class ArticleDetailAPIView(RetrieveUpdateDestroyAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer SERIALIZERS.PY class ArticleSerializer(TranslationFieldMixin, serializers.ModelSerializer): class Meta: model = Article fields = ['id', 'title', 'content'] def to_representation(self, instance): language = get_language() self.fields = self.get_field_names(language=language) return super().to_representation(instance) UTILS.PY class TranslationFieldMixin(): def get_field_names(self, declared_fields, info, language=None, *args, **kwargs): field_names = super().get_field_names(declared_fields, info, *args, **kwargs) if language: translated_field_names = [ str(_(field_name)) … -
USE_L10N deprecated, but it disables DATETIME_INPUT_FORMATS when removed
Have I found a bug in Django? The config setting USE_L10N is deprecated since 4.0 and scheduled for removal in 5.0. However, the documentation of forms.DateField for 5.0 still states If no input_formats argument is provided, the default input formats are taken from the active locale format DATE_INPUT_FORMATS key, or from DATE_INPUT_FORMATS if localization is disabled. Which begs the question, how does one disable localisation and enable the DATE_INPUT_FORMATS setting once USE_L10N = False is not longer possible? I don't want to upgrade to 5.0 yet, so I cannot easily test this. I have established that on 4.2, if I comment out the deprecated USE_L10N = False in my settings.py, then DATE_INPUT_FORMATS ceases to be honoured. I wonder whether anybody running Django 5.0 can comment? -
Django API Database Design for both Multi-Tenant and Customer (No-Tenancy) Authentication
I am developing a backend API using Python Django Rest Framework. The frontend will handle authentication at these 3 URL paths: Customer Authentication URL: www.mydomain.com Functionality: Customers can search for and purchase products. To complete a purchase, customers must create an account. This account provides access to view purchase history and the option to save payment methods. Multi-Tenancy Authentication URL with tenant subdomain: myclient.mydomain.com Functionality: Clients can login to manage their accounts and add their products to sell. Additionally, clients need the ability to give their employees their own login to assist in managing their listed products. Internal Admin Authentication URL with admin subdomain: admin.mydomain.com Functionality: Admins can access tools for customer and client support. What would be the best way to design my database schema to handle this in the most efficient way and also keeping my database organized and as clutter free as possible? I am just now starting this part of my project, so I do not have any code written for my schema as of yet. I have done a ton of Googling and YouTubing to find a solution and there isn't a whole lot of info on multi-tenancy architecture around the use case that I … -
Managing migrations while moving from default taggit tags to taggit custom tags
I was working on adding Tags to Articles, Comments using django-taggit. Butnow I need the Tags to be associated with Account - so every tag must be tied to an account_id and only Articles, Comments of that Account can access these tags. To achieve this, I had to implement a CustomTag. In between these two stages, there were few other migrations relavant to other models. Example 0021_add_tags_to_articles_and_comments.py 0022_some_other_model_migration.py 0023_some_other_model_migration.py 0024_use_custom_tag_with_custom_taggedobject.py Taggit documentation mentions the below to remove the tables taggit created and using custom tags But this is messing up with my initial migration that added taggit tables because 0021_add_tags_to_articles_and_comments.py has dependencies class Migration(migrations.Migration): dependencies = [ ( "taggit", "0006_rename_taggeditem_content_type_object_id_taggit_tagg_content_8fc721_idx", ), ("blog_app", "0020_blog"), ] I cant delete all the migrations and redo them because of these changes are being used in current app. Is there any way to achieve this? Apologies if the question doesn't seem well explained. -
How to filter by user or all users in same viewset in Django REST framework
I am a beginner in Django REST Framework and I want to ask how I can (and if at all possible) filter listings by user id or return all listings if user id is not set as a query parameter. Also, each user should be able to edit or delete only their own listings, but be able to see the listings of other users if the parameter is_listed=true. Here is the corresponding code: views.py class ListingViewSet(viewsets.ModelViewSet): """ Viewset for API endpoint that implements CRUD operations for listing(cards for sale). - To perform listing search for all users use base endpoint (api/listing/). - To perform listing search by 'is_listed' use base endpoint with ?is_listed=true/false parameter. - To perform listing search for specific user use base endpoint with ?user_id=<user_id> parameter. - To perform PUT or PATCH use base endpoint with /<listing_id> parameter. """ queryset = Listing.objects.all().order_by('id') serializer_class = ListingSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [DjangoFilterBackend] filterset_class = ListingFilter def get_queryset(self): user = self.request.query_params.get('user_id', None) if user: if [IsOwner()]: return self.queryset.filter(user=user) return self.queryset def perform_create(self, serializer): serializer.save(user=self.request.user) urls.py urlpatterns = [ path('', views.ListingViewSet.as_view({'get': 'list', 'post': 'create'}), name='listing'), path('<int:pk>/', views.ListingViewSet.as_view( {'get': 'retrieve', 'put': 'update', 'delete': 'destroy', 'patch': 'partial_update'}), name='listing_detail'), ] serializers.py class ListingSerializer(serializers.ModelSerializer): card_name … -
Django existing db records not found in testcase when using postgresql
ubuntu 22.04, mysql 8.0.35, postgresql 16.1, python 3.8.18, django 4.2 django default db = "mydb" We have a large data set saved in "mydb", generating that takes a long time. While using mysql db, I was able to fetch items from "mydb" like <ModelName>.objects.filter() in my test cases. I'm unsure if records are copied into "test_" db from "mybd" by django. Then I switched to postgres, recreated the data. When I fetch the data in APiView, it's working fine. But in testcases all model queries return blank queryset. Is there a workaround for testcases while using postgres so I would not have to recreate the data every time I run the tests ? Thanks. -
I am building Django Web Application .I am using rest-framework but i am so confused How to intregate django rest-framework with frontend
Like this method i am getting the data but how will i render the data in html file `@api_view(['POST']) @authentication_classes([JWTAuthentication]) @permission_classes([IsAuthenticated]) def homeapi(request): try: data = json.loads(request.body.decode('utf-8')) print(data) # Dummy student data (replace this with your logic to fetch real data from a database) dummy_students = [ {'id': 1, 'name': 'Alice', 'age': 20, 'grade': 'A'}, {'id': 2, 'name': 'Bob', 'age': 22, 'grade': 'B'}, {'id': 3, 'name': 'Charlie', 'age': 21, 'grade': 'C'}, # Add more students as needed ] # Return student details as JSON response return JsonResponse({'students': dummy_students}) except Exception as e: return JsonResponse({'error': str(e)}, status=400)` I am expecting that first i am requesting the data from an API after getting the data i want to show it to the user how will i do that.