Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django project not send data to database
I'm trying to create a register and login system in the Django framework, but there some problem with sending the data to the database, I have been checked the internet for any solution but I don't found the problem in the code !! -
I have models.py file. I am not sure how to write test for it? What to test? Can anyone please help and write test for it? #django #python
How to write tests for models.py file? from django.db import models from django.conf import settings from django.utils import timezone from django.contrib.auth.models import User class Profile(models.Model): #new user = models.OneToOneField(User, on_delete=models.CASCADE) institute = models.CharField(max_length=200, null=True) department = models.CharField(max_length=200, null=True) def __str__(self): return 'Email:{} Department:{} Institute:{}'.format(self.user.email, self.institute, self.department) class Access(models.Model): user = models.ManyToManyField(User) endpoint = models.CharField( max_length=20, choices=( ('pubmed', 'pubmed'), ('foster', 'foster'), ('med_apps', 'med_apps'), ('mayerson_transcripts', 'mayerson_transcripts'), ('all', 'all') ), unique=True ) def __str__(self): return self.endpoint class Request(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) created_time = models.DateTimeField(default=timezone.now) url = models.CharField(max_length=1000) def start(self): self.created_time = timezone.now() self.save() def __str__(self): return 'url:{} time:{}'.format(self.url, self.created_time) Need to run the test in Visual Studio Code. Also, I have seen a lot of examples for writing tests, but again got confused. It seems like I need to work on basics. -
Django: Use block in multiple places?
This is the template I've written {% extends 'base.html' %} {% load static %} {% block body %} <div class="row hide-on-mobile" style="height: 100vh"> <div class="col-auto p-5"> <img src="{% static 'logo.svg' %}" class="mb-5 hide-on-mobile" style="height: 84px"/> {% block form %} {% endblock %} </div> <div class="col bg-brown p-5"> <div class="d-flex flex-column justify-content-between" style="height: 100%"> <h1 class="text-blue mb-3">It's always Ups<br>and Downs</h1> <img src="{% static 'investing_illustration.svg' %}" class="auth-illustration"/> </div> </div> </div> <div class="hide-on-desktop" style="height: 100vh; position: relative"> <div class="d-flex flex-column bg-brown h-100 p-3 align-items-start"> <img src="{% static 'logo.svg' %}" class="mb-3 hide-on-desktop" style="height: 56px"/> <p class="text-blue mb-3">It's always Ups<br>and Downs</p> <img src="{% static 'investing_illustration.svg' %}" class="auth-illustration"/> </div> <div style="position: absolute; bottom: 0; z-index: 99; background: white; width: 100%"> <div class="d-flex flex-column p-4"> <p class="mb-4">Login</p> {% block form %} {% endblock %} </div> </div> </div> {% endblock %} The form block is used two times..because when I inherit the template I want to write only once..but display it in two different places in the same page. In this case, I've written different layouts for mobile and desktop show the user actually sees only once. However, this code doesn't work and gives the following error: django.template.exceptions.TemplateSyntaxError: 'block' tag with name 'form' appears more than once How … -
How to return 2 models in django
I have 2 models that I want to render to my html code and I tried doing this: form = CreateNewList() empName = employeeName.objects.all return render(response, "main/home.html", {"form":form}, {"empName":empName}) but it does not work. Is there a way to do this? -
Django Postgres JSONB and using a JSONB index
So we have a value stored in a JSONB column which I need to query on. I created an index for it like so create index user_notification_policy_id on user_notification using btree (((extra->'policy_id')::int8)); The explain plan is using the index if the query is formatted as so ("user_notification"."extra" -> 'policy_id')::text = '12345678'); How can I get Django to create a where clause like that? I've been trying to use extra but without luck return self.extra( where='("extra"->"policy_id")::int8 = %s', params=[policy_id] ) results in E ValueError: unsupported format character ')' (0x29) at index 1061 Django 2.2.16 -
django rest framework recursive models endpoints structure
I have three models like this (Simplified). class Locker(CoreModel): def __str__(self): return self.name topic = models.CharField( verbose_name=_('topic'), help_text=_("locker description"), null=True, max_length=1024 ) name = models.CharField( verbose_name=_('name'), help_text=_("locker name"), max_length=100, validators=( MinLengthValidator(2), ) ) owner = models.ForeignKey( to=settings.AUTH_USER_MODEL, related_name='owned_locker_set', verbose_name=_('owner'), on_delete=models.CASCADE ) class Folder(CoreModel): def __str__(self): return self.name name = models.CharField( verbose_name=_('name'), help_text=_('name of the folder'), max_length=256 ) parent = models.ForeignKey( to='self', verbose_name=_('parent'), on_delete=models.CASCADE, null=True ) locker = models.ForeignKey( to='lockers.Locker', verbose_name=_('locker'), on_delete=models.CASCADE, editable=False ) class Upload(CoreModel): def __str__(self): return self.name name = models.CharField( verbose_name=_('name'), help_text=_("upload name"), max_length=100, validators=( MinLengthValidator(2), ) ) locker = models.ForeignKey( to='lockers.Locker', verbose_name=_('locker'), on_delete=models.CASCADE, editable=False ) parent = models.ForeignKey( to='lockers.Folder', verbose_name=_('folder'), on_delete=models.CASCADE, null=True ) file = PrivateFileField( verbose_name=_('file'), help_text=_("raw file"), upload_to='uploads/', storage=private_storage ) as you can see, the structure is recursive. Ideally, from the frontend, I would want to make a single request to return all the files and folders the locker has at the root level (parent is None). Then, I would also like to make requests to get all the files and folders inside of a specified folder ( when the user opens a folder at the frontend). I am using Django Rest Framework right now. However, I cannot think of a way to achieve this … -
How to run Django with SAP HANA as database?
I would like to use SAP HANA as a database for my Django project. But unable to find a good document on how to connect Django and SAP HANA. Please suggest your opinion on this. Thank in advance :-) -
How can i get the average value of datas which is collected from endnode?
Hi everyone i am working on a project which is concerns endnode(sensor), IoT UI, and db simply. I'll try to summarize it. I have some endnodes which are supply some datas for me (temperature, humidity etc.) and i am showing them on and user-interface which is developed by django framework. Datas are collected for every 4 minutes(approximately). I want to show the daily average datas (for last 5 days) in my UI at the end of the day. I will show you my codes and my results following; models.py class DailySicaklikNemData(models.Model): endnode = models.ForeignKey(EndNode, on_delete=models.PROTECT, db_constraint=False) devEUI = models.CharField(verbose_name="Device EUI", max_length=255) company = models.ForeignKey(Company, on_delete=models.PROTECT, db_constraint=False) iaq = models.CharField(verbose_name="iaq", max_length=255) quality_condition = models.CharField(verbose_name="Quality Condition", max_length=255) date = models.DateField(verbose_name="Lora Data Send Time", default=datetime.now,blank=False) def __str__(self): return self.endnode.name class Meta: db_table = "temp_hum_daily_data" verbose_name = "Temp-Hum" verbose_name_plural = "Temp-Hum" ordering = ['-id'] views.py def sicaklikNemEndNode(request, devEUI): user = CheckUser(request) if user == 'none': return redirect('/user/login/') user_device = request.user_agent endnode = get_object_or_404(EndNode, devEUI=devEUI) data = getSicaklikNemEndNodeValue(endnode) dailyiaqdatas = DailySicaklikNemData.objects.filter(endnode=endnode).values('date', 'quality_condition').order_by('-date').annotate(iaq=Avg('iaq'))[:5] weather = getWeather(request) return render(request, "monitoring/sicaklik_nem_endnode.html", {'endnode': endnode, 'data': data, 'weather': weather, 'dailyiaqdatas': dailyiaqdatas, 'user_device': user_device}) and lastly html <div class="d-flex flex-row"> {% for data in dailyiaqdatas %} <div class="col text-center mt-3"> <p … -
Getting Mysql Connection Error with docker compose
I am trying to setup my development env using docker & docker compose.I am using Django with Mysql & phpymyadmin.Whener I run docker-compose up command my mysql & phpmyadmin images setups properly but my Django app fails & throws this error, django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '192.168.1.221' (115)") Here is my yaml file. version: '3.1' services: db: image: mysql restart: always environment: MYSQL_HOST: localhost MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: test MYSQL_ROOT_HOST: '%' ports: - "3308:3306" phpmyadmin: image: phpmyadmin/phpmyadmin:latest restart: always environment: PMA_HOST: db PMA_USER: root PMA_PASSWORD: root ports: - "8080:80" web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver" container_name: demo volumes: - .:/data ports: - "8000:8000" depends_on: - db networks: base: Here is my Dockerfile for django app. # Dockerfile FROM python:3.8 # install nginx RUN apt-get update && apt-get install nginx vim -y --no-install-recommends RUN pip install mysql-connector COPY nginx.default /etc/nginx/sites-available/default # RUN ln -sf /dev/stdout /var/log/nginx/access.log \ # && ln -sf /dev/stderr /var/log/nginx/error.log # The enviroment variable ensures that the python output is set straight # to the terminal with out buffering it first ENV PYTHONUNBUFFERED 1 # create root directory for our project in the container RUN … -
What is the difference between request.POST.get and request.GET.get in django
What is the difference between request.POST.get and request.GET.get in Django. I understand that when you use request.POST.get, you are trying to get data from front-end. In what situations will you require request.GET.get -
How to concatenate inputs of two charfields and store the result in another model in django?
This is my models.py.Here I want to create a username field such that it is concatenation of first name and registration ID of the users For Example: If, FirstName = Harry RegistrationID = 32pzc12 Then, Username=Harry_32pzc12 class User(models.Model): FirstName = models.CharField(max_length=20) LastName = models.CharField(max_length=20) RegistrationID = models.CharField(max_length=6) EmailID = models.EmailField(primary_key=True) Password = models.CharField(max_length=200) ProfilePicture = models.ImageField() MobileNumber = models.CharField(max_length=10) DateOfBirth = models.DateField() UserType = models.CharField(max_length=10,choices=UserTypeOptions) Description = models.TextField() -
How to replicate an entry in /etc/hosts file in Django/Heroku application? [duplicate]
I have a web URL which I can access only after I have added an entry into the /etc/hosts file which was <IP> <URL> But now I want to replicate the same thing in an online django application on heroku. How do I replicate this with code, either some library on python or some procedure on heroku? -
Django: Pass an url id to another url
I'm newer for Django. I'm trying to pass a id from 1st url to 2nd ur. In the list, the url has already have a id named order_id, I want to use this order_id to open another url to create a new content with this id. path('list-ordercontent/<order_id>', OrdercontentListView.as_view(), name='list-ordercontent'), path('create-ordercontent/<order_id>', create_ordercontent, name='create-ordercontent'), view.py class OrdercontentListView(ListView): model = Ordercontent template_name = 'store/list_ordercontent.html' context_object_name = 'ordercontent' def get_queryset(self): model = Ordercontent order = self.request.resolver_match.kwargs['order_id'] return model.objects.filter(order=order) in list-ordercontent.html, I tried to use same order_id to pass the variable I wanted, but it' incorrect. I want to know how to use the order_id into the another url, in my program it's the url for creating. <a href="{% url 'create-ordercontent' order_id %}">Add Product</a> -
How use Exists in Django 2.2
How to use or Exists in DJANGO 2.2 select distinct pcode as papercode, pname, from pap p inner join change syl on syl.syllabusyr=p.year where syl.admnyr='2021' and (pcode like '"HIN2"%' or exists(select * from paper_dep_maps where pcode =p.pcode and course_id='HIN' and paper_dep_maps.pcode like'___2%')) -
Django admin template overriding not working on hosting
In general, I have such a structure project |project/ |myapp/ |templates/ |admin/ |myapp/ |change_form.html in the html file this code {% extends "admin/change_form.html" %} {% block field_sets %} {# your modification here #} {% endblock %} everything is fine on the local server but when uploaded to the hosting, there are no changes. What is the problem ? -
How can i filter parent data on the basis of children data using django rest frameworks?
Suppose I've two models called A, B Eg: class A(models.Model): ............ ............ class B(models.Model): a = models.ForeignKey(A, ............) ............ Now I want to create filterset so that i can filter data from model A using on the basis of model B objects informations, I'm trying to achieve some thing like this but it is only working for field available in model A, Here is code snippets class ProductFilterSet(filters.FilterSet): min_price = filters.NumberFilter(field_name="price", lookup_expr='gte') max_price = filters.NumberFilter(field_name="price", lookup_expr='gte') category = filters.ModelMultipleChoiceFilter(queryset=Category.objects.all()) company = filters.ModelMultipleChoiceFilter(queryset=Company.objects.all()) size = filters.ModelMultipleChoiceFilter(queryset=VariationSize.objects.all()) class Meta: model = Product fields = ['category', 'min_price', 'max_price', 'company', 'size'] It is working fine for min_price, max_price, category and company, But I'm getting invalid name in case of size because size field is only exists in model B. Here is screenshot snippets -
How to use model Field name in foreign key attribute limit_choice_to
I have 3 Models 1.CustomUser 2.ABC 3.XYZ CustomUser Model is an extended User Model. ABC Model class ABC(models.Model): class_name = models.CharField(max_length=255) profile_id = models.ForeignKey(CustomUser) class XYZ(models.Model): # This profile_id field is for knowing which user has created the following data profile_id = models.ForeignKey(CustomUser) processor = models.ForeignKey(ABC, limit_choices_to = {"profile_id": profile_id}) I want to add data in XYZ Model based on the profile_id field. The user who has created data in ABC Model can only add data in the XYZ model. Suppose User A didn't add data in ABC Model. but trying to add data in XYZ Model. If there is no instance of USer A in model ABC it should give validation error through Model only. I want to do this validation at Model Level. That's why I am using limit_choices_to. Thanks in Advance. If my question is not understandable. Please let me know -
How to add data from django database to autocomplete?
I am new to web development and I found this HTML code online that creates a dropdown input. I want to change the array that contains for all the countries to the names inside my database. this is the html that contains all the countries: var countries = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central Arfrican Republic","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cuba","Curacao","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Myanmar","Namibia","Nauro","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","North Korea","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre & Miquelon","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","St Kitts & Nevis","St Lucia","St Vincent","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad & Tobago","Tunisia","Turkey","Turkmenistan","Turks & Caicos","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States of America","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"]; models.py: class employeeName(models.Model): employee = models.CharField(max_length=200) total_Hours_Worked = models.CharField(max_length=8, default="Empty") def __str__(self): return self.employee views.py def dropdown(response): form = employeeName() return render(response, "main/dropdown.html", {"form":form}) How do I insert the employee names into the countries array? -
Django ModelAdmin autocomplete_fields
I did not use the admin.py but can I use the autocomplete fields in the frontend like a webshop search field? regards Christopher. -
form submission not working when trying to send an email in Django
I have created a simple system to keep patient records. I have added a patient to the system and now i have created a view to retrieve patient name and email address from the system (GET method) and is working. The challenge is sending an email to the selected patient using the patient's registered email address with some additional information that is Subject and Body of the email from a form on form submission (POST method) is not working. the form is not being submitted. I have send some emails before using the same EmailForm from forms.py in a different view and is working. here is my views.py def send_client_mail(request, pk): patient = Patient.objects.get(id=pk) address = patient.email if request.method == "POST": form= EmailForm(request.POST) if form.is_valid(): name = form.cleaned_data.get('subject') address = address message = form.cleaned_data.get('email_body') send_mail( name, message, 'myemailaddress@gmail.com', [address, ], fail_silently=False) messages.info(request, 'Email was sent successfully !!') else: form = EmailForm(None) return render(request, 'client_email.html', {'title': 'send email to ', 'form': form, 'patients': patient) here is my forms.py class EmailForm(forms.Form): subject = forms.CharField(required=False, label='Email subject', widget=forms.TextInput(attrs={'size':'40', 'style':'font-size:medium'})) email_address = forms.CharField(required=False, label='Recepient Email Address', widget=forms.TextInput(attrs={'size':'40', 'style':'font-size:medium'})) email_body = forms.CharField(required=False, label='Email body/message', widget=forms.Textarea(attrs={'size':'10', 'style':'font-size:medium;', 'rows' :4})) def clean_subject(self): subject = self.cleaned_data.get('subject') if subject … -
NoReverseMatch Reverse for 'ux' not found. 'ux' is not a valid view function or pattern name
I am getting below error only when i am trying to access the website via domain name. When i access my website using ip address (by running python manage.py runserver) it doesn't throw an exception. Please check using below: https://adhocdevices.com/ Please help me in resolving this issue. My urls.py is as below: path('category/<int:pk>/',views.CategoryShow), path('about/',views.about,name='about'), path('contact/',views.contact,name='contact'), path('product/',views.product,name='product'), path('ux/',views.ux,name='ux'), path('webservices/',views.webservices,name='webservices'), path('iotdevices/',views.iotdevices,name='iotdevices'), path('digitaloceanhosting/',views.digitaloceanhosting,name='digitaloceanhosting'), path('devops/',views.devops,name='devops'), path('dataanalytics/',views.dataanalytics,name='dataanalytics'), path('chatmessanger/',views.chatmessanger,name='chatmessanger'), path('azurecloudsupport/',views.azurecloudsupport,name='azurecloudsupport'), -
Making Django admin and using rest API for data accessing and posting , front end using html css
I'm pretty confused and making and making new admin thing from the start using start bootstrap admin template but how do I authenticate the admin login on my admin model with session and cookies record and everything using rest api Any help will be appreciated? -
I implemented a star rating system for delivery man in django by users but i am stuck at how to calculate the average
I have a model name Ratings and its connected to custom user model through foreignkey relationship.i used javascript to post data and get ratings in the backend by get method using id but the problem is rating process works fine but it just upgrades the current queryset when ever regarded delivery man gets rated. so how do i calculatye the average as it does not store the previous querysets rather its just upgrades the queryset of that particular deliveryman views.py def rate_user(request): if request.method == 'POST': el_id = request.POST.get('el_id') val = request.POST.get('val') print(val) obj = Ratings.objects.get(id=el_id) obj.rated_number = val obj.save() return JsonResponse({'success':'true', 'score': val}, safe=False) return JsonResponse({'success':'false'}) models.py class Ratings(models.Model): rated_user = models.ForeignKey(User,on_delete=models.CASCADE,blank=True,null=True) avg_rating = models.CharField(max_length=5,null=True,blank=True,default=0) # count = models.CharField(max_length=100000,blank=True,null=True,default=0) rated_number = models.IntegerField(blank=True,null=True,default=0, validators = [ MaxValueValidator(5), MinValueValidator(1), ] ) def __str__(self): return str(self.pk) @receiver(post_save, sender=User) def create_ratings(sender, instance, created, **kwargs): if created: if instance.is_delivery_man or instance.is_driver: Ratings.objects.create(rated_user=instance) js <script> const one = document.getElementById('first') const two = document.getElementById('second') const three = document.getElementById('third') const four = document.getElementById('fourth') const five = document.getElementById('fifth') // get the form, confirm-box and csrf token const form = document.querySelector('.rate-form') const confirmBox = document.getElementById('confirm-box') const csrf = document.getElementsByName('csrfmiddlewaretoken') const handleStarSelect = (size) => { const children = form.children … -
Multiple Models and Forms in Django Class Based View
Is it possible to have multiple forms and retrieve data from four models in one Django class based view? For example we are creating a booking app and on the Admin management page we want the page to be able to show: Data from four separate models Allow editing of the data (e.g. update / delete) Adding of new records (Post - Only from one form at a time) Here is an example of what I have tried. If I include both functions get_context_data they overwrite one before. Thanks in advance for anyone that can help me with this, still fairly new to Django. # ADMIN PAGE VIEWS. class ASPAdminListView(ListView): # creates a context dictionary to return a named list of asp_bookings. context_object_name = 'asp_bookings' model = ASPBookings template_name = "vistours/admin_bookings.html" # creates another dictionary to retun the BFBWBookings data. def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['bfbw_bookings'] = BFBWBookings.objects.all() return context # creates another dictionary to retun the Athlete data. def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet … -
django-Preview the photo after selecting the file in Django
models.py class Banner(models.Model): banner_photo = models.ImageField(null=True, blank=True) As the answer below, I would like to preview the image selection before saving the banner image in django-admin. I am a beginner about HTml. How do I override it? I want to preview the banner picture to be registered with Admin like the captured image. I don't know how to apply it even if I see the answer. onchange file input change img src and change image color