Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to write fixture files for testing models
I want to test my database and django app via fixtures and Testcases. The problem is, that I cannot find any informations, on how to create fixtures, especially regarding relationships. I tried in the python CLI to create objects and relate them to each other, but it won't execute the dumpdata method afterwards Can you guys give me ressources or a little guide on how to do that, focusing on database models and relationships (1-1,1-n,n-m). Thanks in advance and I'm looking forward to learn as much as I can from you!!! Dennis :) -
How to run multiple terminal sessions (Tabs) in pydroid 3
I am trying to create an app using pydroid 3. When I view if the project is setup properly with python manage.py runserver Everything is set up ok but when it's time to start the app, I have to open another terminal or tab while the terminal with runserver continues running. How do I open another terminal session(or tab) without closing runserver. -
Need help loading staticfiles with nginx
I am having trouble loading the static files from my django project. Here is a picture of my directories: DIRECTORIES I have ran docker-compose up and I get the following errors: ERROR IMAGES ON BROWSER Here is what my nginx (default.conf) file looks like: http { server { listen 8080; access_log /var/log/nginx/access.log location / { root /frontend/templates/frontend # proxy_pass http://pathfinder_gunicorn; # include /etc/nginx/mime.types; } location /static/ { alias /static/; } location ~ \.(css)$ { root /frontend/static/css; } } } This is what the entire directory looks like relative to my nginx (default.conf) file: ALL DIRECTORIES WITH DOCKER FILE -
GMB API upload image returns 'Fetching image failed.'
so I have an issue when using the GMB API for uploading media items. In my code, I am able to successfully request and obtain the resourceName as explained in the API docs. I then use the resourceName to upload an image as bytes. This also works very well and I get a 200 response. After this, I then begin the media upload using the steps documented in the API, however this time is fails and returns --> {'error': {'code': 400, 'message': 'Request contains an invalid argument.', 'status': 'INVALID_ARGUMENT', 'details': [{'@type': 'type.googleapis.com/google.mybusiness.v4.ValidationError', 'errorDetails': [{'code': 1000, 'message': 'Fetching image failed.'}]}]}} I have tried the same steps using the Oauth Playground and sending a curl request as well but it always fails in the last step yielding the same error. You can see my code below written in Python using the Django web framework: response = requests.post(f'https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations/{locationId}/media:startUpload', headers=HEADERS) if response.status_code == 200: resource_name = response.json()['resourceName'] with open('C:/Users/nevog/Desktop/testimonial-2.jpg', 'rb') as f: data = f.read() params = { 'upload_type': 'media', } response = requests.post(f'https://mybusiness.googleapis.com/upload/v1/media/{resource_name}', data=data, params=params, headers=HEADERS) if response.status_code == 200: print("upload successful") request_body = { "mediaFormat": "PHOTO", "locationAssociation": { "category": "ADDITIONAL" }, "dataRef": { "resourceName": resource_name }, } response = requests.post(f'https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations/{locationId}/media', json=request_body, headers=HEADERS) … -
cannot unpack non-iterable int object creating shop and cart in Django with session
I am creating a store and when executing this address http://127.0.0.1:8000/carro/agregar/3/ it has to load the product in the store widget where the cart is. If the car is not in the session, create it. Tried deleting cookies and nothing. But when I press the buy button on any product, in this case on product 3, the button sends to the correct address but the page gives me the following error TypeError at /carro/agregar/3/ cannot unpack non-iterable int object Request Method: GET Request URL: http://127.0.0.1:8000/carro/agregar/3/ Django Version: 4.0.4 Exception Type: TypeError Exception Value: cannot unpack non-iterable int object Exception Location: C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py, line 1374, in build_filter Python Executable: C:\Users\HP\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.4 and this C:\Users\HP\Documents\ProyectosDjango\ProyectoWeb\carro\views.py, line 8, in agregar_producto producto = Producto.objects.get(producto_id) views.py from django.shortcuts import redirect from .carro import Carro from tienda.models import Producto # Create your views here. def agregar_producto(request, producto_id): carro= Carro(request) producto = Producto.objects.get(producto_id) carro.agregar(producto=producto) return redirect('Tienda') def eliminar_producto(request, producto_id): carro= Carro(request) producto = Producto.objects.get(producto_id) carro.eliminar(producto=producto) return redirect('Tienda') def restar_producto(request, producto_id): carro= Carro(request) producto = Producto.objects.get(producto_id) carro.restar(producto=producto) return redirect('Tienda') def limpiar_carro(request): carro= Carro(request) carro.limpiar_carro() return redirect('Tienda') context_processor.py def importe_total_carro(request): total = 0 if request.user.is_authenticated: for key, value in request.session["carro"].items(): total = total +(float(value['precio'])*value['cantidad']) return {'importe_total_carro':total} urls.py from … -
Django channels Deploy nginx + uviconr + gunicorn]socket seems to be sending http request
referenced i'm using Reverse Proxy So the https setting is somewhere else. js log WebSocket connection to 'wss://urls/ws/exchange_rate/USD/' failed Dockerfile CMD ["gunicorn", "config.asgi:application", "-k", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000"] nginx.conf upstream django { server django:8000; } map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; # access_log off; # log_not_found off; # error_log /var/log/nginx/finance/error.log crit; location /ws/ { proxy_pass http://django/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location / { proxy_pass http://django/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } localhost test There is no log for socket and it works normally. gunicorn config.asgi:application -k uvicorn.workers.UvicornWorker server gunicorn log "GET /exchange_rate/USD/ HTTP/1.1" 404 It seems to be doing http communication. What did I do wrong? -
Django: how to add ckeditor plugins to my project using django
i want to add some plugins to my ckeditor django, i have installed the package using pip, installed it in settings.py and it's working now, but i want to add some more buttons to the ckeditor as all is have now is bold, align, media, emoji and some more , but i need some feature like code-snippets etc. so where should i add these plugins that i copied from the documentation https://django-ckeditor.readthedocs.io/en/latest/#installation a11yhelp, about, adobeair, ajax, autoembed, autogrow, autolink, bbcode, clipboard, codesnippet, codesnippetgeshi, colordialog, devtools, dialog, div, divarea, docprops, embed, embedbase, embedsemantic, filetools, find, flash, forms, iframe, iframedialog, image, image2, language, lineutils, link, liststyle, magicline, mathjax, menubutton, notification, notificationaggregator, pagebreak, pastefromword, placeholder, preview, scayt, sharedspace, showblocks, smiley, sourcedialog, specialchar, stylesheetparser, table, tableresize, tabletools, templates, uicolor, uploadimage, uploadwidget, widget, wsc, xml -
How i can add static files (css) to django web project
I have tested to embedded css style into html template, but it doesn't load css files, my configure as below, could you please help assist ? checkstatic\showstatic\templates\index.html <!DOCTYPE html> <meta charset="UTF-8"> <html lang="en"> <head> {% load static%} <link rel="stylesheet" type="text/css" href="{% static 'css/mystyle.css' %}"> </head> <body> <img src="{% static 'logo1.png' height="200" width="200" class="d-inline-block align-top" %}" alt=""> <h1 class="test">hahahaha</h1> </body> </html> checkstatic\static\css\mystyle.css .test{ color: red; } my settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'showstatic' ] ... STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'checkstatic/static/') ] when i access the index site, it only apply h1 tag, it can not load red color as the css config. -
Scaling dynos... ! ▸ Couldn't find that process type (web). ERROR with DEPLOYMENT
I am attempting to deploy a project and have been met with a couple errors. I first checked my logs running: heroku logs --tail which then ran error codes H14. After researching I came to a solution of running heroku ps:scale web=1 which then gives me the error of Scaling dynos... ! ▸ Couldn't find that process type (web). My ProcFile looks like this web: gunicorn takeitorleaveit.wsgi release: python manage.py migrate -
Current time of POST with datetime.now() [duplicate]
I have the date in the model as such but when I POST it always just returns the time of when I ran the server and not the current time of the post class UserPost(models.Model): user = models.ForeignKey(User_profile, on_delete=models.CASCADE) h_body = models.CharField(max_length=140) post_date = models.DateTimeField(default=datetime.now()) -
window.location.replace returns incorrect link
I use window.location.replace(qrMessage) in my Django project, but it add the current page's URL before qrMessage into the searching page's URL and can't open it. Why does it happen and how can I avoid this? -
Same coda as in tutorial and getting error
I'm learning Django with Tim. He have this code: Code And I have such a code: def create(response): if response.method == "POST": form = CreateNewList(response.POST) if form.is_valid(): name_of_form = form.cleaned_data['name'] lista = ToDoList(name=name_of_form) lista.save() else: formularz = CreateNewList() return render(response, 'main/forms.html', {'form': formularz}) It's simply the same code but still I get an error: "local variable 'formularz' referenced before assignment" What can I do with it other that asagning None to a form like this: def create(response): formularz = None if response.method == "POST": form = CreateNewList(response.POST) if form.is_valid(): name_of_form = form.cleaned_data['name'] lista = ToDoList(name=name_of_form) lista.save() else: formularz = CreateNewList() return render(response, 'main/forms.html', {'form': formularz}) It works with an error, but after sending a form, the page is rendering blank like This Not like for Tim, where after sending, he still have a form on a page: pic -
Django ERR_insufficient Resources
I have a Django app and for some reason I see this error when loading a page - see picture. It seems like there are a lot of icons being loaded but as far as I know I am not loading much in my template. Also, the page is SO slow to load. A screen-recording here: https://www.loom.com/share/f458664230f14bc9975852647812ef82 Here below the template {% extends 'action/project/project_base.html' %} {% load static %} {% load crew.tables %} {% load crew.availability %} {% load action_extras %} {% block p_header_cta %} <a href="{% url 'action:NewPosition' project.id %}" class="btn-red-border rounded-2"> New Position </a> {% endblock p_header_cta %} {% block project_content %} <!-- Top List --> <div class="row justify-content-between mt-5"> <div class="col"> <ul class="nav nav-pills minimalist mb-3" id="pills-tab" role="tablist"> <li class="nav-item" role="presentation"> <button class="nav-link active" data-role="tab" data-tab-selector=".tab-dates" type="button" role="tab" aria-controls="tab-dates" aria-selected="true">Dates</button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" data-role="tab" data-tab-selector=".tab-notes" type="button" role="tab" aria-controls="tab-notes" aria-selected="false">Notes</button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" data-role="tab" data-tab-selector=".tab-files" type="button" role="tab" aria-controls="tab-files" aria-selected="false">Files</button> </li> </ul> </div> </div> <!-- Top List --> <!-- Data container --> <div class="flex-grow-1 d-flex flex-row w-100 card bg-white border-1 rounded-2"> <!-- Left data container --> <div class="crew-title-column d-flex flex-column border-end ps-3"> <!-- Positions/status header --> <div class="crew-header d-flex flex-row align-items-center"> <div class="d-flex … -
Authentication with three fields in django-rest-framework-simple-jwt
I am working on custom authentication in DRF. User should send 3 fields (phone, email, password). I was following this answer Adding custom user authentication to django-rest-framework-simple-jwt (I was overriding TokenObtainPairSerializer and TokenObtainPairView) I was using this source code https://github.com/jazzband/djangorestframework-simplejwt/blob/master/rest_framework_simplejwt/serializers.py Problem: for the request below I received an empty response {} { "email": "admin1@admin2.ru", "password": "admin123456", "phone_number": "123132" } My code: views.py class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer serializers.py class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): username_field = CustomUser.USERNAME_FIELD def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields[self.username_field] = serializers.CharField() self.fields['password'] = PasswordField() self.fields['phone_number'] = serializers.CharField() # authentication requires 3 fields def validate(self, attrs): authenticate_kwargs = { self.username_field: attrs[self.username_field], 'password': attrs['password'], 'phone_number': attrs['phone_number'] } try: authenticate_kwargs["request"] = self.context["request"] except KeyError: pass self.user = authenticate(**authenticate_kwargs) if not api_settings.USER_AUTHENTICATION_RULE(self.user): raise exceptions.AuthenticationFailed( self.error_messages["no_active_account"], "no_active_account", ) return {} -
Django rest framework + Scrapy [twisted.internet.error.ReactorNotRestartable]. (Flutter + Dart)
I am working on a project that mixes a Django API with Scrapy, the idea is to run the API from my cell phone, said API will run the spider and then return all the information that I will get on my cell phone. When I do the search for the first time on the cellphone, everything works perfectly, but when I try to do another search, I get "twisted.internet.error.ReactorNotRestartable" Here's my API class Prueba(APIView): def post(self, request): dato = request.data['dato'] if dato: imprimir = self.execute(dato) res = json.dumps([o.dump() for o in imprimir], indent=3) return HttpResponse(res, content_type='application/json', status = status.HTTP_200_OK) else: return HttpResponse("NO", content_type='application/json') def execute(self, peticion): url = ['https://listado.mercadolibre.com.co/'+peticion] url2 = ['https://www.olx.com.co/items/q-'+peticion] process = CrawlerProcess({'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'}) process.crawl(ProductoSpider, start_urls=url) process.crawl(ProductoSpiderDos, start_urls=url2) process.start() return outputResponse #global variable in my spider Here's one of my spiders, I know it's a bit weird, but it's because I've been testing a few things. class ProductoSpiderDos(CrawlSpider): name = 'olx' item_count = 0 allowed_domain = ['www.olx.com.co'] def __init__(self, **kwargs): super().__init__(**kwargs) #//button[@data-aut-id="btnLoadMore"] #//div[@class="JbJAl"] rules = { Rule(LinkExtractor(allow = (), restrict_xpaths = ('//button[@data-aut-id="btnLoadMore"]'))), Rule(LinkExtractor(allow = (), restrict_xpaths = ('//li[@data-aut-id="itemBox"]/a')), callback = "parse_item", follow = False), } def parse_item(self, response): global outputResponse lista … -
How to add Wagtail blog categories as links in header and footer
I am building simple blog with posts and posts categories. I would like to add links to posts by category to header and footer, so they appear on every page, to just home page (as routable pages). How do I go about it? -
DRF How to select specific fields only in a nested serializer?
I have a serializer class CategoryListSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ["id", "name", "name_en", "about", "parent",] It is used in two locations: All Categories API: Used to view rich details about the categories. All Posts API: Used to know the name of the category only. In my Posts Serializer, I used: class PostListSerializer(serializers.ModelSerializer): categories = CategoryListSerializer(many=True, ) class Meta: model = Post fields = ["id", "title", "description", "publish_date", "thumbnail", "owner", "categories", ] And in my Post ViewSet: class PostViewSet(ReadOnlyModelViewSet): queryset = Post.objects.all().filter(is_published=True) serializer_class = PostListSerializer This returns All posts with All Categories Details mentioned in CategoryListSerializer, as it should be. Question: I want the PostListSerializer to return only the "name" field from the related Categories, without having to define another CategorySimpleSerializer that selects "name" field only. (I still need the CategoryListSerializer fields in another API) Is it possible to do that? Note: This is only an example, I'll have more usecases for this and want to know ahead if i'll have to create many custom "to-be-nested" Serialzers, to avoid exposing some unnecessary data to some of the APIs. It seemed like lots of redundant update work if a model or API needs change later. -
django: how to make a search bar?
I am new to django. I have done an online order management page using django, where registered users can view their own list of orders. Now I want to add a search bar for users to easily search for any orders. I noticed that in django admin user page, there is a search bar function. and This is exactly what I want. Can some one help to advise how to do the same search bar, incl. html and view.py, plus javascripts if needed. many thanks -
How to set up nested serializers without error
I am new to DRF and have been trying for the past weeks to set up a nested serializer structure. Essentially, I have a User model, and a Social Media model that has User as a Foreign Key: models.py class CustomUser(AbstractUser): id = models.UUIDField(default = uuid.uuid4, editable = False, primary_key = True) country = CountryField(blank_label='(select country)') updated_at = models.DateTimeField(auto_now = True, editable = False, null = True) gender = models.CharField(max_length=50, choices=Gender.choices, default = Gender.OTHERS) avatar = models.ImageField(upload_to = "avatar_pics", default = "avatar_pics/default.jpg", null = True) class UserSocialMediaAccounts(models.Model): id = models.UUIDField(default = uuid.uuid4, editable = False, primary_key = True) user = models.ForeignKey(CustomUser, on_delete = models.CASCADE) social_media = models.CharField(max_length=50, choices=SocialAccounts.choices) social_media_url = models.URLField(null = False) So far, my serializers for displaying the user and the associated social media accounts are: serializers.py class CustomUserSocialMediaSerializer(serializers.ModelSerializer): class Meta: model = UserSocialMediaAccounts fields = ('user','social_media', 'social_media_url') class CustomUserDetailSerializerSM(CountryFieldMixin,serializers.ModelSerializer): social_media = CustomUserSocialMediaSerializer(many = True) class Meta: model = CustomUser fields = ('email','first_name','last_name','country','gender','avatar','social_media') My view that I want to use to display the queried user's associated social media accounts: views.py class CustomUserDetailSocialMediaView(generics.ListCreateAPIView): serializer_class = CustomUserDetailSerializerSM permission_classes = (IsAuthorOrReadOnly,) def get_queryset(self): username = self.kwargs['username'] return UserSocialMediaAccounts.objects.filter(user__username = username) urls.py urlpatterns = [ path('detail/<str:username>/socialaccounts/',CustomUserDetailSocialMediaView.as_view()), ] However, if I tried to … -
Django Python Invalid Syntax When Deployed on Digitalocean
I have a Django project on local machine running on Python 3.10.3 Now I deployed it to a DigitalOcean machine running Ubuntu 20 and Python 3.8.10 When I run the project on local machine there is no issue, but when I do run it on the DO instance, it gives me a syntax error. Here is the code where it gives me the error: def get_day_by_date(date): weekday = date.weekday() match weekday: case 0: return "Lundi" case 1: return "Mardi" case 2: return "Mercredi" case 3: return "Jeudi" ....... This is the error I get in DO: [![enter image description here][1]][1] Is it a problem of the Python version? PS: I have already done pip freeze and installed the exact same requirements on both machines. [1]: https://i.stack.imgur.com/SM8Pt.png -
Response.__init__() takes 1 positional argument but 2 were given Django + Vue3
I build a project with django and vue3 I have problem with creating object. Code below throw a error: TypeError: Response.init() takes 1 positional argument but 2 were given this is my view.py class AddProjectView(viewsets.ModelViewSet): queryset = PassProjects.objects.all() serializer_class = AddProjectSerializer def create(self, request): data = request.data title = data.get('title') body = data.get('body') PassProjects.objects.create(who_create=request.user, title=title, body=body) return Response({'message': ' Project created'}) this is my urls.py router = DefaultRouter() ... router.register('addproject', AddProjectView, basename='addproject') urlpatterns = [ path('', include(router.urls)), ] serializer.py class AddProjectSerializer(serializers.ModelSerializer): class Meta: model = PassProjects fields = '__all__' what i need to change to fix this error? Thank's -
Django Annotate with one model and include "annotated" records in queryset
I am fairly new to Django and have figured out the "basic" annotate function, but I would like to include the records from the annotated values. For example, qs = People.objects.values('status').annotate(total=Count('id'),totalScore=Sum('score'),averageAge=Avg('age')) I would like to include the summarized records in the result, in this case the individual people, like so... [ {'status': 'One', 'total': 2, 'totalScore': 150, 'averageAge': 36, 'people': [ { 'id': 1, 'status': 'One', 'name': 'Jim', 'score': 80, 'age': 40 }, { 'id': 5, 'status': 'One', 'name': 'Jill', 'score': 70, 'age': 32 } ]}, {'status': 'Two', 'total': 1, 'totalScore': 85, 'averageAge': 42, 'people': [ { 'id': 3, 'status': 'Two', 'name': 'Jack', 'score': 85, 'age': 42 } ] },... Thanks for any help. -
How do you add pK's in a django url
I am makeing a blog and I want to go to a specific blog post by clicking on a button. I know I need to use a pk in the URL but I do not know the syntax or how to implement it any help would be appreciated. -
How to Merge values of 2 variable together Django
I have 2 Variables for which the values keep changing. I want to generate barcode for those 2 values side by side. For example {% assign boxes = 2 %} {% for x in (1..boxes) %} {% for sale in picklist.sales -%} {% barcode value: sale.marketplace_id %} {% endfor -%} {% endfor -%} this currently gets id and prints it as barcode. but i want to print id and x together in 1 barcode eg id=13423 boxes=2 so first barcode will be 13423 1 and next will be 13423 2 Please help... -
Access Model Method for Multiple Objects in Django
Let's say I have created a model in Django that looks like this: class Book(models.Model): author = models.CharField(max_length=64) ... (other attributes) def author_pretty(self): return "[··" + self.author + "··]" I need to get from all objects in DB the method author_pretty, as of now I'm doing this: authors = Book.objects.values_list('author', flat=True) authors_pretty = ["[·" + author + "·]" for author in authors] # or books = Book.objects.all() authors_pretty = [book.author_pretty() for book in books] Is there any way of doing this in a single call? Django would still have to make a query to DB and the call the method, but maybe there is a cleaner solution that I'm missing.