Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't describe POST request with BaseHandler
sorry for my bad english get request works fine, the data is displayed correctly, but it's not possible to add new data, it shows a server error status 500 Class Test(models.Model): id = models.AutoField(u'id', primary_key=True) name = models.CharField(u'name', max_length=255, null=True) class Meta: db_table = u'test' verbose_name = u'test' verbose_name_plural = u'tests' Class TestHandler(baseHandler): def read(self, request, id=None): return self.model.object.all() enter image description here def create(self, request, id=None): f=Test(request.POST) new=f.save() return new POST http://127.0.0.1:8000/test/ 500 (INTERNAL SERVER ERROR) I tried this, but it doesn't work either: def create(self, request, id=None): new_test = SmartCheckpointVideo( id=request.POST['id'], name=request.POST['name'] ) new_test.save() return new_test and this def create(self, request, id=None): new_test = SmartCheckpointVideo( name=request.POST['name'] ) new_test.save() return new_test I don't understand how to work with BaseHandler, if there is detailed documentation, please share it -
DRF: many=True causes array instead of returning a regular object
I'm using a nested serializer to access the facility address of each facility. The only way the values will actually show is when i add many=true to the "LeadFacilityDetailFacilitySerializer". But the issue is that it will add [] around my address object. Which leads to "undefined" whjen i try to access the items inside my address object: {info.LeadFacilityDetailFacility.AddressInfo.City} serializers.py class LeadAddressSerializer(serializers.ModelSerializer): class Meta: model = FacilityAddress fields = ( "PrimaryAddress", "SecondaryAddress", "City", "RegionOrState", "PostalCode", ) class LeadFacilityDetailFacilitySerializer(serializers.ModelSerializer): AddressInfo = LeadAddressSerializer(source="fa", many=True) class Meta: model = Facility fields = ('mainimage', 'Name', 'AdministratorCell', 'AddressInfo') class LeadFacilityDetailSerializer(serializers.ModelSerializer): LeadFacilityDetailFacility = LeadFacilityDetailFacilitySerializer(source="assigned_facilities") class Meta: model = LeadFacilityAssign fields = ('assigned_facilities', 'datetime', 'id', 'LeadFacilityDetailFacility') models.py class FacilityAddress(models.Model): PrimaryAddress = models.CharField(max_length=150, null=True, blank=True) SecondaryAddress = models.CharField(max_length=150, null=True, blank=True) City = models.CharField(max_length=150, null=True, blank=True) RegionOrState = models.CharField(max_length=50, null=True, blank=True) PostalCode = models.CharField(max_length=30, null=True, blank=True) Geolocation = models.CharField(max_length=30, null=True, blank=True) AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa') class Facility(models.Model): Name = models.CharField(max_length=150, null=True, blank=False) -
Calling the list created using getlist on the form
In my Django project, I save the data in a field that I have made multiple selections to the database using the getlist function and the POST method. Then I pull this data from the database and print it on an html form, but I cannot access the list data properly unless I split it here. views.py def record_form(request): if request.method == "POST" and 'registrationSave' in request.POST: records = Records() records.medications = request.POST.getlist('medications') records.scale_used = request.POST.getlist('scale_used') records.save() return redirect('/index/tables') def editRecords(request,id): edit_records = Records.objects.get(id=id) if edit_records.medications is not None: edit_records.medications = edit_records.medications.split(",") if edit_records.scale_used is not None: edit_records.scale_used = edit_records.scale_used.split(",") institutionName = Institution.objects.all() medicationName = MedicationName.objects.all() return render(request,"update_record.html",{"Records": edit_records, "institutionName":institutionName,"medicationName":medicationName}) update.html <div class="col-4"> {% for medication in Records.medications%} <div class="mb-3 col"> <label for="">İlaç Adı:</label> <select class="form-select" name="medications" id="medications"> <option {% if medication == '{{medicationName.medicationName}}' %} selected {%endif%}>{{medication}}</option> {% if medicationName%} <p>{{medicationName}}</p> {% for medicationName in medicationName %} <option value="{{medicationName.medicationName}}">{{medicationName.medicationName}}</option> {%endfor%} {%endif%} </select> </div> {%endfor%} </div> I'm sharing my code pieces above with you, and I'm leaving the screenshot of the update.html page below. How can I follow a method to avoid [ ] and ' ' signs? enter image description here Thank you in advance for your help -
Does a function based view in Django returning JSON response considered RESTful?
A function based view in Django which authenticates the user based on the sessionid and requests using X-CSRFToken(for POST calls) which returns data in JSON is considered RESTFul? I am currently not using djangorestframework for my project. -
Need Inline ManytoMany Field add in django admin
I am creating a manytomany field in my model and creating a Inline Tabular with though also. but on django admin it is showing dropdown. and if I add new then it shows a Popup. But I dont want Popup. Instead of that I want inline add as in case of Foreign Key. Thanks in advance. Please help... class ExamInline(admin.TabularInline): # classes = ['collapse'] model = Form.exam.through extra = 0 -
django-advanced-filters text contains not working
I would like to set a filter that gives me all items where "@test.com" is in the email. When setting up the filter, the field only allows me to select something from the autocomplete list of existing entries. Else it does not save. There is no possibility to add a custom string here. I am using python 3.10.4, django 3.0, django-advanced-filters 2.0.0 I tried to insert any different string but it would not save. I would expect the contains to allow for only a part of a string to compare and not to specify an existing string of the field that is already used. -
How to return choices tuple value in string format in django Admin panel
I've been trying to get tuple value from choices tuple of CharField() in Model to display in the Django Admin Panel row whenever a table is accessed I'm aware of the following answer... get_foo_display() but it returns the following error AttributeError: 'device_table' object has no attribute 'get_device_type_display' Here's the model: device_table(models.Model): device_type = ( ('AD' , 'Android'), ('IO' , 'iOS'), ('WD' , 'Windows'), ('MO' , 'MacOS'), ('LX' , 'Linux') ) user_device_type = models.CharField(choices = device_type, null = True, max_length=3) class Meta: verbose_name = ('Device Table') def __str__(self): return self.get_device_type_display() I'm running django 4.0.8 by the way -
Django -- connection to local postgresql to docker container
Hello everyone i try to connect local postgres db to the docker container in django project. as mention in this post it works on my local machine which is ubuntu 20.04 LTS but cannot run same project on ubuntu-server which is ubuntu 20.04 LTS. screenshots are give below pg_hba.conf postgres.conf Error in terminal this is my dockercompose file -
When using django's queryset union function, data in the queryset at the back may be lost
When using django's queryset union function, data in the queryset at the back may be lost. The structure of the model I used is as follows. class Genre(models.Model): name = models.CharField(max_length=50) class Top_Movie(models.Model): title = models.CharField(max_length=100) release_date = models.DateField() popularity = models.FloatField() vote_count = models.IntegerField() vote_average = models.FloatField() overview = models.TextField() poster_path = models.CharField(max_length=200) backdrop_path = models.CharField(max_length=200) genres = models.ManyToManyField(Genre, related_name="top_genre") year = models.IntegerField() ranking = models.IntegerField() class Now_Movie(models.Model): title = models.CharField(max_length=100) release_date = models.DateField() popularity = models.FloatField() vote_count = models.IntegerField() vote_average = models.FloatField() overview = models.TextField() poster_path = models.CharField(max_length=200) backdrop_path = models.CharField(null=True, max_length=200) genres = models.ManyToManyField(Genre, related_name="now_genre") year = models.IntegerField() ranking = models.IntegerField() Top_Movie.objects.all().union(Now_Movie.objects.all()) In the above situation, the genres field data of Now_Movie is lost. Now_Movie.objects.all().union(Top_Movie.objects.all()) In the above situation, genres field data loss of Top_Movie occurs. I don't know why this is happening. Please help. I solved the problem by not using union , but I want to know why this happened. My guess is that the ManyToManyField is causing something, but I don't know exactly why. -
Validation error ['clocked must be one off, one_off must set True']
I am trying to save periodic tasks using django_celery_beat package getting the above error, the code is as follows. Save uses post save signals class MailTask(models.Model): name = models.CharField(max_length=100, blank=True) subject = models.CharField(max_length=100) message = models.TextField() from_email = models.EmailField() recipient = models.EmailField() sent = models.BooleanField(default=False) time_to_send = models.DateTimeField() def schedule_mail_task(sender, instance, created, **kwargs): if created: clocked_schedule, created = ClockedSchedule.objects.get_or_create( clocked_time=instance.time_to_send, ) periodic_task = PeriodicTask.objects.create( clocked=clocked_schedule, name=f'instance.name+{instance.timestamp}', task='core.tasks.send_mail_func', enabled=True, ) post_save.connect(schedule_mail_task, sender=MailTask) -
How can I reach Django admin model stackedinlines in html tags?
I'm using stackedinline for for creating subtopic for each cancer type, in admin everything works fine, i can add subtopic for each type of cancer directly from cancer type creat/edit page, but I cant figure out how to display subtopic related to "parent" type in html template. P.S. I'm new in programming my models.py from django.db import models from ckeditor.fields import RichTextField class CancerType(models.Model): name = models.CharField(max_length=200, blank=False) image = models.ImageField(upload_to="static/assets/images/types") description = RichTextField(default="", blank=True, null=True) def __str__(self): return self.name class Meta: verbose_name = "Տեսակ" verbose_name_plural = "Տեսակներ" class SubTopic(models.Model): type = models.ForeignKey(CancerType, on_delete=models.CASCADE) title = models.CharField(max_length=200, blank=False) topic = RichTextField(blank=False, null=True) def __str__(self): return self.title class Meta: verbose_name = "Ենթաբաժին" verbose_name_plural = "Ենթաբաժիններ" admin.py rom django.contrib import admin from .models import CancerType, SubTopic admin.site.register(SubTopic) class SubTopicInline(admin.StackedInline): model = SubTopic extra = 0 class CancerTypeAdmin(admin.ModelAdmin): inlines = [SubTopicInline] admin.site.register(CancerType, CancerTypeAdmin) type.html {% extends 'base.html' %} {% load static %} {% block content %} <img src="{% url 'home' %}{{ cancertype.image }}"> <h4>{{ cancertype.name }}</h4> <br> {{ cancertype.description|safe }} <br> {% for subtopic in object_list %}} {% if subtopic.type %}} {{ subtopic.title }} <hr> {{ subtopic.body }} {% endif %} {% endfor %} {% endblock %} -
how to stop run path again to join whith same path in django
how can i stop this for example if i run http://127.0.0.1:7000/search_acctable/?txt=Kalpesh but if now i again run my code this is run like http://127.0.0.1:7000/search_acctable/?txt=Kalpesh/search_acctable/?txt=any in django how can i solve this i need help to solve this problem -
model for uploading and downloading file from specific category
I'm creating a website for uploading and downloading wallpapers but I'm not able to add the category field in the model and templates from where user can upload and download wallpaper from specific category. Can someone please suggest something. I'm creating a website for uploading and downloading wallpapers but I'm not able to add the category field in the model and templates from where user can upload and download wallpaper from specific category. Can someone please suggest something. -
Python cli.py execution stuck: Unable to figure out the source
I'm trying tto deploy the following Django-rest api on gcp ubuntu 22.0.4 using python 3.9. https://github.com/OkunaOrg/okuna-api The enter setup is supposed to be done and get setup using a single command : python3.9 okuna-cli.py up-full The execution seems stuck at "Waiting for server to come up..." and doesn't proceed ahead. The setup should complete by stating "Okuna is live at "domain". Another important aspect of the setup is the 5 docker containers are running and working fine when i run the py file. I'm even able to access the database after creating a superuser. The code is as follows : import random import time import click import subprocess import colorlog import logging import os.path from shutil import copyfile import json import atexit import os, errno import requests from halo import Halo handler = colorlog.StreamHandler() handler.setFormatter(colorlog.ColoredFormatter( '%(log_color)s%(name)s -> %(message)s')) logger = colorlog.getLogger('🤖') logger.addHandler(handler) logger.setLevel(level=logging.DEBUG) current_dir = os.path.dirname(__file__) KOSMOS_CLI_CONFIG_FILE = os.path.join(current_dir, '.okuna-cli.json') KOSMOS_CLI_CONFIG_FILE_TEMPLATE = os.path.join(current_dir, 'templates/.okuna-cli.json') LOCAL_API_ENV_FILE = os.path.join(current_dir, '.env') LOCAL_API_ENV_FILE_TEMPLATE = os.path.join(current_dir, 'templates/.env') DOCKER_COMPOSE_ENV_FILE = os.path.join(current_dir, '.docker-compose.env') DOCKER_COMPOSE_ENV_FILE_TEMPLATE = os.path.join(current_dir, 'templates/.docker-compose.env') REQUIREMENTS_TXT_FILE = os.path.join(current_dir, 'requirements.txt') DOCKER_API_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'api', 'requirements.txt') DOCKER_WORKER_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'worker', 'requirements.txt') DOCKER_SCHEDULER_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'scheduler', 'requirements.txt') DOCKER_API_TEST_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'api-test', 'requirements.txt') CONTEXT_SETTINGS = … -
Where to verify the settings during startup
After settings.py executes, I need to check to make sure all the settings were found from the .env variables, and error out if they are not. Where's the appropriate place to put that logic? Right in settings.py? manage.py? -
Custome route in django admin
I wanted to customize my django admin route Not from /admin to something else but to add new clickable custom route inside admin panel Currently I have created superuser using python manage.py createsuperuser command. I can login to django admin panel , but what I want is to have a custom route to be displayed in left sidebar or anywhere else after logging into django admin panel. My custom route is like localhost:8000/my-view/ and my-view should be displayed somewhere in admin panel. TIA. -
Want to make code for inactive or idle user time in Python when he did not show any movement on screen and keyboard and mouse through
I am student and I am making an app regarding tracking time activity. So please help me to give an solution. I am finding out from last 4 days regarding the hints or code . I got one solution of my friend . but i am confuse that how to use this. If i use this and store that time so how could i make an object and api so i can display this time in frontend side. import sys if sys.platform == 'win32': from ctypes import * class LASTINPUTINFO(Structure): _fields_ = [ ('cbSize', c_uint), ('dwTime', c_int), ] def get_idle_duration(): lastInputInfo = LASTINPUTINFO() lastInputInfo.cbSize = sizeof(lastInputInfo) if windll.user32.GetLastInputInfo(byref(lastInputInfo)): millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime return millis / 1000.0 else: return 0 else: def get_idle_duration(): return 0 if __name__ == '__main__': import time while True: duration = get_idle_duration() print('User idle for %.2f seconds.' % duration) time.sleep(0.5) I am expecting that please help me to solve my solution. I am student and I am learning this. I am expecting an output like total idle time of computer is 1 hr or 2 hr . I already made code for tracking time for task/project time. -
I cannot install Django, And give "Installation failled"
I want to install Django,But when I run pipenv install django it create virtual environment and then give Installation Failed. Before try below codes I run pip install django to install Django. And there is no issue with internet connection. How do I fix this? I tried pip install django , pipenv install django -
django.urls.base.get_script_prefix() returns incorrect prefix when executed by apache
Python-3.8/Django-3.2/Mezzanine-6.0 application tries to access incorrect pages when executed by apache. In standalone mode (python manage.py runserver) it creates correct address /admin/page_types/basicpage/2677/change/ whereas in apache mode it creates address /admin/page_types/basi/admin/pages/page/2677/change/ in the same place. It seems to be the get_script_prefix() function in django/urls/base.py that returns incorrect prefix when accessing page 2677 in apache mode. Also it seems to be running the same main thread all the time in apache mode. Could it be the main reason ? Apache configuration: [django@tkpika03p ~]$ cat /etc/httpd/conf.d/pika.conf # # VirtualHost template # Files must have the .conf suffix to be loaded. # # NameVirtualHost statements can be added to /etc/apache2/listen.conf. # # Almost any Apache directive may go into a VirtualHost container. # The first VirtualHost section is used for requests without a known # server name. # <VirtualHost *:80> ServerAdmin palvelin.hallinta@<myDomain> ServerName pikaappm.<myDomain> ServerAlias tkpika03p.ad.<myDomain> # TODO: Missä tilanteissa tänne päädytään? Jos ei löydy wsgi/django # : takaa, palautetaan 404 ja haetaan toiselta serveriltä # : Teoriassa täältä ei siis lueta mitään? DocumentRoot /srv/www/htdocs # if not specified, the global error log is used ErrorLog /var/log/httpd/pika-error_log CustomLog /var/log/httpd/pika-access_log combined # TODO: Vaihdettava debug -> warn -> info, kun kaikki toimii LogLevel warn # … -
How to fix too much time taken by python requests during get and post?
There is one website written in CakePhp and I am moving to Django. Some pages are making get/post request to another website to collect some information. CakePhp $socket = new HttpSocket(); $api_ret = $socket->get($url,$data,$this->header); Django import requests api_ret = requests.get(url,data,headers=self.header) Time taken by requests is too long compare to CakePhp. Is there anything I am doing wrong or Is there any other library that I can use ? Please Help. -
profile page of username 'admin' giving 404 error
My website is acting very weird for some reason. I have a profile page that displays information about an user. it takes username in url and pass it to view. It's working perfectly fine for all users, except for the super user 'admin'. For example, let's say there's an user with an username 'user01'. .../account/user01 will display profile page of 'user01'. But for some reason, .../account/admin leads to 404 error, and it specifies that it tried all urlpatterns including account/<str:username> [name='profile']. What makes this weirder is, when I do the exact same thing in incognito mode, .../account/admin works. Below are relevant codes: account/views.py def profile(request, username): try: user = User.objects.get(username=username) except User.DoesNotExist: raise Http404("User Does Not Exist!") return render(request, 'account/profile.html', {'user': user}) account/urls.py app_name = 'account' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='account/login.html'), name='login'), path('signup/', views.signup, name='signup'), path('<str:username>', views.profile, name='profile'), ] -
Django migrations create object have foreign key
I have Three table one country, state and city. ` class Country(BaseModel): name = models.CharField(max_length=128) code = models.CharField(max_length=2, unique=True) isd_code = models.CharField(max_length=8) class State(BaseModel): country = models.ForeignKey("geo.Country", on_delete=models.CASCADE) name = models.CharField(max_length=256) code = models.PositiveIntegerField(blank=True, null=True) class City(BaseModel): name = models.CharField(max_length=128) country = models.ForeignKey("geo,Country", on_delete=models.CASCADE) state = models.ForeignKey("geo.State", on_delete=models.CASCADE) I have crete objecte throw migration country and state. def import_legacy_countries(apps, schema): Country = apps.get_model('geo', 'Country') for country in Country.objects.all(): country.delete() with open('legacy_data/CountryDetails.csv', mode='r') as file: # reading the CSV file csvFile = csv.reader(file) # displaying the contents of the CSV file for row in csvFile: Country.objects.create( name=row[1], code=row[2] ) def import_legacy_states(apps, schema): Country = apps.get_model('geo', 'Country') State = apps.get_model('geo', 'State') country_cache = {} missing_country_codes = [] non_unique_country_codes = [] with open('legacy_data/State.csv', mode='r') as file: # reading the CSV file csvFile = csv.reader(file) # displaying the contents of the CSV file for row in csvFile: country_code = row[1] if country_code in country_cache: country = country_cache[country_code] else: try: country = Country.objects.get(code=country_code) country_cache[country_code] = country except Country.DoesNotExist: missing_country_codes.append(country_code) except Country.MultipleObjectsReturned: non_unique_country_codes.append(country_code) State.objects.create( name=row[3], country=country ) if len(missing_country_codes) + len(non_unique_country_codes): print('Missing:') pprint(missing_country_codes) print('Non Unique:') pprint(non_unique_country_codes) raise Exception('Missing or non unique country present...') ` Now i want to add all country and state data to city … -
To create a big web app using django, what all things I should learn?
I am an intermediate django developer and I would like to more deeper concepts of django that would help me optimize queries, add mode functionalities to the app(I am a back end dev btw). I know basics of django like model designing, views, drf etc..I need more in-depth knowledge -
Heroku DNS, through cloudlfare not connecting to my domain name
Including the pictures down below, I have my code running and working perfectly fine on the website heroku generated for me, so i got a free website on freenom and sent the nameservers generated from cloudflare, and it just shows as an error on the website any ideas? Heroku CloudFlare I tried messing around with the name servers, and it just never happened to work -
How to post data to different model in django restframework
i am new to restframework .i am trying to save my post data to different model.i have no ideal how to do it or is it possible. views.py class AllAPIView(APIView): def get(self,request,*args,**kwargs): task = Task.objects.all() taskserializer = TaskSerializer(task, many=True) event = Event.objects.all() eventserializer = EventSerializer(event, many=True) context = [taskserializer.data,eventserializer.data] return Response(context) def post(self,request): taskserializer = TaskSerializer(data = request.data) eventserializer = EventSerializer(data = request.data) if taskserializer.is_valid(): taskserializer.save() return Response(taskserializer.data, status=status.HTTP_201_CREATED) if eventserializer.is_valid(): eventserializer.save() return Response(taskserializer.data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) i am trying to do to this in a single path ,how can i differentiate my data while request? i tried by putting 2 serializer into the post function but it only save to the 1st serializer