Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ignore Special characters in queryset filters: Django
I have a model Emp which has a field name. I want to filter on that field by ignoring the special characters. For eg: value of name for an instance is "test_name". And if I pass testname, it should give me the result. result = Emp.objects.filter(name="testname") Is there any lookup to get this result? -
Using docker registry to share my multi-image containerized app: Encountering Problems connecting multiple image repos
My local docker container app is made up of 4 images, React, Django, nginx, postgres. It runs perfectly locally, (although of course I need to manually go to 127.1.1.0 on my local computer to view the app) I want other people to be able to view this app as well, if they have docker installed on their local computer, and so, using the steps in the docker documentation, I pushed all four images to docker hub. I am befuddled by the rest of the documentation, as when I tried an example using my local docker image name as below, docker run -d -p 3000:8000 --restart=always --name myport myport_nginx , only the nginx image service was pulled,and able to start up as a single container, but the rest of the services were not called up. Thus, my question is: How do I define those four images so that they are connected the way they are on my local computer, and so anyone with a local docker can pull my repo and inspect my app by going to 127.0.0.1 on his local computer. I know dockerbub is analogous to github and this should be straight-forward, but somehow my head has muddled this … -
Django: Saving multiple forms from one view
I've looked at a variety of answers but have been unable to progress. Code can be found here: https://github.com/varlenthegray/wcadmin/blob/master/customer/views.py - focused on "customer" right now with a bit of "jobsite" in there for good measure. Question: How do I get the job site primary key? It's reloaded via JS, so I presume it has to be in the form. Is the best method going to be to tag it on as a query string at the end of the URL? It's not "broken" as in it's not giving me any Django errors, but it's also not saving. forms.py class ViewCustomerForm(forms.ModelForm): next_service = forms.DateField(widget=forms.DateInput(format='%m-%d-%Y'), input_formats=['%m-%d-%Y']) edit_customer = forms.BooleanField(widget=forms.HiddenInput, initial=True) class Meta: model = Customer fields = ['company', 'title', 'first_name', 'middle_name', 'last_name', 'secondary_contact_name', 'website', 'email', 'main_phone', 'alternate_phone', 'fax_number', 'billing_address_1', 'billing_city', 'billing_state', 'billing_zip'] class ViewJobSiteForm(forms.ModelForm): edit_job_site = forms.BooleanField(widget=forms.HiddenInput, initial=True) next_service_date = forms.DateField(widget=forms.DateInput(format='%m-%d-%Y'), input_formats=['%m-%d-%Y']) class Meta: model = JobSite fields = ['name', 'address', 'city', 'state', 'zip', 'phone_number', 'email', 'next_service_date', 'active', 'access_code', 'bill_parent', 'customer', 'primary_technician', 'service_interval', 'requires_supporting_technician'] class EditJobSiteEquipment(forms.ModelForm): edit_job_site_equipment = forms.BooleanField(widget=forms.HiddenInput, initial=True) class Meta: model = JobSiteEquipment fields = ['id', 'tags', 'installed_on', 'edit_job_site_equipment'] views.py @login_required def view_customer(request, pk): customer = get_object_or_404(Customer, id=pk) job_site = JobSite.objects.filter(customer=pk).first() all_job_sites = JobSite.objects.filter(customer=pk) edit_customer = ViewCustomerForm(instance=customer, prefix='customer') edit_job_site = … -
Django custom model Interger extrafield not saving in the database return None instead
my models class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): print(phone_number, 'phone_number') """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), **extra_fields ) user.phone_number = phone_number # user.phone_number = 333333 print(user, 'user') user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=100, default="") phone_number = models.IntegerField(default=0, verbose_name='phoneNumber') is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser slug = models.SlugField(max_length=255, unique=True) objects = UserManager() def save(self, *args, **kwargs): print(self.phone_number, 'before') #this print statement return none if not self.slug: self.slug = slugify(utils.rand_slug() + "-" + self.username) super(User, self).save(*args, **kwargs) print(self.phone_number, 'after') #this print statement return none # notice the absence of a "Password field", that is built … -
Django Admin filter by foreign's key foreign key
I have a model that measures a certain tool's use defined as: class MetricToolUse(models.Model): date = models.DateTimeField(default="2000-01-01 12:00:00") user = models.ForeignKey(User, on_delete=models.DO_NOTHING) exec_time = models.FloatField('Execution time (s)') params = jsonfield.JSONField(default={}) On Admin I wan to be able to filter all MetricToolUse's of users that belong to certain groups. So the filter value is the Group name. class MetricToolUseAdmin(admin.ModelAdmin): list_filter = ( ('date', DateFieldListFilter), 'user', # custom filter for all users in group ) I tried using user__group but did not work -
How to get the desired value from the data used by the json dump method
The History model has a summary field. History object is created as follows, and the summary field uses the json.dumps method. The history field is a TextField, and in the template, it is of type 'str'. [views.py - how to create History object] history = History(user=request.user, study=new_study, summary=json.dumps({ 'field_summary': field_summary, 'file_summary': file_summary })) This is the summary field from the template . {"field_summary": {"is_recruiting": "None -> Yes", "teacher": None -> \uad8c\ub098\uacbd/\uae40\uc218\uc5f0"}, "file_summary": {}} But I want to get only the teacher values using annotate [views.py] histories = History.objects.filter(summary__icontains='teacher', create_date__gte='2022-01-01', create_date__lte='2022-04-10')\.annotate(teacher=Value(json.loads('summary')['field_summary']['teacher'], output_field=CharField()))\.values('study_name', 'teacher', 'create_date') Since we used json dumps, we used the json load method to read the data. But I get an error. How do I get the desired value of the textfield's str type? JSONDecodeError at /charts/ Expecting value: line 1 column 1 (char 0) -
How to store data requests in Django API running in AWS EC2?
So I have a Django API (via REST framework) in AWS EC2 that takes in raw JSON data. The API preprocesses the data and outputs a score from 0 to 100. I was wondering how I can store this incoming raw JSON data and the score efficiently for me to analyse the data. Not in a database because it would get complicated but preferrably in a file but I am not sure what is the easiest way. I request the data as data = request.data and the score is outputted like ypred = model.predict_proba(df) for i in range(len(ypred)): # first interval out of 3 intervals if( ypred[i][1]>=0.0 and ypred[i][1]<=0.30): response_dict = {"score": round(ypred[i][1]*100,3)} print(Response(response_dict, status=200)) return Response(response_dict, status=200) Thank you -
if select2 is null, make input field required
I have a text field and a select2 field. The user can input something in the input field, but can also select a predefined choice from the select2 field. I want to do the following: if the select2 is selected, then the form goes through, if not, the input field will be required and the form cannot pass through. I already made a logic in the backend (Django) that copies the value of the select2 to the text field just to make sure all data is valid, but if I leave the frontend without validation, the user could leave everything empty and submit an empty form. Here's my html: <table id="myTable" class="table order-list"> <thead> <tr> <td>Médicament</td> <td>Dosage</td> <td>Posologie</td> <td>Durée</td> <td></td> </tr> </thead> <tbody> <tr> <td class="col-5"> <div class="row"> <div class="col-6"> <input class="form-control mb-4" placeholder="Nom du médicament" type="text" name="medicament0"> </div> <div class="col-6"> <div class="form-group"> <select class="form-control select2-show-search form-select" id="medicament-id0" name="listemedicament0"> <option value="0">Ou choisir de la liste</option> {% for d in drugs %} <option value="{{ d.id }}">{{ d }}</option> {% endfor %} </select> </div> </div> </div> </td> <td> <input class="form-control mb-4" placeholder="20mg" type="text" name="dosage0"> </td> <td> <input class="form-control mb-4" placeholder="2 / j avant repas" type="text" name="posologie0"> </td> <td> <input class="form-control mb-4" placeholder="7 … -
2 models for html in Django
I want to list some data into my html file, below is my 2 models files and My question is how to show products_name in my html ? class ProductsDescription(models.Model): products_id = models.ForeignKey(to='Products', to_field='products_id', on_delete=models.CASCADE, unique=True) products_name = models.CharField(max_length=255, blank=True, null=True) class Products(models.Model): products_id = models.AutoField(primary_key=True) products_type = models.IntegerField(blank=True, null=True) manufacturers_id = models.IntegerField(blank=True, null=True) brand_id = models.IntegerField(blank=True, null=True) products.py from myadmin.models import Products as products from myadmin.models import ProductsDescription def index(request, pIndex=1): mainproducts = products.objects umproducts = mainproducts.filter(products_type=1) pIndex = int(pIndex) page = Paginator(umproducts, 25) maxpages = page.num_pages if pIndex > maxpages: pIndex = maxpages if pIndex < 1: pIndex = 1 list2 = page.page(pIndex) plist = page.page_range context = {"umproducts": list2, 'plist': plist, 'pIndex': pIndex, 'maxpages': maxpages } return render(request, "index.html", context) in my html <table class="table table-hover"> <tr> <th>ID</th> <th>TYPE</th> <th>Products Name</th> <th>MANUFACTORES</th> <th>BRAND</th> </tr> {% for vo in umproducts %} <tr> <td>{{ vo.products_id}}</td> <td>{{ vo.products_type }}</td> <td>{{ vo.products_name }}</td> <td>{{vo.products_manufacturers}}</td> <td>{{ vo.products_brand}}</td> </tr> The problem maybe is I cann't put the product_name from ProductsDescription into umproducts tuple,and my question is how to connect 2 models and namea new tuple then I can use it in html? -
Django save model everyday
I have a model and a signal in models.py and this model sends message to discord webhook with how many days left to something. I want to refresh it everyday at 12:00 AM everyday automatically without using django-celery cause it doesnt work for me. My plan is do something like this time_set = 12 if time_set == timezone.now().hour: ...save model instances... but i have totally no idea how to do it And i want to do it this way cause when model instance are saved signal runs -
can you use python random module inside django models to create unique id
i'm building an invoicing web app, so I want to be able to create a unique id of every invoice but also I want to control how the id looks eg "",BU236718N from random import randint, choice from django.db import models def myID(): my_id = "BU" + randint(1,100000) + choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ") return(my_id) class Invoice(models.Model): invoice_number = models.CharField(myID) def __str__(self): return (self.invoice_number) -
Django to catch all invalid logins and unauthorized access like 401s and 403s
I want to capture all invalid logins/unauthorized access such as 401s and 403s returned from the site so I can log them to a security logging service, investigating if there is an easy way to catch all of these without putting in much custom logic. I have tried using middleware approach: def simple_middleware(get_response): # One-time configuration and initialization. def middleware(request): response = get_response(request) if response.status_code in [403, 401]: log.warning('invalid login') return response return middleware Unfortunately an incorrect login to the /admin/ login, it returns status 200, however I think this would work for custom login that explicitly throws 401/403. I have also tried using the signal approach using request_finished but all I get is just the handler class. So... looking for ideas. -
Django Attribute Error when using serializer
I would like to fetch the entire table. My model and serializer seems to be correct but I am getting the below error Got AttributeError when attempting to get a value for field symbol on serializer CompanySerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'symbol'. Below is my Model models.py from django.db import models class Companies(models.Model): symbol = models.CharField(max_length=100) name = models.CharField(max_length=255) isin = models.CharField(max_length=255) serializers.py from rest_framework import serializers from .models import Companies class CompanySerializer(serializers.ModelSerializer): class Meta: fields = ['symbol', 'name', 'isin',] # fields = '__all__' model = Companies Below is my view views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from .models import Companies from .serializers import CompanySerializer from django.core.serializers import json class companiesView(APIView): def get(self, request): companies = Companies.objects.filter(id=1) serializer = CompanySerializer(companies) # json_serializer = json.Serializer() # json_serialized = json_serializer.serialize(companies) response = Response() response.data = { 'named' : serializer.data, } return response I am not sure what is causing this issue. Thanks in Advance. -
React Native Django authentication
Are there any simple react native django authentication projects that have simple login, logout, password change with django rest framework tutorials. API already set up and fully functional, need to intergrate it with react native, tried axios but system did not sucessfully post rather gave a forbidden error "POST /api/login/ HTTP/1.1" 403 45 Forbidden: /api/login/ Any assistance will be appreciated -
Django 1000 error code on Web socket while sending data to the socket(AsyncJsonWebSocketConsumer)
Can anyone explain it to me the reason behind this error. The socket gets connected, the moment I send data into it, it gives back WebSocket HANDSHAKING /physiochat/ [192.168.43.159:57270] WebSocket CONNECT /physiochat/ [192.168.43.159:57270] WebSocket DISCONNECT /physiochat/ [192.168.43.159:57270] disconnected :- 1000 Here is my code , Also the print commands are not working, nothing gets printed on the terminal. I used the another consumer with same code but its working fine. Kind of new to the web sockets so pardon my question. Any help will be appreciated. Thanks 🙏🏻. class PhysioChatConsumer(AsyncJsonWebsocketConsumer): user = None participant_info_obj = None async def connect(self): print("CONNECTED") await self.accept() async def disconnect(self, code): print('disconnected :- ', code) async def receive_json(self, data): print("Receiving Json") try: print(self.user) if self.user and self.user.id: if 'text' in data.keys() and 'token' in data.keys(): data = await self.add_mssg_to_db(data) await self.channel_layer.group_send( self.room_name, { 'type':'broadcast_message', 'data': data, } ) else: print("NOT GETTING USER") await self.close() else: if 'token' in data.keys() and 'room_id' in data.keys() : self.token = data['token'] self.room_id = data['room_id'] self.is_kiosk = data.get('kiosk', None) if self.is_kiosk: self.profile_id = data['profile_id'] authenticated = await self.authenticate_user() if authenticated: check = await self.check_user_info() if check: self.room_name = f'chat-under-{self.room_id}' await self.channel_layer.group_add( self.room_name, self.channel_name ) else: print("Unable to get the user … -
Django Rest Framework Passing Parameters post
I'm using django rest framework and I want to pass parameters through the POST method, but I'm getting through the url only, is there any way to send information as a body? For example in react pass like this: fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', body: JSON.stringify({ title: 'foo', body: 'bar', userId: 1, }), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }) .then((response) => response.json()) .then((json) => console.log(json)); As it currently stands: angra\urls.py # imports from django.urls import path from . import views as views # if urls.py and views.py are in same dir urlpatterns = [ path('login/<str:email>/<str:password>/', views.login, name="login"), path('hello/', views.hello_world, name="hello_word"), path('calculate/<int:a>/<int:b>/', views.calculate, name="calculate"), path('teste', views.some_view, name="some_view"), ] angra\views.py @api_view(['POST']) def login(request, email, password): return Response({"email":email, "password":password, "nivel":1}) -
Adding a django variable to css
I'm generating a PDF, with django. In my css I use @bottom-left to show the pages, and I would like @bottom-right to show the date and hour when the pdf was generated. I would like to pass this date that I have in a variable to this "content: datetime". Does anyone know if it's possible, and if not, any other alternatives? @page { size: letter; @bottom-left { content: counter(page) " of " counter(pages); font-family: 'Prompt', sans-serif; font-weight: 300; font-size: 9px; color: #868484; } @bottom-right { content: 'datetime'; font-family: 'Prompt', sans-serif; font-weight: 300; font-size: 9px; color: #868484; } } -
How to take multiple value from multiple drop downs in the same POST form in Django
Hello I am creating a cinema book system in Django, and the user must select a film and its date/time from two drop down menus. My issue is that it only takes the film and not date/time. I was wondering how I would be able to add these two in the same form. Thanks the html file: <form action="/booking" method="post"> {% csrf_token %} <div class="movie-container"> <label>Pick a film:</label> <select name="selectedFilm"> {% for showing in showings %} <option value="{{ showing.film }}" name="film">{{ showing.film }}</option> {% endfor %} </select> <br> <br> <label>Pick a time:</label> <select id="selectedDate"> {% for showing in showings %} <option value="{{ showing.date_time }}" name="date">{{ showing.date_time }}</option> {% endfor %} </select> <br> <div class="btn-layer"> <input type="submit" value="Select"> </div> </div> </form> the form file class SelectedFilmForm(forms.Form): selectedFilm = forms.CharField(required=True) selectedDate = forms.DateTimeField(required=True, input_formats=["%Y-%m-%dT%H:%M", ]) enter code here the models file class Film(models.Model): name = models.CharField(verbose_name='Film name', max_length=30) age_rating = models.CharField(verbose_name='Age rating', max_length=5, choices=AgeRatings, default='U') duration = models.DecimalField(verbose_name='Duration (minutes)', max_digits=4, decimal_places=1, blank=True, null=True) description = models.CharField(verbose_name='Description', max_length=500, blank=True, null=True) image = models.ImageField(upload_to='films',default='null') def __str__(self): return self.nameclass Screen(models.Model): screen_id = models.CharField(verbose_name='Screen ID', max_length=30) capacity = models.IntegerField(verbose_name='Capacity') def __str__(self): return self.screen_id class Showing(models.Model): film = models.ForeignKey(Film, on_delete=models.CASCADE, verbose_name='Film', blank=True, null=True) date_time = models.DateTimeField() screen … -
Query through Django tables via switchboard
I have a database structure and solved it with a switchboard instead of ManyToMany. However, decryption is a problem ... class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) class Company(models.Model): name = models.CharField(max_length=60) class CompanyEnrollment(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) company_position = models.ForeignKey( CompanyPosition, on_delete=models.CASCADE) company_enrollment_start = models.DateField(blank=True, null=True) status = models.BooleanField(default=True) class Meta: unique_together = [['person', 'company']] Query the required data: This works, but I don't think Person items that don't have a Company assigned to them appear ... datas = CompanyEnrollment.objects.all().select_related('company') so far I'm fine, I'm listing the people, but I'd like to add the Company_name field next to it. Is it possible to do this in a query? Thanks for the help, I want to understand this, to learn. -
Setting up and activating virtual environment
So, I've been trying to activate my virtual environment in VScode so I could open my Django manage.py and run the server, but for some reason it doesn't seem to activate in my bash terminal. And after running it, I get a "did you forget to activate your virtual environment?". What am I missing here? -
Django ModelForm with extra fields
So I have this ModelForm in my django project: class DateForm(ModelForm): image = forms.ImageField() class Meta: model = Date exclude = ('user',) the Photo model: class Photo(models.Model): date = models.ForeignKey(Date, on_delete=models.CASCADE) image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/') the form: <p class="p-form">Title</p> {{ form.title }} <p class="p-form">Description</p> {{ form.description }} <p class="p-form">Place</p> {{ form.place }} <p class="p-form">Rating</p> {{ form.rating }} <p class="p-form">Photos</p> {{ form.image }} Whenever I try to save my form, its form_invalid method is being called and it doesn't save the form. What is the matter? How do I save extra field of ForeignKey model? How can I get that images sent via form? Thanks! -
Customize text and style in messages from a Django app
I have a form in django, and when submitting I get a message "Complete this field", how can I customize the text and style of it. forms.py: class ClientesForm(forms.ModelForm): class Meta: model = Clientes fields = 'all' widgets = { 'id':forms.TextInput(), 'identificacion':forms.TextInput(attrs={'placeholder': 'Identificación'}), 'nombre':forms.TextInput(attrs={'placeholder': 'Nombre'}), 'direccion':forms.TextInput(attrs={'placeholder': 'Dirección'}), 'email':forms.EmailInput(attrs={'placeholder': 'EMail'}), 'telefono':forms.TextInput(attrs={'placeholder': 'Teléfono'}), } error_messages = { 'identificacion': {'required':'Custom message'} } The message that appears when submitting is enter image description here -
How to make two requests and continue displaying data from the first request in Django?
I'm new to Django and I'm uploading a file and displaying, on the file view page, I'd like to type a word and display that word. I'm having difficulty in requests to display this word, because when I click to display the word, the file that was being displayed is no longer displayed. #view.py def upload(request): if request.method == 'POST' and request.FILES.get('myfile'): ... return render(request, 'show_file.html', { 'path': path, 'fileName': fileName, }) count = None word = None if request.method == 'POST' and request.POST.get('word'): word = request.POST['word'] return render(request, 'show_file.html', { 'word': word, 'count': count, }) return render(request, 'upload.html') #upload.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> #show_file.html <div> <div> <embed src="{% static 'files/' %}{{ fileName }}" type="application/pdf" style="width:718px; height:1000px;"> </div> <div> <form method="POST"> {% csrf_token %} <label for="word">Write a word:</label> <input id="word" type="text" name="word" value="" /> <input type="submit"> {% if count != None %} Word: {{ word }} {% endif %} </form> </div> </div> -
Module object has no attribute "DatabaseError" after upgrading from Django 1.9 to 1.11
I have a project that I want to slowly migrate to a newer version of Django & Python. I changed my Django version to 1.11 from 1.9 and now I get an error. For this code: import psycopg2 ORIGINAL_BACKEND = getattr(settings, 'ORIGINAL_BACKEND', 'django.db.backends.postgresql_psycopg2') original_backend = import_module(ORIGINAL_BACKEND + '.base') DatabaseError = original_backend.DatabaseError I get AttributeError: 'module' object has no attribute 'DatabaseError' for some reason. I don't really understand why, because I've only changed the Django version - but the error seems to be related to psycopg2. Why is this happening and how can I fix it? -
Displaying a model based on anoyher model
I need some help with setting up the view of a model based on another model. Essentially I have one model called Dataset and another one called DatasetReview, where DatasetReview has a foreign key connection to Dataset. I would like to display all of the DatasetReview models that are tied to a specific Dataset in a separate page. I can currently view each Dataset like so: http://127.0.0.1:8000/dataset/3/ and would like to see all of the DatasetReview models for Dataset 3 like so: http://127.0.0.1:8000/dataset/3/reviews But I am unsure how to set this up. I can show my code in the thread to keep everything contained. Any tips would be super helpful, very new to django. As such, I am not sure how to phrase this question well so I had difficulty finding other posts discussing how to do something like this. urls.py: from django.urls import path from .views import ( DatasetListView, DatasetDetailView, DatasetCreateView, DatasetUpdateView, DatasetDeleteView, DatasetReviewsView ) from . import views urlpatterns = [ path('', DatasetListView.as_view(), name='argo-home'), path('dataset/<int:pk>/', DatasetDetailView.as_view(), name='dataset-detail'), path('dataset/new/', DatasetCreateView.as_view(), name='dataset-create'), path('dataset/<int:pk>/update', DatasetUpdateView.as_view(), name='dataset-update'), path('dataset/<int:pk>/delete', DatasetDeleteView.as_view(), name='dataset-delete'), path('dataset/<int:pk>/reviews', DatasetReviewsView.as_view(), name='dataset-review'), path('about/', views.about, name='argo-about'), ] views.py: from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ( ListView, …