Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
Try except inside a function doesn't work but outside does
I'm trying to get the try except block outside of my function as a part of DRY. If I put it directly into the function it works @api_view(["GET", "POST"]) def user_info(request): if request.method == "GET": username = request.GET.get("username") password = request.GET.get("password") try: Account.objects.get(username=username, password=password) except Account.DoesNotExist: return JsonResponse({ "success": "false", "error_code": "1", }) But if I make it into function user_check it doesn't work @api_view(["GET", "POST"]) def user_info(request): if request.method == "GET": username = request.GET.get("username") password = request.GET.get("password") user_check(username,password) def user_check(username,password): try: Account.objects.get(username=username, password=password) except Account.DoesNotExist: return JsonResponse({ "success": "false", "error_code": "1", }) -
Is there a way better than this to save Database in django model from an external API?
I have an external API to get the data and I need to save the data into my Django Model. As of now I am writing a function that save the data into the Model from the JSON response of the API. Now since I need to save the database only once I need to remove the function so as to reduce the chance of duplicate data. So Is there any better way to save the data so that I do not need to remove the function and function is such that I runs only once in entire project? Any help would be appreciated. Thanks -
What should be the approach for the web platform i want to create and please don't down vote or close this question it is very important for me? [closed]
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. -
How to serialize a custom user model(inherited from AbstractUser class) in django rest framework?
I was following a tutorial on django rest framework in which we create a new user using register api route(/api/auth/register) and login the registered user using login api route(/api/auth/login). In this tutorial,for token authentication, django-rest-knox has been used and the default User model provided by django has been used for user accounts. I am trying to do something similar in my own app but I am using custom user model which has been inherited from AbstractUser class provided by django and also I am using Django Token authentication provided by rest_framework.authtoken. Following are the code and their results for serializers, Apiviews from the tutorial: Serializers look like this: from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import authenticate # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user # Login Serializer class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") Now using these serializers API views were created … -
Django Rest Framework Session Authentication
I'm using Django-hosts and hosting my api at api.mydomain.com while my frontend is using django templates at mydomain.com. I'm having some trouble getting session authentication working– my understanding is that if I am session-authed on my web app, I should also be session-authed on my subdomain but this doesn't seem to be true. Is it because of the subdomain– and how should I deal with this? -
How to get extra columns in group by in Django?
I just want to include ID(and other fields) as well in the result of an annotate with values (i.e group by). I'll explain with an example (below is just an example, please suspend your disbelief on this bad model), class Book(models.Model): name = models.CharField() version = models.IntegerField() # Assming its just a number that increments when each version is published like 1...2...3 and so on. published_on = models.DateTimeField() author = models.ForeignKey(User) class Text(models.Model): book_text = models.ForeignKey(Book) What I want is the Max version(or editions) of a Book, which I achieve by Book.objects.values('name', 'author').annotate(Max('version')) **Generated SQL (MYSQL) query**: SELECT "name", "author", Max("version") AS "version__max" FROM "book" GROUP BY "name", "author" But the above result does not contain ID or published_on if I add them to values it groups by them as well, which is not what I want. I want to group by only name and author, But want other fields or at least get an ID. Expected SQL: SELECT "id", "published_on", "name", "author", Max("version") AS "version__max" FROM "book" GROUP BY "name", "author"