Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Registering Django objects with child objects
I have two tables named product and variant. I am building an offer creation module. While creating the offer, I want to pull the products from the product and variant table and save them to the offer product table, but I am having problems with the checkboxes. model.py from django.db import models from firma.models import company class variant(models.Model): name = models.CharField('Varyant Adı',max_length=200) price = models.IntegerField('Varyant Fiyat') stok = models.IntegerField('Varyant Stok') company = models.ForeignKey(company,on_delete=models.CASCADE) image = models.FileField(upload_to="variant",default="") def __str__(self): return f"{self.name}" class product(models.Model): name = models.CharField('Ürün Adı',max_length=200) price = models.IntegerField('Ürün Fiyat') stok = models.IntegerField('Ürün Stok') variant = models.ManyToManyField(variant,blank=True) company = models.ForeignKey(company,on_delete=models.CASCADE) image = models.FileField(upload_to="product",default="") def __str__(self): return f"{self.name}" model.py class offerProductInfo(models.Model): offerProductName = models.CharField('Ürün Adı',max_length=200) offerProductPrice = models.IntegerField('Ürün Fiyat') offerProductStok = models.IntegerField('Ürün Stok') offerProductVariant = models.ManyToManyField(offerVariantInfo,blank=True) offerProductCompany = models.ForeignKey(company,on_delete=models.CASCADE) offerProductImage = models.ImageField(upload_to="product") def __str__(self): return f"{self.offerProductName}" view.py def teklifsave(request): if not request.user.is_authenticated: return redirect('login') if request.method == 'POST': offerVariantId = request.POST.getlist('offerVariantId') offerProduct = request.POST.getlist("offerProducts") count = -1 for fproduct in offerProduct: print(fproduct) count += 1 h = variant.objects.get(id=offerVariantId[count]) c = h.product_set.all() print(c) s = offerVariantInfo( offerVariantName = h.name, offerVariantPrice = h.price, offerVariantStok = h.stok, offerVariantCompany = h.company ) s.save() z = product.objects.get(id=fproduct) c = offerProductInfo( offerProductName = z.name, offerProductPrice = z.price, … -
Django ValueError: field admin.LogEntry.user was declared with a lazy reference to 'app.user', but app 'app' doesn't provide model 'user'
I have a similar problem to this post but its only answer didn't help: ❯ python manage.py makemigrations No changes detected Because when I execute python manage.py migrate I get the following traceback: ❯ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, portfolio, sessions Traceback (most recent call last): File "C:\Users\user\Projects\personal_website\src\packages\pweb_django\manage.py", line 23, in <module> main() File "C:\Users\user\Projects\personal_website\src\packages\pweb_django\manage.py", line 19, in main execute_from_command_line(sys.argv) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\commands\migrate.py", line 236, in handle pre_migrate_apps = pre_migrate_state.apps File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\db\migrations\state.py", line 544, in apps return StateApps(self.real_apps, self.models) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\db\migrations\state.py", line 615, in __init__ raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'portfolio.user', but app 'portfolio' doesn't provide model 'user'. Yet, when I check the file portfolio\models.py it clearly provides the 'user'-model: class User(AbstractUser): """Dummy class in order to mimic a standard Auth-user. Docs: https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project """ pass In the related … -
On Raw HTML, website looks as I intend it. But on Django, there is some blank space created during the for loop
<div id="Project" class="bg-white fnt-white brdr project-div "> <div class="float-left image-for-project-container brdr"> <img src="{% static './Images/manworking.webp' %}" alt="manworking" height="630px"> </div> {% for project in project_details %} <div class=" project-container inline-block "> <h2 class="text-center fnt-black head-portfolio"> {{project.project_name}} </h2> <br> <br> <p class="margin-auto txt-portfolio roboto hover-orange fnt-black"> {{project.project_details}} </p> <br> <a href="#" class="buttons read-more fnt-black">Read More</a> </div> </div> Issue: The project container when receiving dynamic entries from Django model, creates multiple project containers as executed by the forloop. However, as evident from the image attached, as each project container is created, it is creating an unwanted upward indentation or margin successively. What am I doing wrong? This is the HTML code. I do not think there is any requirement for my CSS stylesheet as when I view the HTML file without Django, it's absolutely alright. I have also attached an image to show the space that is being created. In case the Imgur is not being shown here is the link (https://i.stack.imgur.com/EnUUG.png). -
How do I update data in a linked django rest model?
How do I update data in a linked django rest model Here is my json { "doc_type": 1, "warehouse": 4, "date": "2022-06-09", "number": 980, "contragent": 2, "comment": "testcom;mgment", "items": [ { "product": 7, "buy_price": "168.00", "sell_price": "500.00", "quantity": 17 }, { "product": 8, "buy_price": "168.00", "sell_price": "500.00", "quantity": 17 } ] } I can't change the data in the "items" dictionary If I submit only one "product" element, will the other one be deleted? And if, for example, three, will it be added? this is what I have at the moment, records are created without problems, but I can only update the "ConsignmentNote" model #serialisers.py class ConsignmentNoteSerializer(serializers.ModelSerializer): creator = serializers.HiddenField(default=serializers.CurrentUserDefault()) doc_type = serializers.IntegerField(read_only=True) # contragent_detail = ContragentSerializer(source='contragent', read_only=True) items = ConsignmentItemSerializer(many=True) class Meta: model = ConsignmentNote fields = ['doc_type', "warehouse", 'date', 'number', 'contragent', 'comment', 'creator', 'items'] read_only_fields = ['id' ] def create(self, validated_data): items = validated_data.pop('items') note = ConsignmentNote.objects.create(**validated_data, doc_type = 1) for item in items: product = item.pop('product') item = ConsignmentItem.objects.create(consignmentnote=note, product=product ,**item) return note def update(self, instance, validated_data): instance.date = validated_data.pop('date', instance.date) instance.comment = validated_data.pop('comment', instance.comment) return instance -
Compare entirely two different models in Django
I have been working in Django template. I have been stuck here since quite some time now. {% for i in LOOP %} {% if i == {{SECOND VARIABLE}} %} //Do Something {% endif %} {% endfor %} LOOP and second variable are entirely different. Is there something we can do? Is there some alternate solution -
Django,MSSQL server query and pagination
This is a sample of my MSSQL server table Employeetable emp_id name status EMP001 A STATUS-A EMP001 A STATUS-B EMP002 B STATUS-C EMP001 A STATUS-D EMP002 B STATUS-D EMP003 C STATUS-C Now in my app front end page there is a table in which each employee is listed once in the table and expanding each employee will show their every available status For Example: EMPID NAME EMP001 A ---STATUS-A #After expanding the EMP001 row it shows all the status of EMP001 ---STATUS-B ---STATUS-D EMP002 B EMP003 C So how can we use pagination in this consider there are about 200K records and about 100K distinct employees -
How do I test if my django is connecting to my cloud proxy auth mysql site?
I am receiving this error: django.db.utils.ProgrammingError: (1146, "Table 'xpotoolsdb.xpotoolshome_site' doesn't exist") in pycharm on mac os and windows 10. My coworkers are not and they are able to run a local development environment. How would I go about troubleshooting this error? It seems as if my local dev env is not finding a table in the mysql database but I don't think it's actually connecting at all since my coworkers aren't receiving the same error. -
Forms django -> is_valid
i'm currently developping an application on django and when i send a post request from a form, is_valid method return false. my forms.py : from django import forms class formadduser(forms.Form): mail = forms.CharField(label='Mail', max_length=40) # imput_username = forms.CharField(input='input_username', max_length=100) prenom = forms.CharField(label='Prénom', max_length=25) # input_password = forms.CharField(input='input_pathword', max_length=100) nom = forms.CharField(label = 'Nom', max_length=25) -
should I use drf APIView's alongside with django Views in a production project?
I am just learning djangorestframework and my question is: "should I use APIView's alongside with Views?" my friend told me that I should have an api app and for some parts you should only use normal django Views and other parts related to admins the APView. Now I'm a bit confused what should my project structure look like for exmple in an ecommerce project? Thanks for your help! -
Django Validation Check More than two negative list value will give validation error
i have this data , so basically i have to check if i have one list of negative value and one list of positive value and then if i add another list of negative values will rasie validation error. how i can implement that.I am working on django . django /models.py a=[-8,-9] & b=[8,9] & c=[-7,-12] def clean(self): if (self.a <0 and self.b >0).exists , then adding another negative list will raise validation error -
Request swagger with Django view
i'm trying to request swagger of django app from django view. To clarify what I mean, this is an example: @action(methods=['GET'], detail=False, permission_classes=[AllowAny]) def get_swagger(self, request, *args, **kwargs): try: be_url = "http://localhost:8000/?format=openapi" r = requests.get(be_url) except Exception as e: return Response('data': str(e)) return Response('data': r.json()) But when I request this endpoint response goes very long and then fails with a 404. -
Django smtp sendmail is not working for sending mail
I wrote this on settings.py DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = '*********' forms.py from django import forms from django.conf import settings from django.core.mail import send_mail class Emailform(forms.Form): name = forms.CharField(max_length=120) email = forms.EmailField() inquiry = forms.CharField(max_length=70) message = forms.CharField(widget=forms.Textarea) def get_info(self): cd = super().clean() name = cd.get('name').strip() from_mail = cd.get('email') subject = cd.get('inquiry') msg = f'{name} with email {from_mail} said:' msg += f'\n"{subject}"\n\n' msg += cd.get('message') return subject, msg def send(self): subject, msg = self.get_info() send_mail( subject=subject, message=msg, from_email=settings.EMAIL_HOST_USER, fail_silently=False ) views.py from django.views.generic import FormView, TemplateView from .forms import Emailform from django.urls import reverse_lazy from django.shortcuts import redirect class EmailView(FormView): template_name = 'index.html' form_class = Emailform success_url = reverse_lazy('mailapp:success') def form_valid(self, request): if request.method == 'POST': form = Emailform(request.POST) if form.is_valid(): form.send() return redirect('mailapp:success') else: form = Emailform() class EmailSuccessView(TemplateView): template_name= 'success.html' My code is running successfully, but I'm not receiving the mail. I even tried to edit the send function, but it's not working even after that. I'm just confused here. Can anyone tell me why am I getting this problem? My python version is 3.10 and Django version is 4.0.5. Thank you in … -
Django production multiple post request
I have a question regarding the multiple handling of django. I have read the answers to this question How does Django handle multiple requests?. I wrote a django application and it is deployed which takes POST request and do some string splitting in the background and returns the results on the side. My problem would be that if two users sent two POST request (from two different clients), then the process is slowed down dramatically and I only see one process in my Apache server. I am not sure whether Django handles just a request at a time and I could not distribute the process properly. Is a asynchronical restructuring necessary? Thanks -
How do I add packages to an existing docker container using pipenv
I currently have a Django app running in a docker container and I want to install additional packages to the container without rebuilding the entire container. I've tried bringing up the container using: docker-compose up then docker-compose exec web pipenv install "package_name_here" what happens is the package installs but I lose it the moment I shut down the container. How do I persist the installation even after shutting down the container without also rebuilding the entire container? -
django and mypy with apps in a subfolder
We have a Django project with the following setup: We have our apps in an apps folder. We added all those apps to the python path at settings.py level. We then can refer and import these apps like so: from apps.booking.models import Booking # or from booking.models import Booking Now, we want to use mypy for type checking purposes. The issue is that mypy does not recognize the import from booking.models import Booking and complains about missing stubs for this module. This make the typing very unreliable and not very useful as Booking is then typed as Any. It works fine with an import as follow however from apps.booking.models import Booking Is there a way to make mypy understand the path without the prefix apps. ? I tried to use mypy_path = $MYPY_CONFIG_FILE_DIR/apps in mypy.ini but without any success... -
Send POST from JS to Django
I'm trying to send POST with some veriables to DJANGo Send from JS: function sendStatistic(csrftoken, song_id, answer) { fetch('request/', { method: 'POST', headers: { 'X-CSRFToken': csrftoken, 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: { 'Song-Id': song_id, 'Answer': answer ,}, }); } And try to capture 'Song-Id' and 'Answer' in Django but request.POST.get('Answer') returns None what am I doing wrong? -
File sharing system
I need a file sharing system, precisely videos, to create a movie site, educational or something like that. To be a good option, it must meet the following criteria, or almost all of them: Videos accessible only on my website Easy implementation Good price The django project is complete, I just need links to embed for video playback class Episode(models.Model): movie = models.ForeignKey("Movie", related_name="episodes", on_delete=models.CASCADE) title = models.CharField(max_length=100) video = models.URLField() # This embedded link def __str__(self): return f'{self.movie.title} - {self.title}' -
Django 'The current path, dict_list2.html, didn’t match any of these.'
I wanna make dictionary by using Django. I made a code like this but it caused an error 'The current path, dict_list2.html, didn't match any of these.' Help me.. urlpatterns = [ path('admin/', admin.site.urls), path('^/$', views.csvToModel1, name='dict_list1'), path('^/$', views.csvToModel2, name='dict_list2'), path(r'^dialect/$', views.csvToModel3, name='dict_list3'), path(r'^dialect/$', views.csvToModel4, name='dict_list4'), path(r'^dialect/$', views.csvToModel5, name='dict_list5'), path(r'^dialect/$', views.csvToModel6, name='dict_list6'), path(r'^dialect/$', views.csvToModel7, name='dict_list7'), path(r'^dialect/$', views.csvToModel8, name='dict_list8'), path(r'^dialect/$', views.csvToModel9, name='dict_list9'), path(r'^dialect/$', views.csvToModel10, name='dict_list10'), path(r'^dialect/$', views.csvToModel11, name='dict_list11'), path(r'^dialect/$', views.csvToModel12, name='dict_list12'), path(r'^dialect/$', views.csvToModel13, name='dict_list13'), path(r'^dialect/$', views.csvToModel14, name='dict_list14'), ] -
Update a geodjango field after surface computation
I've got a database with a list of building in multiple areas. I want to update all area instances at once with the density of building. Here are my models: class Area(models.Model): mpoly = models.MultiPolygonField() surface = models.DecimalField(max_digits=8, decimal_places=2) density = models.DecimalField(max_digits=3, decimal_places=2) class Building(models.Model): mpoly = models.MultiPolygonField() Here my code (but it fails): sub_qs = Building.objects.filter(mpoly__intersects=OuterRef("mpoly")) sub_qs = sub_qs.annotate( intersection=Intersection("mpoly", OuterRef("mpoly")), intersection_area=Area(Transform("intersection", 2154)), ) sub_qs = sub_qs.aggregate(Sum("intersection_area")) Area.objects.all().annotate( surface_built=Cast( Subquery(sub_qs[:1]), DecimalField(max_digits=3, decimal_places=2) ) ).update(density=F("surface_built")/F("surface")) How would you do it ? -
The @login_required decoration is not working in Django (user not authenticated?)
I am new to Django and I am trying to set up a login page and I am trying to use the @login_required decoration. However, whenever I try and log in with valid credentials I am re-directed to the 'login' page (set to re-direct unauthenticated users). I am not sure if the problem is in the @login_required decoration or perhaps the login() function is not authenticating the user Here is my code for the register form: class RegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] code for login function in views.py: def login_user(request): if request.method =="GET": return render(request, "main/login.html", {}) else: username = escape(request.POST['userfield']) password = escape(request.POST['passfield']) try: user = User.objects.get(username=username) except: user = None if user is None: try: user = User.objects.get(email=username) except: user = None if user is None: messages.info(request, "*Sorry, that username or email does not exist") return redirect('login') pword = user.password if check_password(password, pword): login(request, user) return redirect('homepage') else: messages.info(request, '*Sorry, that was an incorrect password') return redirect('login') my model for User in models.py: class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100) email = models.EmailField(unique=True) password = models.CharField(max_length=100) admin = models.BooleanField(default=False) last_login … -
Can I make a Django query that returns a list per item?
I have 3 models like this: class Person(models.Model): name = models.CharField(max_length=100) class Place(models.Model): name = models.CharField(max_length=100) # ManyToMany Through Table class PersonPlace(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) place = models.ForeignKey(Place, on_delete=models.CASCADE) PersonPlace links Person and Place in a ManyToMany relationship. I want a database query that will give me a list of place id's per person (a list of places every person has visited). Is it possible to make that aggregation through the ORM without having Python put this together? -
How can I allow my dictionary to accept duplicate keys [closed]
I have a function that is creating a dictionary of lists: def Planner(calories, dislikes): carbs = Food.objects.filter(category='Carbs').exclude(name__in=dislikes) proteins = Food.objects.filter(category='Protein').exclude(name__in=dislikes) vegs = Food.objects.filter(category='Vegetables').exclude(name__in=dislikes) carb1 = random.choice(carbs) protein1 = random.choice(proteins) veg1 = random.choice(vegs) carb2 = random.choice(carbs) protein2 = random.choice(proteins) veg2 = random.choice(vegs) veg_exclude = [veg1, veg2] veg3 = Food.objects.filter(category='Vegetables').exclude(name__in=veg_exclude)[0] meals = [carb1, protein1, carb2, protein2] carb3 = random.choice(carbs) protein3 = random.choice(proteins) meals.append(carb3) meals.append(protein3) total_cals = sum(meal.calories * meal.portion_size_in_grams / 100 for meal in meals) calories_short = calories - total_cals calories_per_gram = sum(meal.calories * 1 / 100 for meal in meals) extra_grams_needed = calories_short // calories_per_gram meal_dict = { meal.name: [meal.portion_size_in_grams + extra_grams_needed, meal.calories, meal.category, meal.pack_size] for meal in meals} meal_dict[veg1.name] = [veg1.portion_size_in_grams, veg1.calories, veg1.category, veg1.pack_size] meal_dict[veg2.name] = [veg2.portion_size_in_grams, veg2.calories, veg2.category, veg2.pack_size] meal_dict[veg3.name] = [veg3.portion_size_in_grams, veg3.calories, veg3.category, veg3.pack_size] for key, value in meal_dict.items(): meal_plan_total_cals += value[0] * value[1] / 100 meal_dict['total_calories'] = meal_plan_total_cals meal_dict['total_meals'] = 3 return meal_dict I need the dictionary to be able to accept duplicate keys as sometimes the function will generate the same meal twice (which is fine) but when it gets added to the dictionary it will just overwrite the existing key which is not the intended functionality. How can I modify my code so that the … -
Objects of model does not have primary key
Good morning, unfortunately I can't get out of a problem found in the code: I created a new model to distinguish between sales orders and purchase orders. The problem is that in no way is a primary key recognized when I create the object in question. Through the admin section I create the object but if I try to click on it, it is not recognized, nor can I delete it. Through Robo 3T I notice that compared to the orders of the first model, the second model has one less field, the one related to the id. The models in question are virtually identical, but one works, the other doesn't. models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.utils import timezone class Profile(models.Model): user_profile=models.ForeignKey(User,on_delete=models.CASCADE) btc=models.IntegerField(default=5) usd=models.IntegerField(default=100000) initial_balance=models.IntegerField() class Order(models.Model): profile=models.ForeignKey(User,on_delete=models.CASCADE) datetime=models.DateTimeField(default=timezone.now()) price=models.FloatField() quantity=models.FloatField() class SellOrder(models.Model): buyer_profile=models.ForeignKey(User,on_delete=models.CASCADE) buyer_datetime=models.DateTimeField(default=timezone.now()) buyer_price=models.FloatField() buyer_quantity=models.FloatField() views.py from django.shortcuts import render,redirect,get_object_or_404 from django.contrib.auth import authenticate,login,logout from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .models import Profile,Order, SellOrder from django.views.decorators.csrf import csrf_exempt from .forms import OrderForm, SellOrderForm import requests def home_page(request): price=get_price() return render(request,'app/home_page.html',{'price':price}) @csrf_exempt def register_user(request): price=get_price() if request.method=='POST': form=UserCreationForm(request.POST) if form.is_valid(): form.save() username=form.cleaned_data['username'] password=form.cleaned_data['password1'] user=authenticate(username=username,password=password) login(request,user) messages.success(request,"Registration Successful!") … -
Check if specific channel name exists (is connected) in Django Channels
I'm using Django Channels and need to limit the maximum number of currently active connections by a single user. I'm storing data about present users with django-channels-presence. Basically, I add and remove db records whenever connect and disconnect methods on my consumer are called. That works well unless there's a server crash or reload and I'm looking for a better way to determine currently connected users. Specifically, I'm trying to check if a specific channel name (which is stored in the database record) exists and is connected. Hoped to find some method for it on the channel_layer object (it's returned with get_channel_layer() function), but no luck there. -
Session are not passing between function
I have been trying to pass data between the functions using sessions. The problem is that while testing locally it works perfectly, while testing the same in a development server it doesnt works. Following is my code: views.py def pre_login(request): ... ... if login_obj['success'] == True: request.session['pre_login'] = "Abcd" return JsonResponse("Success", safe=False) def login(request): pre_login = request.session.get('pre_login') print(pre_login) Above works locally but not in server. Development server is simply running using manage.py runserver. What might be the possible cause of it?