Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Importing Data from .sql file into postgresql database (Django)
I have a .sql file containing a 1 year amount of records, and I have a running Django app with a Postgresql database. I would like to import all the records on the .sql file into the new empty database. I used to use these two commands on a different project running with Docker : To export the database : docker exec -t *** pg_dumpall -c -U *** > dump_date +%d-%m-%Y"_"%H_%M_%S.sql To import the database : cat dump_***.sql | docker exec -i *** psql -U *** -d *** But without really understanding what I am doing, so I can't find the equivalent command to use in case I am not using Docker. Thank you for your help. -
how show product by subcategory in django?
i want to show product in category by subcategory. I wrote this but it show all product in category except subcategory!!!? i tested {% if category.childern.all %} in list.html but its not work model.py class Category(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200,db_index=True), slug = models.SlugField(max_length=200,db_index=True), ) parent = models.ForeignKey('self', related_name='children',on_delete=models.CASCADE,blank=True,null=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class Product(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200,db_index=True), slug = models.SlugField(max_length=200,db_index=True), description = models.TextField(blank=True), price = models.PositiveIntegerField(), ) category = models.ForeignKey(Category, related_name='products' ,on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%Y/%m/%d',blank=True) available = models.BooleanField(default=True) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id,self.slug]) def __str__(self): return self.name view.py def product_list(request,category_slug=None): category = None categories = Category.objects.filter(parent=None) products = Product.objects.filter(available=True) if category_slug: language = request.LANGUAGE_CODE category = get_object_or_404(Category,translations__language_code=language,translations__slug=category_slug) products = products.filter(category=category) context = { 'categories':categories, 'category':category, 'products':products, } return render(request,'shop/product/list.html',context) list.html (it show when user click on subcategory in menu bar) {% extends "shop/index.html" %} {% block title %} product list {% endblock title %} {% block content %} <div class="container-fluid"> <div class="row mt-4"> <div class="col-9"> … -
How to insert image file using modal in django?
I want to insert image file using modal form in django framework? the html is not accepting the forms i am using right now. Below is the form I am using Views.py: Forms.py: Html: I am not able to use the below html in modal: def free_upload(request): if request.method == 'POST': imgform = ImageUForm(request.POST, request.FILES or None) if imgform.is_valid(): img_obj = imgform.instance imgform.save() return render(request, 'temp_test.html',{'form': imgform, 'img_obj':img_obj}) else: return HttpResponse("not valid") else: form = ImageUForm() return render(request, 'temp_test.html',{'form': form}) Forms.py: class ImageUForm(forms.ModelForm): class Meta: model = Image fields = ['title', 'image',] HTML: <form method="POST" enctype="multipart/form-data" > {% csrf_token %} <div class="row"> <div class="col-lg-6 col-md-12"> {{form.title|as_crispy_field}} </div> <div class="col-lg-6 col-md-12"> {{form.image|as_crispy_field}} </div> </div> <p> <button type="submit" href="{% url 'userload' %}" class="btn btn-primary">Upload </button> </p> </form> class Meta: model = Image fields = ['title', 'image',] -
how to resolve this error code in django: RelatedObjectDoesNotExist
How to resolve this error code in django rest-framework (RelatedObjectDoesNotExist at /api/following/) User has no following. -
Django is init view twice
Django is run in multithreading mode. Main Thread and Django MainThread How to run in a single-thread mode? Also how to init view file once? -
Cannot query "amclient15": Must be "Client" instance
Am trying to filter the appointments made by a specific client when he is logged in def user( request): client = request.user.client request.user.id appointments = Appointment.objects.filter(user=request.user) context = { 'client': client, 'appointments':appointments } return render(request, 'users/user.html', context) -
DRF ModelViewSet route get mixed in with ApiView route
I have the following views: class NotificationAPI(viewsets.ModelViewSet): authentication_classes = (CustomJWTAuthentication, SessionAuthentication) permission_classes = (IsAuthenticated,) queryset = Notification.objects.all() def get_queryset(self): qs = self.queryset.all() queryset = qs.filter(recipient=self.request.user.id) return queryset class MarkAsReadView(APIView): permission_classes = (IsAuthenticated,) authentication_classes = [CustomJWTAuthentication, SessionAuthentication] @swagger_auto_schema(manual_parameters=[authorization]) def post(self, request, notification_id): # mark single notification as read class MarkAllAsReadView(APIView): permission_classes = (IsAuthenticated,) authentication_classes = [CustomJWTAuthentication, SessionAuthentication] @swagger_auto_schema(manual_parameters=[authorization]) def post(self, request): #mark all notifications as read and here is my urls.py routing: router = routers.DefaultRouter(trailing_slash=False) router.register('notifications', NotificationAPI, basename='notifications') urlpatterns = [ path('', include(router.urls)), # notifications path('notifications/mark-as-read/<int:notification_id>', MarkAsReadView.as_view(), name='mark-as-read'), path('notifications/mark-all-as-read', MarkAllAsReadView.as_view(), name='mark-all-as-read'), ] Currently whenever i call mark-as-read it work find, but when i try to call mark-all-as-read api it always return the following error: { "detail": "Method \"POST\" not allowed." } I checked and it seem like the notification modelviewset routing messing up the other ApiView routes. I checked by commenting out the ModelViewSet out and the mark-all-as-read now work. Why is this happening? shouldn't routing be separate by name and basename ? Why it's when i call mark-all-as-read it go into the ModelViewSet route, but the mark-as-read work normally? -
Query data linked via Foreign key
I have 2 models linked 'Project' and 'Event'. Event has an FK to Project I want to return all events that are related only to the project. I have a basic view that returns the specific project and im trying to include the event list within that view. def show_project_details(request,project_id): today = now().date() project = Project.objects.get(pk=project_id) events = Event.objects.event_list = Event.objects.filter(event_date__gte=today).order_by('event_date') events_list = Event.objects.get(project_name_id=project_id) form = ProjectForm(request.POST or None, instance=project) return render(request, 'pages/project_details.html', {"project": project, "form": form, "events": events, 'events_list':events_list}) but it returns Event matching query does not exist. Any ideas? -
Django choice field(dropdown) restrict according to user type for multiuser type
I have multi user types in my django app where the user can change the status of something usertype a has options to perform create a task,close(choice fields) while usertype b has option to accept the task created by usertype a and mark finish. how do i restrict them in the form according to the user type when the usertype a clicks on form he should see only close under dropdown whereas the usertype b has to see only accept and finish option in dropdown. models.py class todo(models.Model): title = models.CharField(max_length=200) info = models.TextField() created_by = models.ForeignKey(User,related_name = 'created_by',blank=True,null=True,on_delete=models.CASCADE) STATUS_CHOICES = ( (0,opened), ('1','Accepted'), ('2','Completed'), ('3','finish') ) status = models.CharField('Status',choices=STATUS_CHOICES,max_length = 100,default = 'Open') forms.py class CreateForm(forms.ModelForm): class Meta: model = Model fields = ('title', 'info') class EditForm(forms.ModelForm): class Meta: model = Model fields = ('title', 'info','status') -
Django, Python: Can't filter products with passing values true the get request and order the products
I'm trying to filter some products and order the filtered products by price ascending and descending. This is my code in the view: def is_valid_queryparam(param): return param != '' and param is not None def filter(request): if request.GET: price_min = request.GET.get('priceMin') price_max = request.GET.get('priceMax') sort_by = request.GET.get("sort", "l2h") if is_valid_queryparam(price_min): if sort_by == "l2h": products = Product.objects.filter(price__gte=price_min).order_by('price') elif sort_by == "h2l": products = Product.objects.filter(price__gte=price_min).order_by('-price') paginator = Paginator(products, 9) page = request.GET.get('page') paged_products = paginator.get_page(page) product_count = products.count() if is_valid_queryparam(price_max): if sort_by == "l2h": products = Product.objects.filter(price__lte=price_max).order_by('price') elif sort_by == "h2l": products = Product.objects.filter(price__lte=price_max).order_by('-price') paginator = Paginator(products, 9) page = request.GET.get('page') paged_products = paginator.get_page(page) product_count = products.count() else: products = Product.objects.all().order_by('price') paginator = Paginator(products, 9) page = request.GET.get('page') paged_products = paginator.get_page(page) product_count = products.count() context={ 'products': paged_products, 'product_count': product_count, } return render(request, 'store.html', context) If I try to filter based on the min and max price it works, but when I'm trying to sort or if there is no filter apply I get this UnboundLocalError: UnboundLocalError at /store/ local variable 'paged_products' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/store/?sort=h2l Django Version: 3.1 Exception Type: UnboundLocalError Exception Value: local variable 'paged_products' referenced before assignment Exception Location: C:\Users\store\views.py, line 299, in filter … -
Duplication of id values in another column in same table django
I am working on one python(django framework) project in which i have one user model which has 1000 users. I want to make one another column named priority id and need to put default id values in that priority id column accordingly (you can see it below). id username email priority_id 1 abc abc@gmail.com 1 2 xyz xyz@gmail.com 2 ofcourse i can do it manually but for 1000 users it is time consuming. how do i change models.py or admin.py or something else to achieve this? -
FileNotFoundError: [Errno 2] No such file or directory in Django
I'm working on a Django project where I need to send a file to the client via my system by email. But when I put the file name in the attach_file() field, I get the error of not finding the file. This is my code: def email_sender(request): if request.method == "GET": subject = 'welcome to GFG world' email_from = settings.EMAIL_HOST_USER recipient_list = ["example@gmail.com", ] to = 'example@gmail.com' text_content = 'This is an important message.' msg = EmailMultiAlternatives(subject, text_content, email_from, [to]) msg.attach_file('file.file') msg.send() And this is my exception: FileNotFoundError: [Errno 2] No such file or directory: 'file.file' [08/Dec/2021 11:52:52] "GET /email/send/ HTTP/1.1" 500 83111 This is my setting.py: ... STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] ... This is my project structure: src \_emailsender \_ urls.py \_ views.py \_ setting.py \_ static \_ file.file Thanks for your help. -
the name 'title' is not defined, [closed]
I'm trying to make a search bar using Django/Python, and have a small problem with the views.py its telling me that 'name 'title' is not defined' i sure I made a mistake but don't know where, be very happy if someone can help me out def search_post(request): if request.method == "POST": searched = request.POST.get('searched') const title = post = Post.objects.filter(name_contains=title) return render(request, 'Blog/search_post.html', {'searched':searched}) else: return render(request, 'Blog/search_post.html', {}) -
Django datalist not accepting any input as valid
I am trying to use a datalist input field to allow users to enter their own ingredients on Create a Recipe form. Ideally users can select a GlobalIngredient like salt, pepper, chicken, etc. already in the database or create their own. However, regardless of whether I enter a new ingredient or select a pre-existing ingredient, I am getting the following error: "Select a valid choice. That choice is not one of the available choices.". Unsure why I am getting this error? Visual: models.py class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) websiteURL = models.CharField(max_length=200, blank=True, null=True) image = models.ImageField(upload_to='image/', blank=True, null=True) name = models.CharField(max_length=220) # grilled chicken pasta description = models.TextField(blank=True, null=True) notes = models.TextField(blank=True, null=True) serves = models.CharField(max_length=30, blank=True, null=True) prepTime = models.CharField(max_length=50, blank=True, null=True) cookTime = models.CharField(max_length=50, blank=True, null=True) class Ingredient(models.Model): name = models.CharField(max_length=220) def __str__(self): return self.name class GlobalIngredient(Ingredient): pass # pre-populated ingredients e.g. salt, sugar, flour, tomato class UserCreatedIngredient(Ingredient): # ingredients user adds, e.g. Big Tomatoes user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL) description = models.TextField(blank=True, null=True) quantity = models.CharField(max_length=50, blank=True, null=True) # 400 unit = models.CharField(max_length=50, blank=True, null=True) # pounds, lbs, oz ,grams, etc forms.py class RecipeIngredientForm(forms.ModelForm): def __init__(self, … -
I came into the world of programmng and im confused as hell, Im lost, I need help or some advice
Good day, pls im a 16 years old guy, i got intreted in programming and how thing work, i started by learning HTML, CSS, JAVASCRIPT in a place they took those courses, then i decided not to pay for more courses because i felt i wanst taught as i should, since then ive been able to learn orther languages (python, solidity) and get familiar with framework like (Django), but still i cant put anything together. i felt React will be cool to learn and use so i downloaded react native courses from "edx.org" still i wasnt really understanding and i had some issues understandig the "Javascript intro" for the course especially "Javascript classes and construstors". Ive been working with a team(my freinds), to build something and i am to handle the website but im confused as hell, im using django to build it, but i still get confused on stuffs like "Positioning boxes(css) and some little things". I really wanna be a developer, although my mum said "Maybe if you stop looking at the people on the screen everytime and face your life or the physical world, life will be much better" I dont wanna mind that and im not … -
Why can't I pass a list comprehension to Django RelatedManager add()?
Given: class Game(models.Model): rengo_black_team = models.ManyToManyField(Player) class OpenChallenge(CommonChallenge): rengo_black_team = models.ManyToManyField(Player) game = models.ForeignKey(Game, on_delete=models.CASCADE) This OpenChallenge method code works: for p in self.rengo_black_team.all(): self.game.rengo_black_team.add(p) But this code does not: self.game.rengo_black_team.add([x for x in self.rengo_black_team.all()]) Based on the last example in the docs , >>> john = Author.objects.create(name="John") >>> paul = Author.objects.create(name="Paul") >>> george = Author.objects.create(name="George") >>> ringo = Author.objects.create(name="Ringo") >>> entry.authors.add(john, paul, george, ringo) it seems like my example should work, but I get "Field 'id' expected a number but got [<Player: anoek>]" -
Adding new site language in Django admin
Is it possible to control site languages from django admin? if we need new language we should add in settings.py like that: settings.py LANGUAGES = ( ("ru", _("Russian")), ("en", _("English")) ) But is there any way to allow admin to add new supported language using django admin panel? -
Django not serving static file because of i18n prefix in url
I wanted to have i18n internationalization on my project and whenever I need to serve some static file/image, I kept on getting this error. Does anyone know how to fix the url prefix so it know where to redirect? [08/Dec/2021 14:11:09] "GET /admin-interface/logo/photo_2021-12-07_21-08-39_Gp96iY6.jpg HTTP/1.1" 302 0 Not Found: /en/admin-interface/logo/photo_2021-12-07_21-08-39_Gp96iY6.jpg [08/Dec/2021 14:11:09] "GET /en/admin-interface/logo/photo_2021-12-07_21-08-39_Gp96iY6.jpg HTTP/1.1" 404 6917 This is what my urls.py looked like from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('', admin.site.urls), ) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
PDF package without dependencies
I'm trying to deploy a site PaaS service. In one of my APIs I convert html to pdf. But the package has some dependencies which are not installed on the server. That's why I cannot deploy my site. If I want to deploy it using docker I also need to configure nginx myself and i don't want to fall into nginx difficulties. Does anybody know a html-to-pdf package in python that doesn't require any dependencies? -
Django SimpleJWT: Some questions with token authentication
I am implementing authentication in Django using SimpleJWT, and have a few questions regarding the same. To give some background I have multiple domains with my backend, some with normal login (username and password), and some with SSO logins. Question 1: For normal login, I pass username and password in the payload to TokenObtainPairView API, and it gives me access and refresh tokens. How can I get the access and refresh tokens in SSO login, since it does not have any password? Question 2: Suppose, I store the access tokens in local storage and send the access token to all APIs, and I'm also refreshing it before it expires. But what will happen if the user closes the browser, and we are not able to refresh the access token. The access token expires and the user gets logged out. How can we keep the user logged in for a certain amount of time (say 30 days)? Question 3: The username and password passed in the payload are visible in the curl, is this a security issue? How can I deal with this? -
How to write if and else conditions in Django
I wanted to save email in email Model if email is coming from frontend,, else save phone number in phone model if phone is coming else send error def post(self,request): if request.data['email']: serializeObj = EmailSerializer(data = request.data) if serializeObj.is_valid(): serializeObj.save() return Response('Email success') else: serializeObj = PhoneSerializer(data = request.data) if serializeObj.is_valid(): serializeObj.save() return Response('Phone success') return Response(send error) -
How to remove %20%20%20 in url? (Django)
The following url: <a href="{% url 'view' i.value %}" >VIEW DETAILS</a> directs to: http://localhost:8000/view/value%20%20%20 Instead it should direct to http://localhost:8000/view/value How to solve this? -
can someone please send me a link to a video that explains how you can use 2 or more languages together? [closed]
ummm... i just wanna know how to use different languages i learnt like python, html and css or javascript together like they do in those coding livestreams. like i heard there is django for python but i dont understand how theyre connected and how i can implement them for making a server for a website project im doing. Thanks alot for your time God bless you -
how to create an instance of one to one , before the main object will be create - django
i've these two models : class Payment(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT) client_seller = models.ForeignKey(ClientCompany,on_delete=models.PROTECT,blank=True) next_payment = models.OneToOneField(NextPayment,blank=True,null=True,related_name='next_payments',on_delete=models.PROTECT) #others class NextPayment(models.Model): next_payment = models.DateTimeField() status = models.BooleanField(default=True) i want to create NextPayment instance before Payment instance will be create , and assign the NextPayment object to Payment > next_payment field ! here is my views.py @login_required def create_payment(request): main_form = PaymentForm() next_paymentform = NextPaymentForm() next_payment= request.GET.get('next_payment') print(next_payment) if request.method == 'POST' and request.is_ajax(): main_form = PaymentForm(request.POST) next_paymentform = NextPaymentForm(request.POST) if main_form.is_valid(): main_obj = main_form.save(commit=False) main_obj.admin = request.user if next_payment: date_next = next_paymentform(next_payment=next_payment) #date_next = NextPayment(next_payment=next_payment,status=True) also tried this date_next.save() main_obj.next_payment= date_next main_obj.save() else: main_obj.save() data = { 'id':main_obj.id } return JsonResponse({'success':True,'data':data}) else: return JsonResponse({'success':False,'error_msg':main_form.errors,'next_paymentform':next_paymentform.errors}) return render(request,'payments/pay.html',{'main_form':main_form,'next_paymentform':next_paymentform}) my forms.py class NextPaymentForm(forms.ModelForm): next_payment = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M'],widget=forms.DateTimeInput(attrs={'type':'datetime-local','class':'form-control'}),required=False) class Meta: model = NextPayment fields = ['next_payment'] class PaymentForm(forms.ModelForm): class Meta: model = Payment fields = ['client_seller','type_of_payment','price','note','discount','discount_note'] next_payment prints None ! but it wasnt None but doesnt work , and only saves the main form ! i need to check if the next_payment exists then create an instance of NextPayment and assign that new instance to Payment model ? any idea much appreciated .. thank you in advance .. -
React Django WebSocket connection challenge
The challenge I am facing is in trying to connect my Django backend with React frontend app. The error that I am getting is: WebSocket connection to 'ws://localhost:8000/ws/week/' failed: _callee$ @ Week.jsx:77 Here is the Week.jsx code: export default function Week(props) { const [scoops, setScoops] = useState([]); const ws = useRef(null); useEffect(async () => { ws.current = new WebSocket("ws://" + window.location.host + "/ws/week/"); ws.current.onopen = () => console.log("ws opened"); const res = await fetch("/api/scoops/week/"); const data = await res.json(); setScoops(data); }, []); const rows = []; for (let i = 0; i < scoops.length; i++) { rows.push(createData(i, scoops[i]?.rank, scoops[i]?.title, scoops[i]?.url)); } return <Base rows={rows} duration="Week" />; } Here is the server terminal log: System check identified no issues (0 silenced). December 08, 2021 - 10:59:59 Django version 3.2.8, using settings 'app.settings' Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. HTTP GET /week/ 200 [0.02, 127.0.0.1:62685] HTTP GET /api/scoops/week/ 200 [0.14, 127.0.0.1:62685] WebSocket HANDSHAKING /ws/week/ [127.0.0.1:62695] WebSocket DISCONNECT /ws/week/ [127.0.0.1:62695] Any help would be truly appreciated. Thank you!