Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How to customize forms file input
I working with Django & Tailwind CSS project where needs to upload image. I use forms to do this. Now form looks like: image = forms.ImageField(widget=forms.FileInput(attrs={ "class": "bg-nav-blue rounded-xl", } )) But for now it's looks like this one. But for my design I need button How to customize view of this form? -
how to make delete in GenericDeleteView() from Tamplete?
Here is the Model: from django.db import models: class RefugeCamp(models.Model): Camp_Name = models.CharField(max_length=100) Camp_District=models.CharField(max_length=30) Camp_Address =models.CharField(max_length=200) Camp_Block = models.IntegerField() Camp_Population = models.IntegerField() def __str__(self): return str(self.Camp_Name) Here is view : from django.shortcuts import render from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import ListView from django.urls import reverse_lazy from django.db import IntegrityError from django.views.generic import DetailView,UpdateView,DeleteView from django.contrib.auth.decorators import login_required from RefugeCamp.forms import RefugeCampForm from RefugeCamp.models import RefugeCamp # Create your views here. class detail_camp(DetailView): models=RefugeCampForm queryset = RefugeCamp.objects.all() paginate_by = 100 template_name = 'camp/detail.html' class list_camp(ListView): models=RefugeCamp queryset = RefugeCamp.objects.all() paginate_by = 100 template_name = 'camp/camps.html' def add_camp_view(request): if request.method == 'POST': form = RefugeCampForm(request.POST) if form.is_valid(): form.save() pk = form.instance.pk return redirect('camp:detail.html', pk=pk) else: form = RefugeCampForm() context = {'form': form} return render(request, 'camp/addcamp.html', context) class CampDeleteView(DeleteView): # specify the model you want to use model = RefugeCamp template_name = 'camp/delete.html' # can specify success url # url to redirect after sucessfully # deleting object Urls: from django.urls import path from .import views from RefugeCamp.views import list_camp ,detail_camp,CampDeleteView app_name = 'RefugeCamp' urlpatterns = [ path('', views.add_camp_view, name='addcamp'), path('camps/',list_camp.as_view(),name='camps'), path('detail/<int:pk>/', detail_camp.as_view(), name='detail'), path('delete/<int:pk>', CampDeleteView.as_view(), name='camp_delete'), ] now i want to call Delete function from camps.html {% … -
Get Data in a particular Format from serializers in Django
My Models: class Student(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=25) class Subject(models.Model): name = models.CharField(max_length=100) class Student_subject_mapping(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) I'm trying to get all Student_subject_mapping data in the database in a format given below: { "results": [{ "id": 1, "email": "student_1@gmail.com", "subjects": [ { "id": 1, "name": "subject_1" }, { "id": 2, "name": "subject_2" }, ... ] }, My serializers: class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('email') class SubjectSerializer(serializers.ModelSerializer): class Meta: model = Subject fields = '__all__' class Student_Mapping_Serializers(serializers.ModelSerializer): class Meta: model = Student_subject_mapping fields = "__all__" How can I achieve data in the above format? -
Open edx , oath2 as provider
I want to redirect to support application from open edx using single sign-on using oauth i.e I will log in to open edx only and while redirecting to support application it shouldn't ask for credentials. Anyone can help me with how to configure or achieve this s=using open edx tutor? Any help is appreciated. -
How to make a web platform discussed in my description? please don't close or down vote ques it becomes difficult for new users
Let me start by what all things are involved: Data in csv file a python script that i have a python file containing a function that user have. On website the user will upload python file. Then the data i have in csv file will be parsed through user's given function which will generate a single Column Dataframe. Then the resultant Dataframe will be parsed through my Python script which will generate an output and this output will be presented to user on website. I am not able to get the approach and technologies involved but this is very important for me to do please help please Any resource or Reference will be helpful pls help Thank you. -
A django url that contains several optional arguments / parameters
While trying to build my first django project, I am stuck at passing values for product filtering. Every feature which has value 1 passed to it, will be an active filter, and others will be 0, i.e. inactive. urls.py: urlpatterns=[ path('women/<str:category>/filter?pricefrom=<int:min>&to=<int:max>&size?s=<int:s>&m=<int:m>&l=<int:l>&xl=<int:xl>&xxl=<int:xxl>&xxxl=<int:xxxl>&color?blue=<int:blue>&red=<int:red>&yellow=<int:yellow>&black=<int:black>&white=<int:white>&green=<int:green>&brown=<int:brown>',views.women_category,name='women category page with filters'), ] views.py: def women_category(request,category,id=None,flag=None,min=None,max=None,s=None,m=None,l=None,xl=None,xxl=None,xxxl=None,blue=None,red=None,yellow=None,black=None,white=None,green=None,brown=None): #product filter logics here I want that the user should be able to use any possible combination of filters, with the filters being: Price: min,max Size: S,M,L,XL,XXL,XXXL color:yellow,blue,green,...etc I don't know how to use Regex in urls, so please help me convert my url into a regex url so that all filter variables are optional to be passed through the fronted. -
How do I change Serverroot directory with Python Path in Django
I have downloaded Apache from Apachelounge. Details : Apache Lounge VS16 Server built: Apr 21 2020 16:23:13 Server's Module Magic Number: 20120211:92 Server loaded: APR 1.7.0, APR-UTIL 1.6.1 Compiled using: APR 1.7.0, APR-UTIL 1.6.1 Architecture: 64-bit httpd.conf: Define SRVROOT "c:/Apache24" ServerRoot "${SRVROOT}" LoadFile d:/python/python37.dll LoadModule wsgi_module d:/lidarlabellingtool_vikram_new2/lidar_venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd WSGIPythonHome d:/lidarlabellingtool_vikram_new2/lidar_venv WSGIPythonPath "D:\Main Project\Lidar-annotation-tool\lidarLabellingTool\lidarProjct" WSGIScriptAlias / "D:\Main Project\Lidar-annotation-tool\lidarLabellingTool\lidarProjct\lidarProjct\wsgi_windows.py" Require all granted Alias /static "D:\Main Project\Lidar-annotation-tool\lidarLabellingTool\lidarProjct\static" Require all granted Require all granted Require all granted Require all granted Require all granted I am facing an issue here. To give you some background here are few details. I am developing my Django application on Windows 10. I am setting my python path in env variable "PATH" (Windows) and WSGIPythonPath in httpd.conf they both are same. There is a file under "D:\Main Project\Lidar-annotation-tool\lidarLabellingTool\lidarProjct\static\scenes" folder which I want to serve it when the request hits the server. But Apache server is taking "c:/Apache2" as base path, I want the Apache server to take WSGIPythonPath or env variable PATH to serve. I am unable to proceed on this. Can somebody help me on this? -
DjangoCMS products and catalog
I want to create DjangoCMS website which shows only a product list and has a filter function. Is there such plugin? Can you suggest me? -
Get queryset of related objects of field from queryset
for example, i have two models. class Store(models.Model): name = models.CharField() class Book(models.Model): store = models.ForiengKey(Store, on_delete=....) I have one queryset of Store objs. I need a queryset of related books with this objs queryset. Please help -
python djnago - automatic log out - inactive user
i want to automatic log out my application when user does not do anything . first user login then user is not active 30 mint. after 30 mint , need to log out automatically how can i done it from client side using python- Django i tried Django-session-time out , using this. https://pypi.org/project/django-session-timeout/ . but its not working in client side. client side always active mode.. how can i log out the inactive user ? -
Handle properly datetimefield in django
Actually I'm facing invalid error whenever I'm using datetime field in django here is my models class Record(models.Model): record_date_time = models.DateTimeField(blank=True) record_time = models.TimeField(blank=True) record_date = models.DateField(blank=True) and forms.py class RecordCreateForm(forms.ModelForm): class Meta: model = Record fields = '__all__' widgets = { 'record_date_time': forms.TextInput(attrs={ 'type': 'datetime-local' }), 'record_time': forms.TextInput(attrs={ 'type': 'time' }), 'record_date': forms.TextInput(attrs={ 'type': 'date' }), } as shown in image, everytings works fine with date field and time field, But I'm facing error with datetime field. I don't know what I'm missing. I need help as soon as possible. -
Django taggit url pattern not working in Production
I was successfully using Django-taggit in development environment but when I have pushed the app to server it has started getting error in url for taggit. Reverse for 'tagged' with arguments '('',)' not found. 1 pattern(s) tried: ['ads\\/tag\\/(?P<slug>[^/]+)$'] My url: path('ads/tag/<slug>', views.filtered_ads, name="tagged") My href: {% for tag in data.tags.all %} <a href="{% url 'furugi:tagged' tag.slug %}" class="mr-1 badge badge-info">{{ tag.name }}</a> {% endfor %} Any thoughts, why is it happening as I am unable to find the problem? -
How to forward naked domain to www with HTTPS [closed]
I'm trying to forward correctly: https://example.com to https://www.example.com without going through 'Your connection is not private' security issue page I don't know why is this happening because my site is secured with HTTPS certificate. If I write this in browser: https://www.example.com will go directly to my secured site without browser's security page popping up. The forward is working but I want to get rid of the security issue. I know is possible because I've seen on other sites. How can I do this? I'm using GoDaddy with the following DNS settings: -
Django redirecting to wrong view
I have an app called 'vocab', which so far contains a CreateView and a ListView. In my project urls.py file, I have the following: urlpatterns = [ path('admin/', admin.site.urls), path('',views.HomePage.as_view(),name='home'), re_path(r"^accounts/", include("accounts.urls", namespace="accounts")), re_path(r"^accounts/", include("django.contrib.auth.urls")), re_path(r"^logout/$", views.LogOutPage.as_view(), name="logout"), re_path(r"^vocab/", include("vocab.urls", namespace="vocab")), ] And then, in my app urls.py file, I have the following: urlpatterns = [ path('list/', views.WordList.as_view(), name="list"), path("home/",views.VocabHome.as_view(),name='home'), path("create/", views.CreateWord.as_view(), name="create"), ] And in my html templates I have links to these views. The home and list views work, but when I click on the 'create' link, it takes me to 'list' instead. In the command line I can see that it is accessing /vocab/list/? instead of /vocab/create/. I know the create view works, because if I type it in manually it goes there. And if I delete all the other views it works as well. So it is as if django cannot find the 'create' view when there are others. I've tried my best to solve this problem by making sure all the paths are unique, and I've tried using regular expressions, but it still doesn't work. Any help would greatly be appreciated! -
Obtain the label from my choices in my views.py - Django
I have a model where one of the fields is the color assigned. class Gateway(models.Model): colors = ( ('0','Black'), ('1','White'), ('2','Blue'), ('3','Red'), ('4','Green'), ('5','Brown'), ('6','Grey'), ('7','Pink'), ('8','Purple'), ('9','Orange'), ('10','Yellow'),('11','Darkolive'), ('12','Lightpink'),('13','Lightblue'), ) gat_id = models.CharField(max_length=16, primary_key=True, unique=True) gat_name = models.CharField(max_length=20, unique=True) gat_lat = models.FloatField() gat_lon = models.FloatField() gat_color = models.CharField(max_length=5, choices=colors, default='Black') My problem is when I want to obtain the model data in my views.py, because I'm doing the following, gateways = Gateway.objects.all() gateways = loads(serializers.serialize('json', gateways)) And this return de color id and I prefer the name of the color. Reading some posts I understand I have to use .choices but I'm not sure where. Can somebdoy help me please? Thank you very much -
Implement Search field in ManytoManyField(Django Admin) models.py
I currently have a ManytoManyField in Django where I can Select multiple Users with strg and mouseclick. With much more Users it gets heavily complicated to search the User I want to select. Is there a possibility to have a ManytoManyField, but also have a search_field for Users, so I can search and pick. Thank you for your help! -
How do I create a form in django that selects instances of another django model?
I'm new to django and so far I've created these models. Climb represents climbing routes with names, week, grade, and points associated if completed and a Climber model that has climbs_completed, which is a collection of Climb. My question is how do I create a django form that displays the existing Climb objects with a checkbox so that the user can select which Climb he/she has completed and save it to their climbs_completed field? class Climb(models.Model): name = models.CharField(max_length=20, default='') grades = [('v'+str(i),'v'+str(i))for i in range(0,13)] grade = models.CharField(max_length=3, choices=grades, default='v-1') weeks = [(i,i)for i in range(1,13)] week = models.IntegerField(choices=weeks, default=0) points = models.IntegerField(default=0) def __str__(self): return self.name class Climber(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) grades = [('v'+str(i),'v'+str(i))for i in range(0,13)] highest_grade = models.CharField(max_length=3, choices=grades, default='v0') team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) climbs_completed = models.ManyToManyField(Climb, blank=True) def __str__(self): return self.user.username # for each climbs_completed, sum up the points @property def total_score(self): return self.climbs_completed.aggregate(total_score=Sum('points'))['total_score'] -
Django efficient use of prefetch related in one to many relationship and large db
I'm already a few days busy creating a list of devices. A device is linked with gateways due to the gatewaydevice class. "GatewayDevice" is a table in SQL, where a device can be linked to many gateways. But for every device there is only one gateway with no "end_date", that's the current one. I need to display that gateway, for every device. Besides that there are some other attributes, but those are fine. I will start with the code of the models and then my query and serializer models: class Device(models.Model): name = models.CharField(max_length=250, null=True, blank=True) class GatewayDevice(models.Model): gateway = models.ForeignKey( Gateway, on_delete=models.CASCADE, related_name="devices" ) device = models.ForeignKey( Device, on_delete=models.CASCADE, related_name="gatewaydevices" ) class Gateway(models.Model): name = models.CharField(max_length=250, null=True, blank=True) view: def get(self, request): """ GET the data from all the devices. """ devices = Device.not_deleted_objects.filter( delivery_status=Device.RECEIVED ).prefetch_related( "site__users", "software_update_history", "supplier", Prefetch( "gatewaydevices", queryset=GatewayDevice.objects.filter( end_date=None, gateway__isnull=False ).prefetch_related("gateway"), ), ) serializer_class = self.get_serializer_class() serializer = serializer_class(devices, many=True) devices_data = serializer.data return Response( {"total": devices.count(), "items": devices_data}, status=status.HTTP_200_OK ) serializer: class AdminDeviceSerializer(serializers.ModelSerializer): gateway = serializers.SerializerMethodField() class Meta: model = Device fields = [ "id", "name", "gateway", ] @staticmethod def get_gateway(device): return GatewaySimpleSerializer(device.gatewaydevices.get).data class AdminDeviceInfoSerializer(AdminDeviceSerializer): owner = serializers.SerializerMethodField() supplier = serializers.SerializerMethodField() class Meta(AdminDeviceSerializer.Meta): fields … -
how to architect 'crawling.py file' and 'django-restapi server'?
guys. i have a problem. i made an android application written by kotlin. this app communicates to 'django-restapi server' to get some data. 'django-restapi server' gets data from 'crawling.py' file(using selenium,headless chrome). app : show data to people django-restapi server : get data from crawling.py, and saving data on database crawling.py(with chromedriver) : crawling data from website, and sending data to server so, what i want to know is, i don't know how to upload them. i want to use aws. what i'm thinking now is, upload 'django-restapi server' and 'crawling.py' to aws lambda seperately. then, i will run 2 lambda. but i think it's bad architecture. the alternative is to upload all of them into an ec2. and scheduling crawling.py works once in 10minutes. can you advice me better answer? -
Django Admin. Change the title of app page
The default title for every app page is '''verbose_name + "administration"''' How can I change it? -
Cant seem to get my model formset to update my record
The function to create a record works perfectly but the update is the problem. the update function is able to pull the data from the database but u cant save any changes. here is my view.py ''' the create view function def HunCreateView(request): BenefitFormset = modelformset_factory(Staff, form=BenefitForm) form = HonpvForm(request.POST or None) formset = BenefitFormset(request.POST or None, queryset=Staff.objects.none(), prefix ='marks') if request.method == 'POST': if form.is_valid() and formset.is_valid(): try: with transaction.atomic(): pv = form.save(commit=False) profileid = request.user.profile.id pro = Profile.objects.get(id=profileid) pv.worker = pro pv.save() for staff in formset: data = staff.save(commit=False) data.Pv_reference = pv data.save() except IntegrityError: print("Error Encountered") messages.success(request, 'Pv created successfully') return redirect('pv:userdash') context ={'form':form, 'formset':formset} return render(request,'pv/Honurarium.html',context) ''' the update function def HunupdateView(request,pk): pupdate= Pv.objects.get(IA_System_Code=pk) supdate = Staff.objects.filter(Pv_reference=pk) BenefitFormset = modelformset_factory(Staff, form=BenefitForm) form = HonpvForm(instance=pupdate) formset = BenefitFormset(queryset=supdate, prefix='marks') if request.method == 'POST': if form.is_valid() and formset.is_valid(): try: with transaction.atomic(): pv = form.save(commit=False) profileid = request.user.profile.id pro = Profile.objects.get(id=profileid) pv.worker = pro pv.save() for staff in formset: data = staff.save(commit=False) data.Pv_reference = pv data.save() except IntegrityError: print("Error Encountered") messages.success(request, 'Pv created successfully') return redirect('pv:userdash') context ={'form':form, 'formset':formset} return render(request,'pv/Honurarium.html',context) and here is my url.py path('pv/honurarium/',views.HunCreateView, name = 'pv-honurarium'), path('pv/<int:pk>/update/honurarium',views.HunupdateView, name ='hunupdate') the add more and delete fieldset … -
Python, is there a function that give me the cumulate sum? [duplicate]
I have the following list value: iva_versamenti_totale={'Liquidazione IVA': [sum(t) for t in zip(*iva_versamenti.values())],} I want to obtain about the iva_versamenti_totale variable the following sum: p0, p1+p0, p2+p1, p3+p2 and so on... Ad example: iva_versamenti_totale = {'Liquidazione IVA': [1,2,3,4,5],} result={'Totals': [1,3,5,7,9],} -
How Python Django Templates Know about Model user data , when I haven't Passed any data of Model User to template
I've looked through different tutorials and Stack Overflow questions and I'm not sure why I'm still running into this issue: -
Why might my code be using my OS's installed Python when I'm running in a virtual environment?
I'm following a book which introduces Django and at the same time teaches TDD for Python. The stage I'm at is attempting to use POP to retrieve an email (sent to a yahoo.com email) in order to examine its contents. I am running everything on my local machine (which is running tests against a remote server, in my case a VPS hosted by Hostinger). We've just been told to do this, on the local machine (in fact source this from a local .env file): YAHOO_PASSWORD=myYahooPassword The failure which this gives is like this: (test_venv369) mike@M17A ~/IdeaProjects/TestingGoat $ STAGING_SERVER=mikerodentstaging.xyz python manage.py test functional_tests.test_login ... ERROR: test_can_get_email_link_to_log_in (functional_tests.test_login.LoginTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/mike/IdeaProjects/TestingGoat/functional_tests/test_login.py", line 72, in test_can_get_email_link_to_log_in body = self.wait_for_email( test_email, SUBJECT ) File "/home/mike/IdeaProjects/TestingGoat/functional_tests/test_login.py", line 28, in wait_for_email inbox.pass_(os.environ['YAHOO_PASSWORD']) File "/usr/lib/python3.6/os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'YAHOO_PASSWORD' ... and my first puzzled response was to export the variable, instead of leaving it as a non-exported variable. This gave another error: the FT hung (!), for about 60 s, before ending thus: ERROR: test_can_get_email_link_to_log_in (functional_tests.test_login.LoginTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/mike/IdeaProjects/TestingGoat/functional_tests/test_login.py", line 72, in test_can_get_email_link_to_log_in body = self.wait_for_email( test_email, SUBJECT ) File "/home/mike/IdeaProjects/TestingGoat/functional_tests/test_login.py", … -
Error in fetching data from database SQL Server
I have a django project, wherein I take comments from user by executing the following command: Comment = request.POST.get('comment').replace('\n', '\026').replace(' ', '\030') The Comment is then inserted into the DB in the above shown form. There are several 'ID's, each of which can have multiple Comments. Now, the task is to fetch those IDs and corresponding comments which contain particular keywords, which are provided by the user. Here is the query(sample) I am using to fetch the required data: query = "select Comment, ID from table1 where ID in ({}) and Comment like '{}'".format("'1','2','3'", "%Compilation failed%".replace(' ', '\030').replace('\n', '026')) I want this query to fetch all those ID/comment pairs which contain the keyword Compilation failed. However, executing this is fetching me some IDs which actually do not contain the 'Compilation failed' error. What could be the reason for this? I tried a lot but could not figure it out. Any help is greatly appreciated!