Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Nested Serializer Field - Empty OrderedDict
I'm currently having an issue with updating a nested serializer field, the dict value provided is being thrown away and mapped to an empty dict on the code side Serializer: class OrganizationSerializer(QueryFieldsMixin, BaseSecuritySerializer): class Meta: model = Organization fields = ("id", "name") depth = 0 class UsersSerializer(QueryFieldsMixin, BaseSecuritySerializer): organizations = OrgsSerializer(many=True) class Meta: model = Users fields = '__all__' depth = 0 def update(self, instance: ReportSchedule, validated_data): print("validated_data:", validated_data) ... REST Request: METHOD: Patch { "organizations": [{"id": 10}] } Outcome of print statement validated_data: {'organizations': [OrderedDict()]} -
Django FOREIGN KEY constraint failure in pre_delete
I've read quite a few related questions, since this is a beginner DB mistake, but for some reason I can't apply the answers to my situation. I have the following Event model, which contains a foreign key to a Machine model describing the originator of an event, class Event(models.Model): machine = models.ForeignKey( Machine, on_delete=models.SET_NULL, null=True, help_text='The machine this event originated from, or NULL if it has been deleted.') CATEGORY_MACHINE_CREATED = 'machine-created' CATEGORY_MACHINE_UPDATED = 'machine-updated' CATEGORY_MACHINE_REMOVED = 'machine-removed' CATEGORY_CHOICES = ( (CATEGORY_MACHINE_CREATED, 'Machine has been created'), (CATEGORY_MACHINE_UPDATED, 'Machine has been updated'), (CATEGORY_MACHINE_REMOVED, 'Machine has been removed'), ) category = models.CharField( max_length=25, choices=CATEGORY_CHOICES, help_text='The category of the event.') date = models.DateTimeField( default=timezone.now, help_text='The time this event was created.') def __str__(self): return f"<Event id={self.id} machine={self.machine} category={self.category}>" class Meta: ordering = ['-date'] I use signals to generate events around the lifetime of Machine models, @receiver(post_save, sender=Machine) def machine_change_callback(sender, instance, created, **kwargs): if created: logger.warning("CREATED %s %s %s" % (sender, instance, kwargs)) return Event.objects.create( category=Event.CATEGORY_MACHINE_CREATED, machine=instance) else: logger.warning("UPDATED %s %s %s" % (sender, instance, kwargs)) return Event.objects.create( category=Event.CATEGORY_MACHINE_UPDATED, machine=instance) @receiver(pre_delete, sender=Machine) def machine_deleted_callback(sender, instance, **kwargs): logger.warning("REMOVED %s %s %s" % (sender, instance, kwargs)) return Event.objects.create( category=Event.CATEGORY_MACHINE_REMOVED, machine=instance) Then, the following works as I expect, from … -
Capture DEBUG, INFO log level messages in Heroku
I would like to see INFO and DEBUG level logs in Heroku but I'm no sure how. Papertrail, for example, only shows WARNING level logs and above and I don't see any option to change that. I'm using python-django, but I don't think that matters. Is there any option to capture all logs in Heroku? -
Django dynamic form for variations products
I have two models for creating dynamic variations for each product, 'ItemVariation' --> e.g. Blue, Yellow, ... and 'Variation' --> e.g. Color, Size,... class Variation(models.Model): product = models.ForeignKey( Product, related_name='variations', on_delete=models.CASCADE) name = models.CharField(max_length=50) class Meta: unique_together = ( ('product', 'name') ) def __str__(self): return self.name class ItemVariation(models.Model): variation = models.ForeignKey( Variation, related_name='item_variations', on_delete=models.CASCADE) value = models.CharField(max_length=50) image = models.ImageField(blank=True) class Meta: unique_together = ( ('variation', 'value') ) def __str__(self): return self.value As you can see the variations are dynamic, and I can't figure how to add them to a form and then into view -
Django - Only allow one session per user results in Bad request
for some reason I get back http 400 (Bad Request) if I login on another browser while refrshing the first. I just want to accomplish that one user can only have one active session at a time. models.py class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session = models.OneToOneField(Session, on_delete=models.CASCADE) signals.py @receiver(user_logged_in) def remove_other_sessions(sender, user, request, **kwargs): # remove other sessions old_sessions = Session.objects.filter(usersession__user=user) if request.session.session_key: old_sessions = old_sessions.exclude(session_key=request.session.session_key) old_sessions.delete() # save current session request.session.save() # create a link from the user to the current session (for later removal) UserSession.objects.get_or_create( user=user, session=Session.objects.get(pk=request.session.session_key) ) For some reson the first browser does not delete the session, instead it keeps the session and I get back http 400 until I delete the session key manually. I would expect that If the session key does not exist anymore the user is redirected to the login. Can smb. Help? Kind regards -
Reverse for 'xyz' not found. 'chat' is not a valid view function or pattern name. At redirect('xyz')
I am getting an error while using the path in Django. this is the code where the redirect function is called in views.py def addmsg(request): c = request.POST['content'] new_item = messageItem(content = c) new_item.save() bot_msg(c) return redirect('chatapp:chat') urls.py app_name = 'chatapp' urlpatterns = [ path('chat', views.chatbot, name='chat'), path('addmsg',views.addmsg, name='addmsg'), ] Django error: NoReverseMatch at /addmsg Reverse for 'chat' not found. 'chat' is not a valid view function or pattern name. Request Method: POST Request URL: http://localhost:8000/addmsg Django Version: 2.2.17 Exception Type: NoReverseMatch Exception Value: Reverse for 'chat' not found. 'chat' is not a valid view function or pattern name. Exception Location: C:\Users\xyz\Documents\Python\hotel\hotel2\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 673 Python Executable: C:\Users\xyz\Documents\Python\hotel\hotel2\env\Scripts\python.exe Python Version: 3.9.1 Python Path: ['C:\\Users\\xyz\\Documents\\Python\\hotel\\hotel2', 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\xyz\\Documents\\Python\\hotel\\hotel2\\env', 'C:\\Users\\xyz\\Documents\\Python\\hotel\\hotel2\\env\\lib\\site-packages'] Server time: Mon, 1 Feb 2021 18:26:38 +0000 I have also registered the app name in settings.py -
i need help beacause django with doesnt really work for me
Im having a problem with project for school that im working on. when i run the code and go to "random page" link that i created, nothing happens. After trying for a bit, i think the problem is that whatever is in {{}} doesnt seem to be found. views.py: from django.shortcuts import render from django.http import HttpResponse from . import util import random def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) random_page = random.choice(entries) def CSS(request): return render(request, "encyclopedia/css_tem.html", { "article_css": "css is slug and cat" }) def Python(request): return render(request, "encyclopedia/python_tem.html", { "article_python": "python says repost if scav" }) def HTML(request): return render(request, "encyclopedia/HTML_tem.html", { "article_HTML": "game theory: scavs are future humans" }) def Git(request): return render(request, "encyclopedia/Git_tem.html", { "article_Git": "github is git" }) def Django(request): return render(request, "encyclopedia/Django_tem.html", { "article_Django": "this is a framework" }) layout.html: <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> Create New Page </div> <div> <a href = "http://127.0.0.1:8000/{{random_page}}">Random Page</a> </div> {% block nav … -
Django: Not able to execute Validators instead the Except block execute
I'm trying to make an email and password validation using validators in Django. I have my own custom Registration form. I'm just fetching the email and password values from it using a view called 'Register'. Whenever I try to register a new user, the code always runs into the except block, I'm pretty sure I'm doing something wrong with validate_email() and validate_password(). Here's my view: def register(request): if request.method == 'GET': return render(request, 'index.html') else: username = request.POST['username'] email = request.POST['email'] pass1 = request.POST['password1'] pass2 = request.POST['password2'] try: validate_email(email) except ValidationError: return render(request, 'register.html', {'emailErr':'Hmm.. Did you enter a valid email?'}) try: validate_password(pass1) validate_password(pass2) except ValidationError: #This block runs return render(request, 'register.html', {'passErr':'Please enter a valid password'}) if User.objects.filter(email=email).exists(): return render(request, 'register.html', {'error1':'Email already exists'}) else: if pass1 == pass2: try: user = User.objects.create_user(username=username, password=pass1, email=email) user.save() login(request,user) sendConfirm(user) return render(request, 'confirm_please.html') except IntegrityError: return render(request, 'register.html', {'error2':'User already exists'}) else: return render(request, 'register.html', {'error3':'Make sure the passwords are same'}) A little help would be appreciated -
Validating views.py
Can someone advice me how to prevent to 'POST' empty form? i think im missing: if form.is_valid()... but im too noob and dont know where to implement it... def addContact(request): if request.method == 'POST': new_contact = Contact( full_name = request.POST ['fullname'], relationship = request.POST ['relationship'], email = request.POST ['email'], phone_number = request.POST ['phone-number'], address = request.POST ['address'], ) new_contact.save() return redirect('/contact') return render(request, 'contact/new.html') -
How to add Django env folder into .gitignore?
What would I write in my .gitignore file to make it so the CIS440_Env folder is ignored? -
Why am I getting the "refers to field which is not local to model" error while migrating the following models?
I am trying to create a database schema for a simple Visitor Management System where I am creating two models named Visitor and Host by extending the inbuilt User model in Django. The model Appointment is for mapping the relation between the Visitor and Host with their meeting time slot. However, I am getting the 'demoapp.Appointment.host_email' refers to field 'email' which is not local to model 'demoapp.Host' error mentioned in the title when I run python manage.py makemigrations. Why am I getting this, how can I fix it and is there a better way to do it? from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.core.validators import RegexValidator class Host(User): class Meta: verbose_name = "Host" verbose_name_plural = "Hosts" phone = models.CharField(verbose_name='Phone Number',max_length=10, validators=[RegexValidator(regex='[0-9]{10}')], unique=True, null=True) class Visitor(User): class Meta: verbose_name = "Visitor" verbose_name_plural = "Visitors" phone = models.CharField(verbose_name='Phone Number',max_length=10, validators=[RegexValidator(regex='[0-9]{10}')], unique=True, null=True) purpose = models.CharField(verbose_name='Purpose of meeting', max_length=150, null=True) class Appointment(models.Model): host_email = models.ForeignKey(Host, to_field='email', on_delete=models.CASCADE, verbose_name='Host Email') visitor_email = models.ForeignKey(Visitor, to_field='email', on_delete=models.CASCADE, verbose_name='Visitor Email') slot = models.DateField(verbose_name='Appointment Slot', default=timezone.now) is_confirmed = models.BooleanField(verbose_name='Booking Confirmed', default=False) -
unable to load CSS of Static files in django
i just created a django app in project. when i am running the server content is displaying but css styles are not applying. Here is my settings configuration of staticfiles. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') urls configuration of staticfiles. if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) here is code of html : <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>MyApp</title> <link rel="stylesheet" href="{% static 'css/app.css' %}"> </head> -
How can I make my User fields case insensitive during user-login?
I'd like to make my user login fields non case-sensitive for username and email only. I applied it to my models, but then I realized I should keep the data as is and true to itself. How can I apply case-insensitivity to the two fields mentioned above? views.py class CustomUserCreate(APIView): permission_classes = [AllowAny] def post(self, request, format='json'): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: json = serializer.data return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py class CustomUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) username = serializers.CharField(required=True) password = serializers.CharField(min_length=8, write_only=True) first_name = serializers.CharField(max_length=30) last_name = serializers.CharField(max_length=30) subscribed = serializers.BooleanField(default=False) class Meta: model = User fields = ('email', 'username', 'password','first_name','last_name','subscribed') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance model.py: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) start_date = models.DateTimeField(default=timezone.now) subscribed = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name','password'] def __str__(self): return self.username Thank you for any guidance! -
How to get Web Socket to receive messages with Django Channels
I have a chat application with React handling the frontend and Django with using Channels to handle the web socket connection. I can see both on the frontend and backend that the socket is connected and I can see in the terminal that the receive function in ChatConsumer runs but the client isn't receiving it and I can not figure out why. Also if I run self.send() on the connect function in the ChatConsumer, then the client then receives the message. Any help would be greatly appreciated. Here is my code -> asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import rooms.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'musicapp.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( rooms.routing.websocket_urlpatterns ) ) }) routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/room/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] consumers.py import json from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): # Do nothing on disconnect pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) print('[SOCKET] Transmitting a message: ', text_data) room.js import React, { useState, useEffect } from "react"; import axios from 'axios'; import Cookies from 'js-cookie'; import { makeStyles } … -
How to copy a object data to another object in Django?
I am trying to create an E-Commerce Website and I am at the Final Step i.e. Placing the Order. So, I am trying to add all the Cart Items into my Shipment model. But I am getting this error. 'QuerySet' object has no attribute 'product' Here are my models class Product(models.Model): productId = models.AutoField(primary_key=True) productName = models.CharField(max_length=200) productDescription = models.CharField(max_length=500) productRealPrice = models.IntegerField() productDiscountedPrice = models.IntegerField() productImage = models.ImageField() productInformation = RichTextField() productTotalQty = models.IntegerField() alias = models.CharField(max_length=200) url = models.CharField(max_length=200, blank=True, null=True) class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(max_length=100) profileImage = models.ImageField(blank=True, null=True, default='profile.png') phoneNumber = models.CharField(max_length=10, blank=True, null=True) address = models.CharField(max_length=500, blank=True, null=True) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) dateOrdered = models.DateTimeField(auto_now_add=True) orderCompleted = models.BooleanField(default=False) transactionId = models.AutoField(primary_key=True) class Cart(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, blank=True, null=True) dateAdded = models.DateTimeField(auto_now_add=True) class Shipment(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) orderId = models.CharField(max_length=100) products = models.ManyToManyField(Product) orderDate = models.CharField(max_length=100) address = models.CharField(max_length=200) phoneNumber = models.CharField(max_length=13) I just removed additional functions i.e. __str__ and others. Here is the views.py def orderSuccessful(request): number = Customer.objects.filter(user=request.user).values('phoneNumber') fullAddress = Customer.objects.filter(user=request.user).values('address') timeIn = time.time() * 1000 … -
TypeError object is not iterable on (rest_framework) Django
I'm unable to understand how to handle this error. TypeError at /auctions/api/AuctionDetails/68/ 'Request' object is not iterable in "auctions/view.py" def detail(request, auction_id): auction = get_object_or_404(Auction, pk=auction_id) auction.resolve() already_bid = False if request.user.is_authenticated: if auction.author == request.user: own_auction = True return render(request, 'auctions/detail.html', {'auction': auction, 'own_auction': own_auction}) user_bid = Bid.objects.filter(bidder=request.user).filter(auction=auction).first() if user_bid: already_bid = True bid_amount = user_bid.amount return render(request, 'auctions/detail.html', {'auction': auction, 'already_bid': already_bid, 'bid_amount': bid_amount}) return render(request, 'auctions/detail.html', {'auction': auction, 'already_bid': already_bid}) in API folder: api/serilazers.py class AuctionsSerializer(serializers.ModelSerializer): class Meta: model = Auction fields = ["title", "desc", "min_value", "is_active", "date_added","winner","author","image","date_added","final_value","title"] in api/url.py path('AuctionDetails/<int:auction_id>/', AuctionsDetailsApiView.as_view()), I tried to put this code in "api/views.py" Thank you very much! -
django gunicorn on nginx problem to deploy in production
hello i have django in www directory and i have created gunicorn socket so its kinda works but problem is to cannt create secret kay in environment and cannt find what type of file should be i have seen how created for docker yml file and also .sh file but how can i create file which will be writed some file to change instance like yml file gunicorn django_project.wsgi also this runs for like dev like runserver and i have to pin in gunicorn and rund to be production right? i have but still cannt find how to make backside code for environment ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2021-02-01 09:24:43 UTC; 1h 13min ago TriggeredBy: ● gunicorn.socket Process: 66236 ExecStart=/home/user/venv/bin/gunicorn django_project.wsgi (code=exited, status=3) Main PID: 66236 (code=exited, status=3) Status: "Gunicorn arbiter booted" Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: File "/var/www/html/web/django_project/settings.py", line 23, in <module> Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: SECRET_KEY = os.environ['SECRET_KEY'] Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: File "/usr/lib/python3.8/os.py", line 675, in __getitem__ Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: raise KeyError(key) from None Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: KeyError: 'SECRET_KEY' Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: [2021-02-01 09:24:43 +0000] [66248] … -
How to control allowed methods in Django Rest Framework?
I've already seen a number of questions on this topic, but none of the answers seem to solve my issue. I have the following python modules: views.py: class MyObjectViewSet(viewsets.ModelViewSet): queryset = MyObject.objects.all() serializer_class = MyObjectSerializer permission_classes = [permissions.AllowAny] # For testing @action(methods='POST', detail=True) def my_request(self, request, *args, **kwargslf): # Do stuff urls.py: router = routers.DefaultRouter() router.register(r'myobject', views.MyObjectViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] When I try to make an actual POST-request to the my_request-route, I get Method POST not allowed. But as I understand, ModelViewSet should allow all methods. Even if I include http_method_names = ['get', 'post', 'patch', 'put', 'head', 'delete'] in my view, it still doesn't work. -
Download processed opencv images from Django template
I am new, both to Django and Opencv. I work on a Django website where i would like to allow the user to upload some images, to process them and in the end to download them without storing them in the database. How can i include a link in the template where the user can download the processed images from? cv2.imwrite returns a boolean value. Is there any way to append the processed images to a list to be able to send it back to the template? -
I want to search for products in my html page using javascript but it does not show anything
I am making an online shopping website as in django and wanted to use the searchbar using javascript but can't do it right. I think that I am not accessing the elements in javascript correctly. Any help would be appreciated. TIA! HTML Code <div id = 'Products'> <div class="col-12"> <div class="row"> <div class="col-12 py-3"> <div class="row"> <div class="col-12 text-center text-uppercase"> <h2>Featured Products</h2> </div> </div> <div class="row"> <!-- Product --> {% for prd in prds %} <div class="col-lg-3 col-sm-6 my-3"> <div class="col-12 bg-white text-center h-100 product-item"> <div class="row h-100"> <div class="col-12 p-0 mb-3"> <a href=" {% static 'product.html' %} "> <img src="{{prd.img.url}}" class="img-fluid"> </a> </div> <div class="col-12 mb-3"> <a href=" {% static 'product.html' %} " class="product-name">{{prd.name}}</a> </div> <div class="col-12 mb-3"> <span class="product-price"> ${{prd.price}} </span> </div> <div class="col-12 mb-3 align-self-end"> {% if user.is_authenticated %} <button onclick="location.href= '/xyz/{{prd.id}}'"class="btn btn-outline-dark" type="submit" ><i class="fas fa-cart-plus mr-2"></i>Add to cart</button> {% else %} <a href= "accounts/login"><button class="btn btn-outline-dark" type="submit" ><i class="fas fa-cart-plus mr-2"></i>Add to cart</button></a> {% endif %} </div> </div> </div> </div> {% endfor %} </div> </div> </div> </div> </div> Search Bar <div class="input-group"> <input type="search" onkeyup="search_product()" class="form-control border-dark" placeholder="Search..." required> <div class="input-group-append"> <button class="btn btn-outline-dark"><i class="fas fa-search"></i></button> </div> </div> JavaScript Code function search_product() { let input … -
Is the a Django serializer to serialize reverse relations individually?
I have these two models, where A has a many-to-one relation with B: class A(models.Model): field_A1 = models.ForeignKey('B', ...) field_A2 = ... class B(models.Model): field_B = ... #primary key I know I can setup a serializer for B to also serialize the related instances of A, taking advantage of .a_set. For instance, if I tried to serialize an instance of B having two related instance of A I would get something like the following: { "field_B": "instance of B", "a_set": [ { "field_A2": "first related instance of A" }, { "field_A2": "second related instance of A" } ] } What I want the serialize to output instead is the 'product' of instance of B with the related instances of A, e.g. in the same scenario as in the previous example, I would like to get the following: [ { "field_B": "instance of B", "field_A": "FIRST related instance of A" }, { "field_B": "instance of B", "field_A": "SECOND related instance of A" } ] How can I obtain this in Django? Do I need to populate a data structure with the product myself or there's something built-in in the framework I can use? -
How to resolve “django.core.exceptions.ImproperlyConfigured: Application labels aren't unique
Traceback (most recent call last): File "/home/lewis/Documents/FakeNewsProject/fakenewsgui/myapp/class_learner.py", line 62, in class ArticleExample(models.Model): File "/home/lewis/.local/lib/python3.6/site-packages/django/db/models/base.py", line 321, in new new_class._meta.apps.register_model(new_class._meta.app_label, new_class) File "/home/lewis/.local/lib/python3.6/site-packages/django/apps/registry.py", line 231, in register_model (model_name, app_label, app_models[model_name], model)) RuntimeError: Conflicting 'articleexample' models in application 'Article_Examples': <class 'myapp.models.ArticleExample'> and <class 'main.ArticleExample'>. I have tried various solutions from here but none seems to have worked -
Specify database inspectdb in django
Is there any way how can I inspectdb specific database in Django. I've been open new connection and then I want to inspectdb under matchyv3_revamp. How do I specify matchyv3_revamp in inspectdb? It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance Currently I'm using this line python manage.py inspectdb --database=matchy > models.py but it seems it inspect all database under matchy connection, is there any way to specify matchyv3_revamp? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'payroll', 'USER':'root', 'PASSWORD':'', 'HOST':'localhost', 'PORT':'3306', }, 'matchy': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'matchy', 'USER':'test_user', 'PASSWORD':'sample', 'HOST':'172.26.111.111', 'PORT':'80', }, } -
Using middleware class for user authentication in Django project
One of my company's project is in Django and I was assigned to a task to 'add authentication to the top-level router' so we don't forget to add an authentication code to every view, such as: if not request.user.is_authenticated: return HttpResponseRedirect('/admin/login/?next=/admin/some-page/') After doing a bit of research I found out that this can be accomplished by writing my own middleware. I was not familiar at all with the concept until doing my homework. So now I am trying to write a LoginRequiredMiddleware class that intercepts every request and sends the user to the login page if not authenticated and, after authentication, to the original page the user was trying to access. This is the code I have so far. middleware.py from django.conf import settings from django.http import HttpResponseRedirect from django.utils.deprecation import MiddlewareMixin from django.utils.http import is_safe_url import re EXEMPT_URLS = [re.compile(settings.LOGIN_REDIRECT_URL.lstrip('/'))] # '/admin' class LoginRequiredMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'user'), "The Login Required Middleware" if not request.user.is_authenticated: path = request.path_info.lstrip('/') if not any(m.match(path) for m in EXEMPT_URLS): redirect_to = settings.LOGIN_REDIRECT_URL if len(path) > 0 and is_safe_url( url=request.path_info, allowed_hosts=request.get_host()): redirect_to = f"{settings.LOGIN_REDIRECT_URL}/login?next={request.path_info}" return HttpResponseRedirect(redirect_to) I have already registered the middleware in the MIDDLEWARE list in settings.py and included both SessionMiddleware … -
Django Rest Framework - ImageField - use default value if no image is provided
I am sending a POST request with Axios using FormData that contains an individual image and also a list of images, like this: React State: "thumbnail": thumbnailImage, "gallery": [ galleryImage0, galleryImage1, galleryImage2 ] FormData: formData.set("thumbnail", this.state.thumbnail); for (let image of document.querySelector("#gallery").files){ formData.append("gallery", image); } Note: this part is probably fine, as the problem persists even when using Postman to craft the request In Django, using DRF I can perfectly deserialize this data if there are actual images sent, but if for example the "thumbnail" does not contain a file (user did not choose a file), I get the following: [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')] What I actually want is to use the default provided in the model, which looks like this: class Item_ThumbnailImage(models.Model): image = models.ImageField(upload_to=hash_image_thumbnail, default='items/no-image.gif', blank=True) belongs_to = models.ForeignKey( 'Item', related_name='thumbnail', on_delete=models.CASCADE) I get the data ready this way: thumbnail_data = { 'belongs_to': item.id, 'image': request.data.get("thumbnail") } Here's the deserialization: thumbnail = Item_ThumbnailImageSerializer(data=thumbnail_data) if thumbnail.is_valid(): thumbnail.save() else: print(thumbnail.errors) Serializer: class Item_ThumbnailImageSerializer(serializers.ModelSerializer): class Meta: model = Item_ThumbnailImage fields = '__all__' I have tried this in the serializer: image = serializers.ImageField(required=False, allow_empty_file=True, allow_null=True) ...along with this: thumbnail_data = { 'belongs_to': …