Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
absolute path? `upload_to` of models.FileFIeld
I have FileField in models.py class DocFile(models.Model): document = models.FileField(upload_to='_mat/') It works well for local(mac),and the file is stored under /Users/whitebear/myproj/_mat/ However I do the same thing on server (Ubuntu 20, using ENGINX-unit) It shows the error PermissionError: [Errno 13] Permission denied: '/_mat' But, /var/www/html/myproj/_mat/ permission is 777 So I guess, somehow it trys to make /_mat as absolute path ..??? If I set upload_to like this , document = models.FileField(upload_to='/var/www/html/myproj_mat/') It says to use 'relative path' These are error stack trace. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/var/www/html/aicomposer/current/defapp/views.py", line 350, in post entry.save() File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/db/models/query.py", line 1270, … -
Display model items grouped by the category they belong to (kanbam board style) using Django and Vue.js
Hi I hope you are all well. Am working on a kanban board app with Django as backend and Vue.js. as frontend. I have 2 models: Status and Items. Items contains status as a foreignkey from Status model. api/models.py from django.db import models from django.contrib.auth.models import User class Status(models.Model): created_by = models.ForeignKey(User, related_name='status', on_delete=models.CASCADE, null=True) status = models.CharField(max_length=50, null=True) def __str__(self): return self.status class Items(models.Model): PRIORITY_CHOICES = ( ("High", "danger"), ("Medium", "info"), ("Low", "primary"), ) notes = models.CharField(max_length=255, null=True) status = models.ForeignKey(Status, null=True, blank=True, on_delete=models.CASCADE) priority = models.CharField(max_length=15, null=True,choices=PRIORITY_CHOICES, default="2") start_date = models.DateField(null=True) end_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='task', on_delete=models.CASCADE, null=True) def __str__(self): return self.notes And am using class based views in my api/views.py views.py screenshot api/serializers.py from rest_framework import serializers from .models import Items, Status class ItemsSerializer(serializers.ModelSerializer): class Meta: model = Items read_only_fields = ( 'created_by', 'created_at', ) fields = ('id','notes','status','priority','start_date','end_date') class StatusSerializer(serializers.ModelSerializer): class Meta: model = Status read_only_fields = ( 'created_by', ) fields = ('status','id','pk') The problem - I want to display items created in my app in a column whereby the column name is the Status.status and under every column I want to display all Items.notes(items represents tasks that user creates) that contain … -
How to use celery progress bar in a function in the class?
I want to create a progress bar for my project. I have a class and this class has some functions. Especially, one of them takes a long time (def download_all) and this is my main reason for wanting to create a progress bar. I successfully set up celery, celery-progress, etc. and they work all fine. My problem is this: I want to integrate the progress bar to download_all function. I try a lot of things but it gives errors. This is my code. How can I do it? views.py def setup_wizard(request): ... task = (functions.myClass(n_username, n_password, n_url, n_port, db_password, username=request.user.username)) task_id = task.task_id ... context = { ... 'task_id':task_id } functions.py @shared_task(bind=True) class myClass(): def __init__(self, nessus_user, nessus_password, nessus_url, nessus_port, db_password, username): self.location = zt_dosya_url self.static_fields = {} self.download_all(n_user, n_password, n_url, n_port, db_password) self.send(username) ... def download_all(self, n_user, n_password, n_url, n_port, db_password): ... for s in scans: i = 0 scanner.scan_name = s['name'] ... // I have to get the values of progress bar from here //for example // progress_recorder.set_progress(i + 1, len(scans), f'On iteration {i}') ... i += 1 -
Django multiple user types migration error
I'm trying to create a multiple user types using Django Abstract User but whenever I try to migrate the changes it gives me an error. As I'm still new to Django, I don't understand that it means Here is my models code: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): is_customer = models.BooleanField(default = False) is_seller = models.BooleanField(default = False) name = models.CharField(max_length = 60) And whenever I try to migrate this model I get this error: ERRORS: Accounts.CustomUser.groups: (fields.E304) Reverse accessor for 'Accounts.CustomUser.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'Accounts.CustomUser.groups' or 'auth.User.groups'. Accounts.CustomUser.user_permissions: (fields.E304) Reverse accessor for 'Accounts.CustomUser.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'Accounts.CustomUser.user_permissions' or 'auth.User.user_permissions'. auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'Accounts.CustomUser.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'Accounts.CustomUser.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'Accounts.CustomUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'Accounts.CustomUser.user_permissions'. -
How to manage a form with many-to-many intermediate table fields and class-based views?
I would like to be able to edit an article directly via the web page where it is displayed. For this I use the UpdateView. My "News" model has a many to many relationship with my "User" model. The intermediate model is called "NewsUpdate" and it has 2 additional fields (update_date and update_reason). I can display and run the edit form of my "News" model, but I can't add the "update_reason" field and validate it. Is it possible to do this with the generic views? Thank you in advance! models : class News(models.Model): ... image = models.ImageField(upload_to='contents', null=True, blank=True) uuid = models.UUIDField(default=uuid.uuid4, unique=True, verbose_name='UUID') author = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Auteur', related_name='create_news') news_update_user = models.ManyToManyField(AUTH_USER_MODEL, through='contents.NewsUpdate', related_name='news_update_user') news_delete_user = models.ManyToManyField(AUTH_USER_MODEL, through='contents.NewsDelete', related_name='news_delete_user') class NewsUpdate(models.Model): news = models.ForeignKey(News, on_delete=models.CASCADE, related_name='updated_news') updater = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Auteur', related_name='news_updater') update_date = models.DateTimeField(auto_now=True, null=True, verbose_name='Modification le') update_reason = models.CharField(max_length=250, verbose_name='Raison de la modification') class Meta: unique_together = ('news', 'updater') class User(AbstractUser): first_name = models.CharField( max_length=30, blank=True, null=True, verbose_name='Prénom' ) last_name = models.CharField( max_length=30, blank=True, null=True, verbose_name='Nom' ) ... News update view : class NewsUpdateView(SuccessMessageMixin, UpdateView): model = News template_name = 'contents/news_update.html' success_message = 'La news a bien été mise à jour !' fields = ['category', 'title', 'content', … -
fetch dosent bring any data
when i use fetch to bring the list of notes and consol.log it nothing shows up. The url is not wrong i have carefully checked it. Here is the code: import React, { useState, useEffect } from 'react' const NotesListPage = () => { let [notes, setNotes] = useState([]) useEffect(() => { }, []) let getNotes = async () => { let response = await fetch('http://127.0.0.1:8000/api/notes/') let data = await response.json() console.log(data) setNotes(data) } return ( <div> </div> ) } export default NotesListPage here is the api part: @api_view(['GET']) def getNotes(request): notes = Note.objects.all() serializer = NoteSerializer(notes, many=True) return Response(serializer.data) -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. when i try to import models in consumers.py on heroku
i run my django project on local which import models on consumers.py that work but when i deploy on heroku error occurred 2021-11-06T10:22:14.039525+00:00 app[web.1]: Traceback (most recent call last): 2021-11-06T10:22:14.039542+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2021-11-06T10:22:14.039607+00:00 app[web.1]: sys.exit(CommandLineInterface.entrypoint()) 2021-11-06T10:22:14.039607+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 170, in entrypoint 2021-11-06T10:22:14.039690+00:00 app[web.1]: cls().run(sys.argv[1:]) 2021-11-06T10:22:14.039697+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 232, in run 2021-11-06T10:22:14.039772+00:00 app[web.1]: application = import_by_path(args.application) 2021-11-06T10:22:14.039778+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/utils.py", line 12, in import_by_path 2021-11-06T10:22:14.039824+00:00 app[web.1]: target = importlib.import_module(module_path) 2021-11-06T10:22:14.039830+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-11-06T10:22:14.039892+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-11-06T10:22:14.039898+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-11-06T10:22:14.039963+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-11-06T10:22:14.040002+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-11-06T10:22:14.040040+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-11-06T10:22:14.040078+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2021-11-06T10:22:14.040124+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-11-06T10:22:14.040163+00:00 app[web.1]: File "/app/./spotgame/asgi.py", line 16, in <module> 2021-11-06T10:22:14.040212+00:00 app[web.1]: import spotifymusicgame.routing 2021-11-06T10:22:14.040218+00:00 app[web.1]: File "/app/./spotifymusicgame/routing.py", line 3, in <module> 2021-11-06T10:22:14.040261+00:00 app[web.1]: from . import consumers 2021-11-06T10:22:14.040268+00:00 app[web.1]: File "/app/./spotifymusicgame/consumers.py", line 59, in <module> 2021-11-06T10:22:14.040324+00:00 app[web.1]: from .models import roomInfo 2021-11-06T10:22:14.040330+00:00 app[web.1]: File "/app/./spotifymusicgame/models.py", line 10, in <module> 2021-11-06T10:22:14.040373+00:00 app[web.1]: class songModel(models.Model): 2021-11-06T10:22:14.040379+00:00 app[web.1]: File … -
How to disable django forms radio button depending on anotehr radio button value
I have a Django form with two sets of radio buttons. I would like to block two choices in the second set depending on the selected button in the first set. How can I do that? Do I have to write a function for it in views? forms.py DOWNLOAD_CHOICES = [("all", "All values"), ("all_divide", "All values separated per IfcType"), ("unique", "Unique values"), ("unique_divide", "Unique values separated per IfcType")] FORMAT_CHOICES = [("xlsx", "Excel (.xlsx)"), ("csv", "comma-separated values (.csv)")] class DownloadForm(forms.Form): file_format = forms.ChoiceField(choices=FORMAT_CHOICES, widget=forms.RadioSelect()) file_download = forms.ChoiceField(choices=DOWNLOAD_CHOICES, widget=forms.RadioSelect()) model_form_download.html <form action="" name="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Download"> </form> I think that my views.py is not relevant to this question, so I am not posting it now. It is too long anyways... -
PYTHON DJANGO HOSTING IN GODADDY - FACING FOLLOWING ERROR "The requested URL was not found on this server."
I'm trying to host a python django test site in godaddy cpanel hosting. My first index page has only heading and "next page" link. Whereas the next page has few test text. On choosing the next page i get an error as Not Found The requested URL was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. I am not sure why my next page is not being accessible. -
Getting error add() got an unexpected keyword argument 'override_quantity' in Django
When I run the URL http://localhost:8000/cart/add/1/ it gives me error: TypeError: add() got an unexpected keyword argument 'override_quantity'. Can anyone please help me why I'm getting this error? here I have added my whole code. urls.py app_name = 'cart' urlpatterns = [ path('', views.cart_detail, name='cart_detail'), path('add/<int:product_id>/', views.cart_add, name='cart_add'), path('remove/<int:product_id>/', views.cart_remove, name='cart_remove'), ] forms.py from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1,21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField( choices = PRODUCT_QUANTITY_CHOICES, coerce=int) override = forms.BooleanField(required=False, initial = False, widget=forms.HiddenInput) views.py @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], override_quantity=cd['override']) return redirect('cart:cart_detail') @require_POST def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart': cart}) -
Add multiple objects in same form
I have a form to take a ticket for bus But you also can add another ticket and fill the same form I handle this with Ajax like this: function createTickets() { let tickets = document.querySelectorAll(".ticket-form"); for (var i = 0; i < tickets.length; i++) { let ticketForm = tickets[i].querySelectorAll("input"); let single_data = {}; for (var j = 0; j < ticketForm.length; j++) { single_data[ticketForm[j].name] = ticketForm[j].value; } var csrftoken = $('[name="csrfmiddlewaretoken"]').val(); $.ajax({ url: window.location.origin + "/tickets/create-ticket/", headers: { "X-CSRFToken": csrftoken, }, type: "POST", data: single_data, success: function (data) { console.log("maca"); }, error: function (err) {} }); } } This is my views.py def ticket_create(request): ticket_form = TicketForm(request.POST) if ticket_form.is_valid(): ticket_form.save() return HttpResponse("") Is this good way, or I can handle in another way? -
Using file.js in the script of an external html document, which is not on the server
I would like to use a file.js document from my Django-Server as a script of an external html-document, which does not belong to my server. That´s why I tried to implement the file.js as an path and use the link of this path for my html document as a script, but it did not work because the script could not be gotten from the html document. Does anyone has an advice for me what I did wrong? file.js: var test = {“variable“:“test“} test.html: <script href=“https://url_of_my_server/file.js“> </script> -
Celery task (.delay()) causes Django to freeze if I'm using Gunicorn or uWsgi
If I'm using celery with Django (by calling .delay()) while using Gunicorn or uWsgi it causes it to freeze and eventually timeout. I'm guessing it gets stuck trying to send task to broker. This is happening on both developer server and production server, where both are running Ubuntu 20.04. Using built in developer server using python3 manage.py runserver works without any issues. And removing the .delay() also makes it work automatically. Example task: @shared_task def SayHello(): print('Hello!') Celery config in settings.py: CELERY_BROKER_URL = 'redis://:password@ip:6379' CELERY_RESULT_BACKEND = 'redis://:password@ip:6379' CELERY_ACCEPT_CONTENt = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER ='json' init.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) celery.py (in project folder with settings.py): import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject.settings') app = Celery('djangoProject') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all … -
I got this Django error MultiValueDictKeyError while clicking on "view" button
I need help I got an error in my project when I click on the "view button" to open the post i get this error : MultiValueDictKeyError at /Post/21 'bid' Request Method: GET Request URL: http://127.0.0.1:8000/Post/21 Django Version: 3.2.8 Exception Type: MultiValueDictKeyError Exception Value: 'bid' I think there is something wrong with my "viewList def" because of the bid: please take a look on my code view.py (form class) class BidForm(ModelForm): class Meta: model = Bid fields = ['bid'] def viewList(request, id): # check for the watchlist listing = Post.objects.get(id=id) user = User.objects.get(username=request.user) if listing.watchers.filter(id=request.user.id).exists(): is_watched = True else: is_watched = False if not listing.activate: if request.POST.get('button') == "Close": listing.activate = True listing.save() else: price = float(request.POST['bid']) bids = listing.bids.all() if user.username != listing.creator.username: if price <= listing.startBid: return render(request, 'auctions/item.html', { "listing": listing, 'form': BidForm(), "message": "Error! Your bid must be largest than the current bid!", }) form = BidForm(request.POST) if form.is_valid(): bid = form.save(commit=False) bid.user = user bid.save() listing.bids.add(bid) listing.bid = price listing.save() else: return render(request, 'auctions/item.html', { "form": BidForm() }) return HttpResponseRedirect(reverse('viewList', args=(listing.id,))) context = { 'listing': listing, 'comment_form': CommentForm(), 'comments': listing.get_comments.all(), 'is_watched': is_watched, 'form': BidForm() } return render(request, 'auctions/item.html', context) model.py class Bid(models.Model): user = models.ForeignKey(User, … -
my form.cleaned_data['object'] is printing None
my Django form ''' class servicesform(forms.ModelForm): class Meta: model = services fields = ['supplies', 'airport', 'goods', 'package', 'shipping', 'food', 'drunk', 'animals', 'additional_service', 'price'] widgets = {'supplies': forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'flexCheckDefault'} 'airport': forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'flexCheckDefaultt'} 'goods': forms.NumberInput(attrs={'class': 'addservices form-control', 'placeholder': '$'}), 'package': forms.NumberInput(attrs={'class': 'addservices form-control', 'placeholder': '$'}) 'shipping': forms.NumberInput(attrs={'class': 'addservices form-control', 'placeholder': '$'} 'food': forms.NumberInput(attrs={'class': 'addservices form-control', 'placeholder': '$'}), 'drunk': forms.NumberInput(attrs={'class': 'addservices form-control', 'placeholder': '$'}), 'animals': forms.NumberInput(attrs={'class': 'addservices form-control', 'placeholder': '$'}) 'additional_service': forms.TextInput( attrs={'class': 'addservices form-control', 'placeholder': 'additional'}), 'price': forms.NumberInput( attrs={'class': 'addservices form-control timepicker', 'placeholder': '$'})} my views.py file ''' def Signup2(request): form = Registerform2() service_form = servicesform() if request.method == "POST": service_form = servicesform(request.POST) form = Registerform2(request.POST) if form.is_valid(): data = form.save(commit=False) print(data, request.user.id, 'data') data.user = request.user data.save() else: print(form.errors) if service_form.is_valid(): print(service_form) price = service_form.cleaned_data['price'] add_ser = service_form.cleaned_data['additional_service'] print(price, add_ser) services.objects.create(user=request.user, additional_service=add_ser, price=price) service_data = service_form.save(commit=False) service_data.user = request.user service_data.save() else: print(service_form.errors) return redirect('/') ''' here is my models.py file ''' class services(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) supplies = models.BooleanField(default=False) airport = models.BooleanField(default=False) goods = models.IntegerField(null=True, blank=True) package = models.IntegerField(null=True, blank=True) shipping = models.IntegerField(null=True, blank=True) food = models.IntegerField(null=True, blank=True) drunk = models.IntegerField(null=True, blank=True) animals = models.IntegerField(null=True, blank=True) additional_service = models.CharField(max_length=100, null=True, blank=True) price = models.IntegerField(null=True, blank=True) ''' … -
how to complete some part of form in another page?
I made a contact form for the users to complete in their profile. It consists of some simple fields like address and phone number and a location field to choose their coordination on a map. However, I want the location field on another page. for instance, when a user wants to fill this form, they first fill in other fields, then by clicking a button they get redirected to another page to fill the location field and then again return to the form and submit everything. is this even possible? how can I submit part of a form on a page and the rest on another page? -
How are applications (which accepts different types of requests like http and smtp) deployed on different ports on servers?
I'm a beginner in all these http and tcp/ip thing. So there maybe many things in these questions that may not make sense or are totally incorrect. First I will add all the questions I had in mind since, I could not put them on title. I work on django (python framework) for web development. I'm confused as to how servers work. And how is the destination port is decided through the url? MAIN Q : What I have learned so far is that through DNS we get the ip address of the website. And port (Both destination and source) are decided by the TCP. And sent through TCP headers. But how does it decide which port should it go to in a server(i.e. destination port). MY ANS TO ABOVE QUESTION : After spending lots of my time, I have come to know that, http requests default to 80 and https defaults to 443 and similarly other types of requests also defaults to some port. So we can figure out the ip address based on this. But this rises another question in my mind. Another Question : I have also built a simple django website and deployed it on pythonanywhere. … -
Class OfferSerializer missing "Meta.model" attribute
I have been trying to build offer management app in Django rest framework. So i made following serilizer class OfferSerializer(serializers.ModelSerializer): class Meta: fields = { 'id' 'Name' 'valid_from' 'valid_to' 'is_disabled' } fields = '__all__' and when i passed following in jason format { "id":1, "Name" : "Discount Offer", "valid_from":"2021-05-21", "valid_from":"2021-08-21", "is_disabled":1 } But i am getting error :- Class OfferSerializer missing "Meta.model" attribute In above code i have created meta mode; but still why I am getting that error? -
How do I refresh my JWT provided by Django-Rest-Framework, using Apisauce from my React-Native App?
I am building an Application with Django-Rest-Framework backend and using dj-rest-auth for authentication with Simple JWT and for the frontend I am using React-Native and am making my api calls using api-sauce (github link -> API-Sauce). API-Sauce is built on axios This is my basic clientAPI code which hits the Django-Rest-Framework from my React-Native app import { create } from "apisauce"; import authStorage from "../auth/authStorage"; const baseURL = "http://192.168.0.109:8000/api"; const apiClient = create({ baseURL: baseURL, }); apiClient.addAsyncRequestTransform(async (request) => { const authToken = await authStorage.getToken(); if (!authToken) return; request.headers["Authorization"] = "Bearer " + JSON.parse(authToken).access_token; }); export default apiClient; This works perfectly as long as the Token is active. Once the token has expired, to refresh my token I have to do the following Target URL - http://192.168.0.109:8000/api/token/refresh/ Header - "Content-Type" : "application/json" data - {"refresh":"refresh_token"} // refresh_token is obtained from authStorage in the above code-snippet like so //JSON.parse(authToken).refresh_token How can I efficiently add the code which refreshes my token, to my existing code, which makes my API to call refreshes the token automatically? -
Django: Passing variable from view to view via url link
I am learning Django and as part of a project, am trying to reference a topic from view1 called "page" (containing content) to be passed into view2 called "editpage" (where I can edit the respective topic). I believe one way to do this is via sessions, but given I only need to reference the topic a single time when the user wants to edit view1 - is there a way to pass the topic from view1 to view2 without sessions and forget the topic once the edit has been made? From the best answer to the question below, it seems I can do it via redirects? But I cannot find a way to use redirects with url links. Django Passing data between views My attempted approach was to have the editpage url contain the topic from view1, but I do not know how to pass the topic between the two views. Attempted code below for page and editpage in urls.py, views.py, page.html and editpage.html: urls.py from django.urls import path from . import views urlpatterns = [ path("editpage/<str:topic>", views.editpage, name="editpage"), path("<str:topic>", views.page, name="page"), ] views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django import … -
Django: AttributeError: 'function' object has no attribute 'get_extra_actions'
I am getting this error, and it seem to be a problem with the router urls.py: from django.contrib import admin from django.urls import path, include from rest_framework import routers from main import views from django.contrib.auth.views import LoginView router = routers.SimpleRouter() router.register(r'login', LoginView.as_view(), basename='login') urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls())) ] error: extra_actions = viewset.get_extra_actions() AttributeError: 'function' object has no attribute 'get_extra_actions' here is the full traceback, stackoverflow could not let me post a full trackback because of formatting issue: https://paste.gg/p/anonymous/620b2e1923014f3c8ae2eec788656d7b so I assume the view have no problems (which is Django default view), anyone can help me solve the issue? -
Get backward relationships items for model in Django
I have a pet project with reviews about spare parts for cars. Here is models.py: class CarBrand(models.Model): brand = models.CharField(max_length=40, choices=(), unique=True, verbose_name="Марка") def __str__(self): return self.brand def get_absolute_url(self): return reverse_lazy('car_models_all', kwargs={'car_id': self.pk}) class CarModel(models.Model): model_name = models.CharField(max_length=60, db_index=True, verbose_name="Модель") brand_id = models.SmallIntegerField(verbose_name="ID марки") def __str__(self): return self.model_name def get_absolute_url(self): return reverse_lazy('model_info', kwargs={'model_id': self.pk}) class SparePartCategory(models.Model): name = models.CharField(max_length=255, db_index=True, verbose_name='Название') def __str__(self): return self.name def get_absolute_url(self): return reverse_lazy('spare_parts_category', kwargs={'category_id': self.pk}) class SparePart(models.Model): name = models.CharField(max_length=255, db_index=True, verbose_name='Название') brand = models.CharField(max_length=255, db_index=True, verbose_name="Производитель") number = models.CharField(max_length=30, db_index=True, verbose_name="Номер (артикул)") category = models.ForeignKey(SparePartCategory, on_delete=models.PROTECT, verbose_name="Категория") def __str__(self): return ' '.join([self.name, self.brand, self.number]) def get_absolute_url(self): return reverse_lazy('get_spare_part', kwargs={'spare_part_id': self.pk}) class Review(models.Model): RATING_VALUES = [ ('1', 'Ужасно'), ('2', 'Плохо'), ('3', 'Сносно'), ('4', 'Хорошо'), ('5', 'Отлично'), ] spare_part = models.ForeignKey(SparePart, on_delete=models.PROTECT, verbose_name="Запчасть") mileage = models.SmallIntegerField(verbose_name="Пробег, тыс.км") car_brand = models.ForeignKey(CarBrand, on_delete=models.PROTECT, verbose_name="Марка авто") car_model = models.ForeignKey(CarModel, on_delete=models.PROTECT, verbose_name="Модель авто") owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Владелец") rating = models.CharField(max_length=1, choices=RATING_VALUES, verbose_name="Рейтинг", default=3) review = models.TextField(max_length=1000, blank=True, verbose_name="Отзыв") def __str__(self): return ' '.join([self.spare_part.name, self.spare_part.brand, self.spare_part.number]) In views.py I get one SparePart def get_spare_part(request, spare_part_id): spare_part = get_object_or_404(SparePart, pk=spare_part_id) installed_on_cars = # here I need to get all CarModel for current SparePart with Review exists context = { 'spare_part': … -
django login invalid form
I did everything right but my login does not work I put 2 input in the login form but the user request sent me 3 fields, 1 of which I did not put and I receive this fields phone-number - login-password - phone-number form* class LoginForm(AuthenticationForm): phone_number = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control mb-3', 'placeholder': 'phone_number', 'id': 'login-phone_number'})) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': 'Password', 'id': 'login-pwd', } )) view* def account_login(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': form = LoginForm(request.POST) print(form) print(form.is_valid()) => #false if form.is_valid(): phone_number = form.cleaned_data.get('phone_number') password = form.cleaned_data.get('password') user = authenticate(phone_number=phone_number, password=password) print(user) if user is not None: login(request, user) return redirect('/') else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = LoginForm(request.POST) return render(request, "account/login.html", {"form": form}) login.html* {% extends "./sub_base.html" %} {% block title %}Log-in{% endblock %} {% block sub_content %} <form class="account-form" action="{% url 'account:login' %}" method="post"> {% csrf_token %} <h3 class="mb-4">Sign In</h3> {% if form.errors %} <div class="alert alert-primary" role="alert"> Error: Username or Password not correct! </div> {% endif %} <label class="form-label">{{ form.username.label}}</label> {{ form.username}} <label class="form-label">{{ form.password.label}}</label> {{ form.password}} <div class="d-grid gap-2"> <input type="hidden" name="next" value="{{ next }}"> <button class="btn btn-primary py-2 mb-4 mt-5 fw-bold" … -
Django: OR filter on Q object and manytomany values is slow
By doing the following, you can get an object whose title and tag name contain value. However, Q object and .distinct(), the query execution time will be very slow. Model.objects.filter(Q(title__icontains=value) | Q(tags__name__icontains=value)).distinct() In this case, do you recommend creating a field called search in the model and storing the values of title and tags__name in it, separated by spaces? tags = list(Model.tags.values_list('name', flat=True)) Model.search = f"{Model.title} {' '.join(tags)}" Model.save() -
(Exception while fetching data) type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
class Product { int? id; String? title; String? price; String? description; Category? category; bool? favorites; Product( { this.id, this.title, this.price, this.description, this.category, this.favorites}); Product.fromJson(Map<String, dynamic> json) { id = json['id']; title = json['title']; price = json['price']; description = json['description']; category = json['category']; favorites = json['favorites']; category = json['category'] != null ? new Category.fromJson(json['category']) : null; favorites = json['favorites']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['title'] = this.title; data['price'] = this.price; data['description'] = this.description; if (this.category != null) { data['category'] = this.category!.toJson(); } data['favorites'] = this.favorites; return data; } } class Category { int? id; String? categoryName; String? createDate; Category({this.id, this.categoryName, this.createDate}); Category.fromJson(Map<String, dynamic> json) { id = json['id']; categoryName = json['category_name']; createDate = json['create_date']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['category_name'] = this.categoryName; data['create_date'] = this.createDate; return data; } } Flutter is giving the unhandeled exception while fetching the data This is the console output: I/flutter ( 5234): {banners: [{name: New Sale for Diwali, image: /media/banners/b1_1Xc9YP7.jpg, link: /product/24, first: true}, {name: Sale, image: /media/banners/os2.jpg, link: /products?category=Topwear, first: true}], products: [{id: 22, title: Nike Air Force 1, image: https://minimals.cc/static/mock-images/products/product_1.jpg, description: dfmkdgfdkmgnfdgn, …