Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
facebook's sharer.php shows 403 Forbidden in share box
I am using this for sharing on Facebook. <meta property="og:image" content="https://url.com/{{ article.img_path }}"> <meta property="og:type" content="website"/> <meta property="og:title" content="{{ article.title }}"/> <meta property="og:description" content="{{ article.title }}"/> <meta property="og:url" content="https://url.com/{{ article.path }}"/> . . <a href="https://www.facebook.com/sharer/sharer.php?u=https://url.com/{{ article.path | urlencode }}"> <i class="fa fa-facebook-square fa-2x"></i> </a> I also get a 403 Forbidden in the box. Default is mobile view even on Desktop ? -
How to create invoice depending upon template give by User in django
I am making a web application built on django which has a feature of Invoice which should be downloadable. I want that invoice to be created depending upon the template provided by User. Eg: If a doctor uses my application he can upload the template of his medical clinic and whenever we generate invoices of patients for medicines all the invoice generated for prescribed medicines must be downloadable in that template. Please help me -
how to change EmailValidator Error Message
models.py class User(AbstractBaseUser): email = models.EmailField( verbose_name='Email', max_length=255, unique=True, error_messages={'msg':"Enter a valid Email Address"}, ) name = models.CharField(max_length=200) phone_number= models.CharField(max_length=200, blank=True) address= models.CharField(max_length=200, blank=True) tc = models.BooleanField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'tc'] serializer.py class UserRegistrationSerializer(serializers.ModelSerializer): # We are writing this becoz we need confirm password field in our Registratin Request password2 = serializers.CharField(style={'input_type':'password'}, write_only=True) class Meta: model = User fields=['email', 'name' ,'phone_number', 'address','password', 'password2','tc' ] extra_kwargs={ 'password':{'write_only':True}, } def validate(self, attrs): password = attrs.get('password') password2 = attrs.get('password2') if password != password2: raise serializers.ValidationError("Password and Confirm Password doesn't match") return attrs def create(self, validate_data): return User.objects.create_user(**validate_data) Output i am getting when i put an invalid email id { "email": [ "Enter a valid email address." ] } Expected Output { "msg": "Enter a valid email address." } I have used error_message in models to get the output i want and i have also used EmailValidator(message="") but nothing is working. I tried to use def clean_email in serializers.py but that also didn't worked. please help -
ERROR: TypeError at /admin/myapp/booking/19/change/
I've created a model using an abstract user model class for Online flight ticket booking. I'm new to this so haven't added many functionalities to it. I'm sharing my model.py, admin.py, serializer.py, views.py. My question: In the link below shows a screenshot of an error occurring while I want to GET PUT DELETE booking data using ADMIN panel. I'm not able to figure out the problem yet. Error while trying to GET PUT DELETE booking #models.py import email from pyexpat import model from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) class UserManager(BaseUserManager): def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None): if not email: raise ValueError('User must have an email address') user = self.model( email=self.normalize_email(email), name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None): user = self.create_user( email, name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, password=password, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = … -
when i am django date filter not working?
This is my query : I given the below dates: startdate : 2022-06-06 enddate : 2022-06-07 user=Model.objects.filter(agent=fullnames['username']).filter(status=ticket_status)).filter(completed_date__gt=startdate,completed_date__lt=enddate) output: after filter the query im getting this output , in this 2022-06-08 not required, but it is showing { "reference": "9802047093", "name": "Caliber", "completed_date": "2022-06-07" }, { "reference": "9802510868", "name": "Caliber", "completed_date": "2022-06-06" }, { "reference": "9738614446", "name": "Caliber", "completed_date": "2022-06-08" } -
Django: [Errno 2] No such file or directory: '/tmp/tmpmhi9gua5/texput.pdf' during generate a pdf
I need some help please, Hi for all here am trying to generate a pdf with latex in my django applicaton but i keep see an error when i add a specific data in my template-latex.tex. This is my views.py: if request.user.is_authenticated: if request.method == 'POST': form = ReportForm(request.POST, ) form.instance.user=request.user if form.is_valid(): form.save() obj_Formulaire = MyModel.objects.filter(user=request.user).last() field_obj_load_between_posts = MyModel._meta.get_field('load_between_posts') field_value_load_between_posts = field_obj_load_between_posts.value_from_object(obj_Formulaire) load_between_posts = field_value_load_between_posts if load_between_posts == True: field_obj_custom_load = MyModel._meta.get_field('custom_load') field_value_custom_load = field_obj_custom_load.value_from_object(obj_Formulaire) qh = float(field_value_custom_load) else: qh = float(0) #----some other code about getting the value fields---- w_profile = float(sizes_column_wprofile) w_project = round(float((1.5 * qh * distance * height) / fy),2) if w_profile >= w_project: resultat_mechanical = "Wprofile={0} > Wproject={1}".format(w_profile, w_project) resultat_resistance_criteria = "Profile Verified ✔" else: resultat_mechanical = "Wprofile={0} < Wproject={1}".format(w_profile, w_project) resultat_resistance_criteria = "Profile Not Verified" context = { 'qh': qh, 'resultat_resistance_criteria': resultat_resistance_criteria, 'resultat_mechanical' : resultat_mechanical } template = get_template('pages/my_latex_template.tex') rendered_tpl = template.render(context).encode('utf-8') # <3> with tempfile.TemporaryDirectory() as tempdir: # <4> for i in range(2): process = Popen( ['pdflatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') # <5> r.write(pdf) return r form = ReportForm() context = {'form': form} return render(request, 'pages/form_gelander_report.html', context) everything … -
Cannot open any page when implemented next parameter in Django 3.2
I am using Django 3.2. I have my custom LoginView and I'd like to implement the next parameter so if somebody will try to access the page where login is required then after log-in it will redirect the user to this page. I have seen many solutions but they are old and I cannot implement them in my code. views.py class UpdatedLoginView(LoginView, CategoryMixin, TagMixin): form_class = LoginForm template_name = 'user/login.html' redirect_field_name='main/homepage.html' def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): if 'next' in request.POST: return redirect(request.POST.get('next')) else: return(redirect('homepage')) else: return render(request, self.redirect_field_name, {'form': form}) class HomePageView(LoginRequiredMixin, TemplateView): template_name = "main/homepage.html" login.html <form method="post" novalidate> {% csrf_token %} {{ form|crispy }} {% if request.GET.next %} <input type="hidden" name="next" value="{{ request.GET.next }}"/> {% endif %} <button type="submit">Login</button> </form> settings.py LOGIN_REDIRECT_URL = 'homepage' LOGOUT_REDIRECT_URL = 'login' The problem with my solution is that it redirects me to homepage but once I click on any hyperlink it redirects me to login page again and the url looks like this: http://127.0.0.1:8000/?login=/article_list/ In all my views I am using LoginRequiredMixin mixin. How can I fix this issue? -
Django tests self.client.post using wrong url
I have a test which throws a NoReverseMatch exeption. In the test I define the url add_collection_url = reverse('add-cc-collection', args=[client.code, order.code]) and I can check that the url is found print(add_collection_url) which finds the correct url /crm/clients/A00001/order/O00001/add-cc-collection/ However, on the next line I post to the url response = self.client.post(add_collection_url, {'order': order.id, 'deadline': deadline, 'instructions': "Some instructions etc"}) and this line throws the exception django.urls.exceptions.NoReverseMatch: Reverse for 'add-collection' not found. 'add-collection' is not a valid view function or pattern name. note the reference to 'add-collection', which was the name of the url before I changed it to 'add-cc-collection'. When I run the server everything works as it should, it's just the test which throws the exception. My guess is something weird happening with caching but, for what it's worth I make sure to cache.clear() in TestCase tearDown