Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NuxtJS with NestJS
Im really confused and i wanted soemone to explain this for me, so if im not wrong is NuxtJS just a vue front end framework and NestJS a node based backend framework? if i work with both it shouldnt matter right? it should be like working with some x frontend framework with other y backend framework. I want a good framework to use with my NuxtJS application that has good security implemented, should i work with node? nest? express? django? What u guys recommend me? Sorry for being a newbie haha. -
How to save data from form.ModelForm in database and also show new post in template?
View.py def create_post(request): form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.date_posted = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'post_detail.html', {'form': form}) Forms.py from django import forms from django.forms import ModelForm, fields from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'description', 'date_posted', 'author'] -
Unable to install mod_wsgi with command <pip install -v mod_wsgi>
I am trying to set up a Django-Apache platform to host my Django Application on my local network. I am facing an issue with installing the mod_wsgi module with the command : ''' pip install mod_wsgi ''' The command is actually downloading all the versions of mod_wsgi starting from mod_wsgi-4.1.0 to mod_wsgi-4.9.0 and is ultimately getting terminated while raising the error: ERROR: No matching distribution found for mod_wsgi and ModuleNotFoundError: No module named '_distutils_hack'. Given below is the screenshot of the issue: Please help me resolve this. -
TypeError: 'RelatedManager' object is not iterable - serializers.ListField()
I have this 2 models: Route and Order. Route has a relation oneToMany with Order as you can see: class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer') retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer') date_publish = models.DateField(default=datetime.date.today) date_available = models.DateField() weight = models.DecimalField(decimal_places=2, max_digits=5) description = models.CharField(max_length=500, null=True) route = models.ForeignKey(Route, related_name='orders', null=True, on_delete=models.CASCADE) class Route(models.Model): day = models.DateField() warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) start_time = models.TimeField() When a order is created it's route should be null. When a route is created I want to associate orders with the route created, so I have the following Route Serializer. class routeSerializer(serializers.ModelSerializer): orders = serializers.ListField() class Meta: model = Route fields = ['day', 'warehouse', 'start_time', 'orders'] def create(self, validated_data): keys_to_extract = ['day', 'warehouse', 'start_time'] route_subset = {key: validated_data[key] for key in keys_to_extract} print(validated_data) route = Route.objects.create(**route_subset) for order_data in validated_data['orders']: Order.objects.filter(id=order_data).update(route=route) return route The body of the request should be like this: { "day" : "2021-12-12", "warehouse": "1", "start_time": "7:00", "orders": [ 1,2,3,4,5,6,7 ] } I was doing this in a different way, but I was told to do this in this way, but with orders = serializers.PrimaryKeyRelatedField(). But in that way I can't get the 'orders' from validated_data since it just come with 'day', 'warehouse' … -
How to merge data from two models
I have a VideoView model which tracks data about a user who watched a video. I am now creating a Todo model which will keep track of what users need to watch. I figured I may as well merge these models into one Todo model and remove the VideoView model. What is a common procedure for moving the data from one model to another? I see a couple different options but maybe there are other options. The models: class VideoView(models.Model): user = models.ForeignKey(Employee, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) date_time = models.DateTimeField(auto_now=True) class Todo(models.Model): created_on = models.DateTimeField(auto_now_add=True) completed_on = models.DateTimeField(auto_now=True) user = models.ForeignKey(Employee, on_delete=models.CASCADE) video = models.ForeignKey( Video, on_delete=models.CASCADE, null=True, blank=True, related_name='todos' ) Option 1: Write a view which opens each VideoView then creates new Todo instances with the data of each. Then visit the view in the browser to migrate the data. This option seems to be decent as the code will be readable and I can delete Todos if there are mistakes. Option 2: Same thing but in the shell. Less readable. More prone to errors. Option 3: Is there a way to simply move the field from one model to another? Or maybe doing a multi-stage(?) migration, where … -
How to "create or update" using F object?
I need to create LeaderboardEntry if it is not exists. It should be updated with the new value (current + new) if exists. I want to achieve this with a single query. How can I do that? Current code looking like this: (2 queries) reward_amount = 50 LeaderboardEntry.objects.get_or_create(player=player) LeaderboardEntry.objects.filter(player=player).update(golds=F('golds') + reward_amount) PS: Default value of "golds" is 0. -
NOT NULL constraint failed: plegdetect_fileupload.user_id
I am building a plagiarism detector using Django. Whenever a user upload a file and click on upload , That file goes to my media file . But I got the error that NOT NULL constraint failed: plegdetect_fileupload.user_id . my models.py is : from django.db import models from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class FileUpload(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField(upload_to='files') def __str__(self): return self.user.username my view.py is: class PostCreateView(CreateView): model = FileUpload fields = ['file'] def form_valid(self, form): form.instance.author = self.request.user return super(PostCreateView, self).form_valid(form) my urls.py is : from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('post/new/',views.PostCreateView.as_view(),name='post-create'), ] Thanks in advance -
How to Convert MP4 to HLS with Multiple Audio and Multiple Video Quality in Python/Django?
I have tried with ffmpeg library and I can convert videos mp4 to hls with multiple quality but multiple audio is not working. > [Commands Excuting from Terminal] And with subprocess library calling subprocess.call. > [ Want to know is this the right way? to do with Django? ] -
<form method="get"> is send as POST (Django)
I'm trying to make django-filter work, and it have worked, but now it suddenly have stopped. The issue is that the submit button in the filter seems to be sending a POST request and not GET Below is a snippet of the HTML code <div class="form-group"> <form method="POST"> {% csrf_token %} {{form|crispy}} <button class="btn btn-outline-success" type="submit">Add product</button> </div> <div id="filter-menu"> <form method="get"> {{filter.form.nick_name|as_crispy_field}} <br> {{filter.form.domain|as_crispy_field}} <br> <button class="btn btn-outline-success" type="submit">Apply filter</button> </form> </div> I do have a POST-request submit button above as seen, and it seems like it's the one being triggerd, since when I debug the application, request.method == "POST" when pressing the apply filter button. If needed, a snippet of my view is here (omitted messages and stuff) def MyView(request): user = request.user user_products = MyModel.objects.filter(user=user).all() ### Create filters ### filter = get_user_filter_fields_wishlist(user_products) #Helper function for returning filters filter = filter(request.GET,queryset = user_products) if request.method == "POST": post_form = MyForm(request.POST) if post_form.is_valid(): filter = get_user_filter_fields_wishlist(user_products) filter = filter(request.GET,queryset = user_products) form = MyForm() context = { "form":form, "filter":filter } return render(request, "myapp/my_html.html",context=context) else: #invalid post_form context = { "form":post_form, "filter":filter } return render(request, "myapp/my_html.html",context=context) else: #Get request form = MyForm() context = { "form":form, "filter":filter } return render(request, … -
django CSS & Javascript not loading in HTML files?, error 404?
I have put some static files for CSS Javascript and Jquery in my file static. I have put load static in my HTML and it doesn't respond properly to the HTML. Do you have anything else to do with it? output error setting.py file -
RuntimeError: set_wakeup_fd only works in main thread of the main interpreter when adding a proxybroker job in django-apscheduler
I tried to use django-apscheduler to add a proxybroker job. There is no problem to run test_proxybroker.py and got proxies returned. But I got this error when I run the django-apscheduler command. set_wakeup_fd only works in main thread of the main interpreter #test_proxybroker.py import asyncio from proxybroker import Broker # https://proxybroker.readthedocs.io/en/latest/examples.html def broke(): async def show(proxies): while True: proxy = await proxies.get() if proxy is None: break print('Found proxy: %s' % proxy) try: loop = asyncio.get_event_loop() except: new_loop = asyncio.new_event_loop() asyncio.set_event_loop(new_loop) loop = asyncio.get_event_loop() proxies = asyncio.Queue() broker = Broker(proxies) tasks = asyncio.gather( broker.find(types=['HTTP', 'HTTPS'], limit=10), show(proxies)) loop.run_until_complete(tasks) #runapscheduler.py. (the django command file) ... def test_job(): try: broke() except: pass ... -
Recent user visits in Django
I have a visit model on my site that is strong enough to use the page of a product, an object is registered with the product and the user's IP. If anyone knows, thank you -
Django appeared ajax error after uploading the site to heroku
I am making a portfolio site in django and I wanted to upload it to heroku. Everything worked fine on localhost, but after uploading the site to heroku, I started getting errors when using AJAX. Im using ajax for register user and sending email massage Js $.ajax({ type: 'POST', url: "", enctype: 'multipart/form-data', data: fd, success: function(response) { mess = $('.b-popup_message') if (response.status == 'login') { window.location.href = '/'; mess.text('Wait...') } else { mess.text('We have sent the code to you by mail. Enter it') } }, error: function(error) { console.log(error); }, cache: false, contentType: false, processData: false, }) return false view.py def main(request): global code login_form = LoginForm(request.POST or None) data = {} if request.method == 'POST': if login_form.is_valid(): if request.is_ajax(): email = request.POST.get('email') data['email'] = email data['code'] = login_form.cleaned_data['code'] if not code or code != data['code']: sleep(10) code = generate_code(4) send_email_message = EmailMessage('DONUTELA CODE', f'Enter this code on the register form: {code}', to=[email]) send_email_message.send() data['status'] = 'sent_code' elif code == data['code']: if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) else: user = User.objects.create_user(username=generate_code(20), email=email, password=generate_code(20)) login(request, user, backend='MainApp.Backends.PasswordlessAuthBackend') data['status'] = 'login' return JsonResponse(data=data) added_products_cookies = request.COOKIES.get('added_products') added_product_names = [] # все добавленые продукты по названию added_products_dict = {} # вид {название продукты: … -
How can I use an extra ModelChoiceField on a ModelForm?
I am trying to add a ModelChoiceField to a ModelForm, but I keep getting a TypeError: type object argument after ** must be a mapping, not QuerySet. I feel like I implemented the modelchoicefield as in the docs, with a queryset argument. The form worked fine before I added the ModelChoiceField. forms.py from django import forms from events.models import Event, ExtraThing class EventForm(forms.ModelForm): extra_thing = forms.ModelChoiceField(queryset=ExtraThing.objects.all()) class Meta: model = Event fields = ('name', 'date', 'extra_thing') views.py from events.forms import EventForm def newevent(request): if request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): form.save() else: form = EventForm() return render(request, 'manage/event_form.html', {'form': form}) -
Frontend and backend validation synergy
I've created a register form validation on frontend and backend and I am checking both at the frontend and backend: whether the name and surname consist of letters only, whether the password contains numbers, uppercase and lowercase letters, whether the email is correctly saved. The interface informs about errors. My question is, since I check all the conditions on the frontend, should the backend also send error messages to the frontend? I mean both frontend and backend check data validation, but should the frontend react to backend error messages? It seems unnecessary for the backend to send information that f.e. the password is too short, since the frontend already does it. The backend should only make sure that f.e. the password length is appropriate. Second question: should I check on the backend side whether the checkbox regarding acceptance of the website regulations has been selected or whether the password and the repeated password are the same? -
Python/DJango 'django.db.utils.OperationalError: no such table' in Django Rest Framework (DRF)
I'm trying to create a POST API for users to vote on a given choice. But I keep getting the error below. What could be the problem? Thanks in advance! Internal Server Error: /polls/6/choices/19/vote/ Traceback (most recent call last): File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: main.vote_choice__old File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\models\base.py", line 879, in _do_insert return manager._insert([self], fields=fields, return_id=update_pk, File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ..... ..... File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: main.vote_choice__old [08/Aug/2021 17:09:09] "POST /polls/6/choices/19/vote/ HTTP/1.1" 500 193455 Here's the vote class in serializer.py: class VoteSerializer(serializers.ModelSerializer): class Meta: model = Vote fields = '__all__' Here's the CreateVote class in apiviews.py: class CreateVote(APIView): serializer_class = VoteSerializer def post(self, request, pk, choice_pk): voted_by = request.data.get("voted_by") data = {'choice': choice_pk, 'poll': pk, 'voted_by': voted_by} serializer = VoteSerializer(data=data) if serializer.is_valid(): vote = serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here's the URL Patterns code in urls.py: urlpatterns = [ path("polls/<int:pk>/choices/<int:choice_pk>/vote/", CreateVote.as_view(), name="create_vote"), ] And the models code looks like so in models.py: class Vote(models.Model): choice = models.ForeignKey(Choice, related_name='votes', on_delete=models.CASCADE) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) voted_by = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = ("poll", "voted_by") -
Page Not Found (404) Error in simple Django 2.2 application
I used the official Django documentation to create this code and I consistently get a 404 error when I put localhost:server/polls/ in the search bar. I followed the tutorial pretty much identically but it still doesn't seem to work. Anyone know a solution to get text displayed at localhost:server/polls/ or at localhost:server? polls/views.py: from django.shortcuts import render from django.http import HttpResponse def index(response): return HttpResponse('Polls') polls/urls.py: from django.urls import path from . import views urlpatterns =[ path('', views.index, name='index'), ] mysite/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), ] Error message: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn't match any of these. I have looked at lots of different potential solutions and none of them seem to work. Please let me know if you need more info/code, thanks -
Access to fetch at 'http://127.0.0.1:8000/blog/1' from origin 'http://localhost:3000' has been blocked by CORS policy
I'm trying to fetch some data from the Django Rest API. But browser throw cors policy error. let headersList = {Accept: '*/*'} fetch(url, { method: 'GET', headers: headersList, }) .then(function (response) { return response.json() }) .then(function (data) { console.log(data) }) Access to fetch at 'http://127.0.0.1:8000/blog/1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I also include cors-header in django api. CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True -
Pass data to modal querying data again in django?
I have an transaction list and its been looped to show in a table. In this, when user click on view a modal will be opened with extra information. How to pass the data to the modal, I know i can do this by making ajax request. But the thing is we have already have all the data from the for loop ? then why we need to do ajax again to get same request ? Ex: {% for data in transactions %} <tr class="nk-tb-item"> <td class="nk-tb-col"> <span>{{forloop.counter}}.</span> </td> <td> <a href="#tranxDetails" data-toggle="modal">View</a> </td> </tr> {% endfor %} As you see, we got all information from transactions and when user clicks on "View" - it opens the modal but how to send transactions of that particular data to the modal ? I have even tried using index on modal like <div class="modal fade" tabindex="-1" id="tranxDetails"> <div>{{transactions.0.amount}}</div> </div> But dont know how to replace the "0" with respective current index. Please suggest a way, am not doing any POST or GET on the modal - just want to show some extra information from "transactions" on the modal ( as the table can only show few columns adding the extras to the … -
Is there a way to know why i cant access my newly deployed website?
Ok so I recently deployed my Django app on Digital ocean and the app was fine and working normally. suddenly when i try to access the app using the server Ip address it doesn't allow me stating as follows:i cant embed a picture directly i am new here . i tried a vpn and it didnt work however my colleagues can access the server normally and use the app i am the only one that cant access it. i tried rebooting the server using sudo reboot and tried disabling firewall and nothing works. i am new to deploying apps so i need help and sorry if my question lacks information. -
RSA Encryption not supported - caching_sha2_password with django mysql and docker
im trying to connect Mysql with django using docker, and i get this error 2061, 'RSA Encryption not supported - caching_sha2_password plugin was built with GnuTLS support' i tried changing user and creating a database with // create a user // CREATE USER 'user'@'localhost' IDENTIFIED BY 'user'; GRANT ALL PRIVILEGES ON *.* TO 'user'@'localhost' WITH GRANT OPTION; CREATE USER 'user'@'%' IDENTIFIED BY 'user'; GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' WITH GRANT OPTION; // create a database // CREATE DATABASE user_db; BUT still the sqme error message in the settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'user_db', 'USER': 'user', 'PASSWORD': 'user', 'HOST': 'db', 'PORT': '3306', } } and in docker-compose: db: image: mysql:latest environment: MYSQL_DATABASE: 'user_db' MYSQL_USER: 'user' MYSQL_PASSWORD: user MYSQL_ROOT_PASSWORD: root volumes: - ./data/mysql/db:/var/lib/mysql ports: - 3306:3306 thank you for your help -
Internal Application error in Heroku app deployment
I have been trying to deploy this Python Django based Weather app on heroku. I have followed all the procedures exactly as mentioned for example created the proctile file and changed some things on settings.py including the allowed host. But still I can't figure out why this error is occurring for me. Please do help me to get this error fixed. I have also attached the screenshots. And at the same time I followed this tutorial down here. https://youtu.be/Q_YOYNiSVDY enter image description here enter image description here -
Django Oscar or e-com from scratch
I'm developing an e-commerce site with Django and REST framework. Products are books and other things that designed by user, and product creation parts are done. Now I want to add e-commerce parts, and found some frameworks like oscar and django-shop, but also encounter some opinions on them suggesting to do it from scratch since "after a while you customize it to some extent that you ask yourself why even I use this framework". Not a direct quote but you got the idea. My questions are: Considering the type of product what approach is better for me? (Frameworks or from scratch) Is there a significant difference in develop time between them? Because products are complex i assume there should be lot of customization needed in frameworks. I want to know considering these customization, using frameworks are still a lot faster? If you suggest to use a framework, which one would you recommend? -
The chained field in my django app is empty. I am using django smart select
Right now I'm practicing using Django smart select. However, the chained field dropdown list (country field in Location model) in Django-admin is empty. It doesn't load any objects unless I switch the show_all argument to True. You can find my models.py below. from django.db import models from smart_selects.db_fields import ChainedForeignKey # Create your models here. class Continent(models.Model): continent= models.CharField(max_length=200) def __str__(self): return self.continent class Country(models.Model): continent= models.ForeignKey(Continent, on_delete=models.CASCADE) country= models.CharField(max_length=200) def __str__(self): return self.country class Location(models.Model): continent= models.ForeignKey(Continent,on_delete=models.CASCADE) country= ChainedForeignKey(Country, chained_field='continent', chained_model_field='continent', show_all=False, auto_choose=True, null=True, blank=True) Django-admin screenshot (You can find that the country doesn't load any objects) -
html5sortable drag and drop not working on ajax load HTML
I was trying to add a draggable HTML list that loaded via AJAX request, it's not working here below the code for the draggable feature, I used html5sortable HTML template code <script src="{% static 'assets/javascripts/libraries/html5sortable.min.js' %}"></script> <script src="{% static 'assets/javascripts/main.js' %}"></script> <div class="card-body" id="item-container"> </div> JS code $.ajax({ URL: list_data_url, type: "POST", data: data, success: function (response) { if (response["success"] == true) { const parent = $("#item-container").empty(); // Added sortable DIV let item_html = '<div class="sortable">'; let total_price = 0; for (const item of items) { item_html += ` <a href="${details_url}"> <div class="item-wraper" style="background:${bk_color}; opacity:0.5;"> <div><strong>Items SL: </strong> Item Name</div> </div> </a>`; } item_html += "</div>"; parent.append(item_html); // Items Sortable sortable(".sortable"); } }})