Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What web technology to be used to develop an interactive web app for the Energy Hub model?
I need recommendations regarding the technology to be used in a web app. What the app is about and what I am looking for are described in detail here. I understand that this question is better suited to be asked on https://softwarerecs.stackexchange.com, which is where the link above leads to. Since the StackOverflow community is larger, I felt a need to post it here as well. If this violates any of the community guidelines, feel free to take it down. Please help me out. Mentioning good learning material/tutorials for what you suggest would be a cherry on top. Thanks. -
Django model edit page creates new model instead of editing the current one
I just deployed my first Django app, which is for the small company I work for to track jobs, expenses, and it has a blog for customers to see. After I deployed the site, I realized the page to edit the job model did not show the job's information but a blank form for a new instance. When the edit is submitted it creates a new instance instead of changing the current job that's meant to be edited. Editing works just fine through the admin dashboard, but I just can't figure out why the edit page won't work. I tried tweaking the view function for editing the job, deleting migrations and the database, and re-migrating, all to no avail. views.py def job_edit(request, pk): if request.user.is_authenticated: job = get_object_or_404(Job, pk=pk) if request.method == "POST": form = JobForm(request.POST, request.FILES) if form.is_valid(): job = form.save(commit=False) job.author = request.user job.last_updated = timezone.now() job.image0 = form.cleaned_data['image0'] job.image1 = form.cleaned_data['image1'] job.image2 = form.cleaned_data['image2'] job.image3 = form.cleaned_data['image3'] job.save() messages.success(request, 'Job updated successfully') return redirect('job_detail', pk=job.pk) else: form = JobForm() return render(request, 'job_edit.html', {'form': form}) else: return render(request, 'job_edit.html') forms.py class JobForm(forms.ModelForm): foreman = forms.ChoiceField(choices=FOREMEN, required=True) status = forms.ChoiceField(choices=JOB_STATUS, required=True) zip = forms.IntegerField(validators=[MinValueValidator(00000), MaxValueValidator(99999)]) class Meta: model = … -
How can I structure Django permissions to have multiple categories of permissions groups?
I'd like to have multiples layers of permissions for an API using Django Rest Framework, how can I best achieve this? Specifically the three categories of authorization I have are: Roles: Model level access, such as admin and different customer types. GroupAccess: Per object, group access such as a team of users. Sensitivities: Per object, additional tags for sensitive information. The second two categories apply equally across all models and it would be nice to not need separate permissions for each model. Idea 1: Create a model for each category inheriting from the standard django auth group. Doing these as proxy groups, to be logically different in my code, but as consistent with standard authorization as possible. Then use django-guardian to enable the object level permissions. Idea 2: Use the standard groups for roles and assign model level permissions based on these groups. For the object level permissions write a custom permission classes in Django Rest Framework to check the object level permissions against the user. -
What does base_name do in Django?
router.register(r'my-model/', MyModelView, base_name='MyModel') I don't understand what the base_name is for in the code above. I've read the Django doc: https://www.django-rest-framework.org/api-guide/routers/, and other Stackoverflow questions. But I still don't understand. -
Converting to Django Channels 2.0 how to serve static pages from runserver
Channels 1.0 I was able to serve my http pages in development runserver using: urlpatterns += ( url(r'^$', static_views.serve, kwargs={'path': 'app/index.html'}), ) What would be analogous to this in 2.0? I assume I'd have to override the "http" in my ProtocolTypeRouter, but unclear how to make that happen. -
How to save with django model form multiple data into one table?
I have a model to save the reservation data with a form model and it works very well but only for one person. I would like that when the number of people exceeds a person the form asks the same data for the following people in the same form with the same model (Table). I have tried to create multiple model to save data depending the number of people but it's not what I want because I want to do this with one model I mean one table from the database. This is my model: class BusTicket(models.Model): ''' Class to define a bus ticket ''' vip_types = ( ('Yes', 'Yes'), ('No', 'No'), ) #each indivitual status PENDING = 'Pending' CONFIRMED = 'Confrimed' TICKET_STATUSES = ((PENDING,'Pending'), (CONFIRMED,'Confrimed'), ) vip_booking = models.CharField(max_length=60, choices=vip_types, default="No") gender = models.CharField(max_length=15, choices=gender_choices) first_name = models.CharField(max_length = 255) last_name = models.CharField(max_length = 255) email = models.EmailField(max_length = 254) active = models.BooleanField(default=True) update = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) bus_id = models.ForeignKey(BusTravels, on_delete=models.CASCADE, blank=True, null=True) phone_number = PhoneNumberField() def __str__(self): return self.first_name + ' ' + self.last_name + ' ' + str(self.phone_number) -
Django OneToOneField allow online one reference
I am trying to create a one to one reference and want to make sure that that reference is not allowed to be used for another model or instance. For example Say I have an address model, Person Model and Company Model Person has a OneToOneField field to Address Company also has a OneToOneField field to Address address=Address(data="some address") company=Company(name="some company",address=address) person=Person(name="my name",address=address) Models: class Address(models.Model): data = models.CharField(max_length=255, blank=True, null=True) class Company(models.Model): name = models.CharField(max_length=255, blank=True, null=True) address=models.OneToOneField(Address,on_delete=models.CASCADE) class Person(models.Model): name = models.CharField(max_length=255, blank=True, null=True) address=models.OneToOneField(Address,on_delete=models.CASCADE) I would like the system to throw an error on this since I am setting the same address to 2 different models. Also this would delete both person and company if I delete address. Usually you catch this with code and not make a stupid mistake like this. But can system catch it since it is one to one ? -
Django bootstrap4 - Parameter "form" should contain a valid Django Form
I am getting the following Bootstrap exception 'Parameter "form" should contain a valid Django Form.' when running the following code from this tutorial: {% load bootstrap4 %} <form action="/url/to/submit/" method="post" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Submit</button> {% endbuttons %} </form> Is the second'form' in 'bootstrap_form form' supposed to reference/point to something? Is it a variable? What is a valid django form? I checked several posts and answers on this issue, but haven't been able to make sense of this error. -
I am trying to run an endless worker thread (daemon) from within Django
I have a worker thread which only task is to query a list of active users every 10 minutes from the database, and to send them an SMS message if a certain condition is fulfilled (which is checked every minute); also the worker thread does not hinder the main application at all. So far I managed to get the thread up and running and sending SMS works also just fine. However, for some reasons the thread stops/gets killed after some random time (hours). I run a try: except Exception as e: within a while True, to catch occurring errors. Additionally, I print out a messages saying what error occurred. Well, I never see any message and the thread is definitely down. Therefore, I suspect Gunicorn or Django to kill my thread sort of gracefully. I have put log and print statements all over the code but haven't found anything indicating why my thread is getting killed. My wsgi.py function where I call the function to start my thread """ WSGI config for django_web project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application … -
search non index fields in django vs making them keys
This is a general question about searching on a non-indexed field in Django 2.2 If I have a model with class Policy(models.Model): policy_no = models.PositiveIntegerField() eff_date = models.DateTime(auto_now=False, auto_now_add=False) name_id = models.ForeignKey(InsuredName, on_delete=models.CASCADE) Now when the insured goes to my website and searches for his policy number. I do not have this as the primary key because you can have many policies endorsements(change in coverage) during a policy term. There can be millions of policies. Should I use the following model setup instead to add policy number as an indexed field? class Policy(models.Model): policy_no = models.PositiveIntegerField(db_index=True) eff_date = models.DateTime(auto_now=False, auto_now_add=False) name_id = models.ForeignKey(InsuredName, on_delete=models.CASCADE) Also is it a good practice if you are going to order by, or filter by, it should be indexed. Please let me know if this is the correct way to make a field indexed. Thank you I need to know what approach is better? Nonindex field vs indexed class Policy(models.Model): policy_no = models.PositiveIntegerField() eff_date = models.DateTime(auto_now=False, auto_now_add=False) name_id = models.ForeignKey(InsuredName, on_delete=models.CASCADE) vs class Policy(models.Model): policy_no = models.PositiveIntegerField(db_index=True) eff_date = models.DateTime(auto_now=False, auto_now_add=False) name_id = models.ForeignKey(InsuredName, on_delete=models.CASCADE) Also is it a good practice if you are going to order by, or filter by, it should be indexed. … -
Form not raising ValidationError on creation, only when instance is updated
I have kind of a strange error when I try to clean my instance data. My instance is running a clean method to create a condition where the required stock needs to be less than the actual stock. Even so, the method only works when the instance its updated, and not when the instance is created. Another strange behavior is that I have in console the error printing "validation error raised", but the actual error is not raising ONLY when created. I am not very sure if I am triggering the method in a good way. class SaleItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(SaleItemForm, self).__init__(*args, **kwargs) self.fields['client'].queryset = Associate.objects.filter(status="CLIENT") class Meta: model = SaleItem exclude = () # validate clean information def clean(self): cleaned_data = super().clean() print("CLEAN COUNT") product_temp = cleaned_data.get('product') count_temp = cleaned_data.get('count') product_stock = Product.objects.get(id=product_temp.id).stock print("Count:{}".format(count_temp)) print("Stock:{}".format(product_stock)) if count_temp > product_stock: print("validation error raised") self.add_error('count','Not possible to obtain more items than allowed') -
Display profile image in nav bar
I am building my own blog site. I managed to have the users upload their own profile pic and have it displayed beside their post but now i want to have that same image be displayed in the navbar as a profile image but when i do it the same way i did it with the posts it doesnt work and looks like this. For the posts i made a profile image model and accessed the variable from within the html file but the same method does not work for displaying it in the nav bar. I am using python and django for backend. This is my model code for the profile image: from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics") def __str__(self): return f"{self.user.username} Profile" def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) This is how i reference it in my html file for displaying next to posts: <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}" id="img"> What am I doing wrong? -
Mailgun forwarded POST requests have completely another requests data
We have the mailgun setup that forwards the emails to our API endpoint to be scraped. But, nearly 20 per cent of the transactions data is not the data expected, but the data of the some previously failed POST request to our scraping end point. this is the craziest problem I have ever seen, when I open the log file and check the URL of storage field, open the file I see that recipient and content is the one I expected, but when I log it on my endpoint, I see completely different data. I have opened a support ticket but couldn't have a logical response yet. Mailgun forwarding, POSTing emails to scraping API endpoints developed in Django Rest Framework running on Heroku Server response: 404 "error: user not found adfc@blabla.com" which I directly printing from request.POST.get("recipient") field. But the actually file has completely another recipient as well as other request.POST fields -
Django site won't load both http and https links submitted via form/model
Users can submit links to external sites via a form and "Event Website" field on my site. The site is sent to the "link" model in the admin and is rendered in the template with <a href="//{{ item.link }}" target="_blank"> {{ item.title }} </a>. However, not all links are loading the external site. When on the production site, only links with "http://" or "https://" included in the link the user submitted navigate to the external site. Links entered without such as "facebook.com" or "www.facebook.com" do not load. I get a 404 error. How can I get my page to load the external site no matter how the link is entered (given that it's valid)? -
How to sort values of serializer custom field in DRF
I have created a custom field in the client serializer. The value of this field is calculated by a complex serializer method. class ClientStatsSerializer(serializers.ModelSerializer): """ Serializer shows total_spend for 2019 by client. """ refs_count = serializers.SerializerMethodField() total_spend_2019 = serializers.SerializerMethodField() class Meta: model = Company ordering = ('total_spend_2019',) fields = [ 'id', 'legal_name', 'refs_count', 'total_spend_2019', ] def get_total_spend_2019(self, obj): ... I would like to get the output sorted by the value of total_spend_2019. It looks like I cannot do it here with a simple ordering = ('total_spend_2019',) I cannot do it either in the model, neither in the view. Any idea how to solve this? Thank you very much!! -
Loading data through template rendering?
Currently I have some code in my index.html looking like: <script> var episodes = [ {% for episode in episodes_json %} {{episode|safe}}, {% endfor %} ] </script> And in my view: def view(request): return render("index.html", request, {"episodes": ...} This loads some data that I display to my user. It works great, but I haven't seen this type of data loading in any django tutorials I've seen thus far. Are there are any downfalls to loading data this way, rather than through AJAX request or something? -
How to fix this 400 bad status error while accessing my pache on apache sever?
I'm deployed my django app on server and when I'm trying to get the page on my web browser, then "Bad Request (400)" is all I can see on the page. No errors in sudo tail /var/log/apache2/error.log artifai-website.conf <VirtualHost *:80> DocumentRoot "/home/artifai/artifai_website/" WSGIScriptAlias / /home/artifai/artifai_website/src/artifai_website/wsg$ WSGIDaemonProcess artifai_website python-path=/home/artifai/artifai_web$ WSGIProcessGroup artifai_website <Directory /home/artifai/artifai_website/src/artifai_website> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /home/artifai/artifai_website/src/static <Directory /home/artifai/artifai_website/src/static> Require all granted </Directory> </VirtualHost> -
Django:Admin List_display is not working for one specific model
I am building an app. I am trying do display fields for 2 different model. Consultation and Consultationserie. The list_display function works for consultationserie but not for consultation. It only shows one field (start_date). There is a foriegnkey of linking to a consultationserie type in the consultation model. I wonder if it is causing a problem. I added to create a parent to child relationship between consultationserie and consultation. Thank you in advance for your help I tried to use different register method (With the decorator, with admin.site.register, admin.site.register(Consultation,ConsultationAdmmin)). Models.py: from django.contrib.auth.models import User from django.db import models import uuid from datetime import date from django.urls import reverse # Used to generate URLs by reversing the URL patterns class ConsultationSerie(models.Model): """Model representing a consultation process (define by the relationship between a patient and a doctor) but notr a specific consultation""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text = 'Unique ID for this particular Consultation process' ) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) patient = models.ForeignKey('Patient', on_delete=models.SET_NULL, null=True) doctor = models.ForeignKey('Doctor', on_delete=models.SET_NULL, null=True) def __str__(self): "Number representing the consultation process" # return str(self.id) return self.patient.lastname + "&" + self.doctor.lastname def get_absolute_url(self): """Returns the url to access a detail record for this consultation process""" return … -
How to divide my app and make extensions?
So, a while ago i have made a web application and now i want to improve it and put some premium content. The problem is that i have no idea how to do that. The application is used by different roles(for example: students, professors, administrators, etc.) and i want to make a normal package, premium package and custom package that i will sell optionally. Normal package would contain only base functionalities, premium would contain all of them and custom would contain only functionalities that customer wants. Imagine it like this, the application is made for an University and a professor is using it. There is an index page for his role and if he is using a normal package he can see only timetable of his lessons, if he is using a premium package than he can see his timetable, students who go to his class, grades, etc. How can i achieve that? Do i need to make numerous versions of an applications for every combination of functionalities? I hope there is a way to achieve this by separating functionalities and somehow disabling and enabling them optionally. P.S. I am using Django framework for backend and React js for frontend. -
Bidirectional OneToOne relation - Django
I have two models (Slot, Appointment). On the appointment one, I have defined a OneToOne relation with the slot model, so good so far; thanks to the RelatedManager I can access the appointment from the slot object but this's done at python level and I need (for some future changes) appointment_id column to be created on the Slot table. class Slot(models.Model): start_at = models.DateTimeField() end_at = models.DateTimeField() duration = DateTimeRangeField( null=True, blank=True ) # Bidirectional appointment = models.OneToOneField( "appointments.Appointment", on_delete=models.SET_NULL, related_name="slot", blank=True, null=True ) class Appointment(models.Model): slot = models.OneToOneField( Slot, on_delete=models.SET_NULL, related_name="appointment", null=True, blank=True, ) The code above will raise some errors when trying to create the migrations like: appointments.Appointment.slot: (fields.E302) Reverse accessor for 'Appointment.slot' clashes with field name 'Slot.appointment'. HINT: Rename field 'Slot.appointment', or add/change a related_name argument to the definition for field 'Appointment.slot'. Basically, due to the python part of the ORM, you can't define the same field on both models. Any idea of how to achieve this. I guess I will have to overwrite some parts of the RelatedManager. I could make this throw SQL but then it won't be clear on the code level. -
How to send object from django template to view function?
I want to send objects from a list in django template to view function. Basically what I want to do is that whenever user hits "view" button in code then I send a post request and send "sel" as data to a view function because I have to use "sel" in view function. search.html {% for sel in selections %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <img src="../static/listhome/media/images/house2.jpg" width="100%" height="225" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" ><rect width="100%" height="100%" fill="#55595c"/></svg> <div class="card-body"> <h3>Price: </h3> <p> {{sel.address}}<br> Bedrooms: <br> Baths: <br> Square Feet: {{sel.approximate_square_footage}} </p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> ## THIS IS BUTTON TO BE USE TO SEND DATA <button type="submit" class="btn btn-sm btn-outline-secondary">View</button> </div> <small class="text-muted">Days listed: </small> </div> </div> </div> </div> {% endfor %} 'Selections' is a list containing some elements from my database. It is the filtered result of my database passed to this template earlier through the following code: views.py def search(request): value = request.POST.get('searchvalue') selections = Listing.objects.filter(address__contains=value) context={ 'selections':selections, 'value':value, } return render(request, 'search.html',context) -
Saving ManyToManyFields using ModelForms
I am a very new to Django. I am trying to create a Django app. It has portlist and internalapp models. I am using ModelForm to create Internalapp entry. However,the problem is that ports in internalapp model is a ManyToManyField. When I create new entry of internalapp, the ports field( ManyToManyField) does not save data into database.Below,I provide my modles.py,forms.py and views.py code snippets. Any help would be appreciated. models.py class portList(models.Model): PROTOCOL = (("tcp","TCP"),("udp","UDP"),("icmp","ICMP")) appName = models.CharField(max_length=50) serviceName = models.CharField(max_length=50) protocol = models.CharField(max_length=10, choices=PROTOCOL, default= "TCP") reviewDt = models.DateField(default=date.today) status = models.CharField(max_length=20,null=True) def __str__(self): return self.serviceName class internalapp(models.Model): PERIMETER_DOM = (("All","All"),("ECN","ECN"),("GIZ","GIZ"),) plAppConfig = models.CharField('PaloAlto Application Config',max_length=1000, blank=False, null=True) comment = models.CharField('Comments',max_length=500, blank=False, null=True) createdDt = models.DateField('Creation Date',default=date.today) # Automatically set the field to now when the object is first created. ports = models.ManyToManyField(portList,blank=True) def __str__(self): return self.servGrpNm forms.py class InternalappModelForm(forms.ModelForm): groupInd = forms.IntegerField(label='Group Index',min_value=0) appGrpNm = forms.CharField(label='Application Group Name',help_text="This field consists of Perimeter Dom, Group Index and Appliction Function name" ) servGrpNm = forms.CharField(label='Service Group Name',help_text="This field consists of Perimeter Dom, Group Index and Appliction Function name") comment = forms.CharField(widget=forms.Textarea(attrs={'cols': 50, 'rows': 3}),required=False) ports = forms.ModelMultipleChoiceField(queryset=portList.objects.all(),required=False) class Meta: model=internalapp fields = ['appGrpNm', 'servGrpNm', 'perimeter', 'groupInd', 'appGrpFunc', 'comment', 'ports'] views.py … -
Inbuilt User form access
We know there is inbuilt model in django named User, but how to access inbuilt form for that User model in django 2.2? Is there a similar UserCreationForm in django 2.2 as in django 1.10 ? if yes then which directory ? -
Cannot access running django server?
I've created a docker image for django rest project, with following Dockerfile and docker-compose file, Dockerfile FROM python:3 # Set environment variables ENV PYTHONUNBUFFERED 1 COPY requirements.txt / # Install dependencies. RUN pip install -r /requirements.txt # Set work directory. RUN mkdir /app WORKDIR /app # Copy project code. COPY . /app/ EXPOSE 8000 docker-compose file version: "3" services: dj: container_name: dj build: django command: python manage.py runserver 0.0.0.0:8000 volumes: - ./django:/app ports: - "8000:8000" And docker-compose up command bring up the server like this, but in web browser i can't access the server. -
Need examples of how to use djangorestframework-api-key
So I am trying to get comfortable using api-keys and this is a package I found and it seems promising. I added the from rest_framework_api_key.permissions import HasAPIKey permission_classes = [HasAPIKey] Also in settings changed the custom header with API_KEY_CUSTOM_HEADER = "HTTP_API_KEY" and looked at the documentation, but no matter what I pass in as an argument in my url it seems to not work. I pass in http://127.0.0.1:8000/api/questions/API-KEY:********/ with my prefix key and it doesn't work. Any help?