Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I send email from Django app deployed in digital ocean?
I created a Django project where I send email using Gmail. It's working on my local server, but when I deploy the project to the digital ocean, the email is not sent. What can I do now? -
django how to convert request json string to object to process it
I receive this json response from web page data=%7B%22header%22%3A%22%7B%5C%22salno%5C%22%3A%5C%220%5C%22%2C%5C%22saldt%5C%22%3A%5C%22Wed+Jul+28+2021+00%3A33%3A40+GMT%2B0530+(India+Standard+Time)%5C%22%2C%5C%22soldto%5C%22%3A%5C%22%5C%22%2C%5C%22remark%5C%22%3A%5C%22%5C%22%2C%5C%22totqty%5C%22%3A310%2C%5C%22subtot%5C%22%3A20251%7D%22%2C%22details%22%3A%22%5B%7B%5C%22status%5C%22%3A%5C%22old-modified%5C%22%2C%5C%22saldtlid%5C%22%3A%5C%221%5C%22%2C%5C%22itemnm%5C%22%3A%5C%22item1%5C%22%2C%5C%22qty%5C%22%3A%5C%2218%5C%22%2C%5C%22rate%5C%22%3A%5C%2212.00%5C%22%2C%5C%22amount%5C%22%3A%5C%22216.00%5C%22%7D%2C%7B%5C%22status%5C%22%3A%5C%22new-record%5C%22%2C%5C%22saldtlid%5C%22%3A%5C%22-10%5C%22%2C%5C%22itemnm%5C%22%3A%5C%22new+item%5C%22%2C%5C%22qty%5C%22%3A%5C%2210%5C%22%2C%5C%22rate%5C%22%3A%5C%2210.00%5C%22%2C%5C%22amount%5C%22%3A%5C%22100.00%5C%22%7D%5D%22%7D&csrfmiddlewaretoken=q1ortMN1jyzBIJVn6qOREBLiNr3Lc7njhvI24lT93gLb5VNzWutot0qDeNvlyY5d the actual object contains invoice information and one csrfmiddlewaretoken the invoice data has 1 header dict object and multiple detail dict array how to convert the above to python objects so that I can process it -
Django Tabularinline with Auto complete field
I am trying to implement an auto complete field in a tabular inline model.where a user selects a site and the address cell is consequently filled with the appropriate address I defined my fields in a form as below : self.fields['sites'].widget = forms.Select( attrs={ 'id': 'id_sites', 'onchange': 'getsiteaddress(this.value)', 'style': 'width:200px' }, choices=sites_list, ) self.fields['site_address'].widget = forms.TextInput( attrs={ 'id': 'id_siteaddress', 'style': 'width:200px' } ) Everything works fine for the first row My issue is that when I move to the second row of the inline model and select an address the cell of the first row is the one that changes. How can I call the second row? This is my jquery function function getsiteaddress(site){ let $ = django.jQuery; $.get('/Delivery/deploymentsite/'+ site, function(resp){ $('#id_siteaddress).val(resp.data) }); } I would really appreciate any help -
How do you set up a subprocess to receive api requests in Heroku?
I have a react frontend deployed to a web process on Heroku. I have a django backend that is deployed to an app process as shown below. I keep getting a 502 error, so I originally thought my issue was in django. However, after a mistake where I had the react open already, and changed the web process to be django, I had a fully functioning app. However, after a little bit of clicking around, I only got the backend. Long story short, I need a way for my backend to receive api request calls from my frontend. Nothing I have done seems to have worked. Having two web processes doesn't work because Heroku only takes the last one and basically ignores the other one. As it stands, I am using http requests as the api call, but realistically, I just need a way to communicate between Django and React. If I have to redo something, I am willing to do so. Procfile release: python manage.py migrate backend api: gunicorn backend.wsgi:application web: bin/boot To be clear, web: bin/boot is a buildpack specifically for react apps. It works just fine, and I do not believe it is the issue. -
Djanog - Is there a better approach for a DRY CRUD solution in views.py?
I'm fairly new to Django, and I am trying to understand a better way to implement CRUD in my views.py file. Example view.py: # Assume I have two generic models: Foo and Bar from django.views.generic import UpdateView, DeleteView from .forms import FooForm, BarForm from .models import Foo, Bar class FooUpdateView(UpdateView): model = Foo form_class = FooForm template_name = 'foo_form.html' success_url = reverse_lazy('success-page') class BarUpdateView(UpdateView): model = Bar form_class = BarForm template_name = 'Bar_form.html' success_url = reverse_lazy('success-page') class FooDeleteView(DeleteView): model = Foo template_name = 'foo_delete.html' success_url = reverse_lazy('success-page') class BarDeleteView(DeleteView): model = Bar template_name = 'Bar_delete.html' success_url = reverse_lazy('success-page') Is there a way like the example below, where I can create a base class that I can inherit from, but still allows me to override and customize functions and variables. class UpdateBaseView(UpdateView): form_class = self.model_form template_name = 'self.model_form.html' success_url = reverse_lazy(success_url) class FooUpdateView(UpdateBaseView): model = Foo class BarUpdateView(UpdateBaseView): model = Bar success_url = reverse_lazy('bar-success') -
Django Models: How to write query for multiple value with filtering multiple value
I have user local_user and personal models. I try to make a query with the multiple results but should filtered with multiple value. Models have one to one relations between each other. There are models. class Hospital_Local_User(models.Model): id = models.AutoField(primary_key=True) email = models.CharField(max_length=45) password = models.CharField(max_length=45) phone = models.CharField(max_length=45) class Personal (models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) lastname = models.CharField(max_length=255) user_roles_id = models.ForeignKey(User_Role, on_delete=models.CASCADE) hospitals_id = models.ForeignKey(Hospital, on_delete=models.CASCADE) hospital_local_users_id = models.OneToOneField( Hospital_Local_User, on_delete=models.CASCADE) and This is the code I try to build. def listDoctors(request): userRole = User_Role.objects.get(id=2) Doctors = Personal.objects.filter(user_roles_id=userRole) hospLocUser = Hospital_Local_User.objects.filter(id=Doctors) serialized_queryset = serializers.serialize('json', hospLocUser) return JsonResponse(json.loads(serialized_queryset), safe=False) I try to make two objects then merge them into one object because when I try to convert Personal model to json it does not show email and phone fields. It just shows them as local_user_id. I do not need local user id I need fields in it. -
Pytest and mixer does not raise errors when testing non model fields
I am following Test driven development and am working through Django models with mixer, Pytest and pytest-django. This is the test for the Project model: class TestProject: def test_model_valid_fields(self, django_user_model): project = mixer.blend( 'workspaces.Project', title="Road map", non_model_field="some value" ) assert project.pk == 1 assert project.title == "Road map" assert project.non_model_field == "some value" The Project model, notice that Project model has only the title field: class Project(models.Model): title = models.CharField(max_length=200) Two things: How is mixer allowing the use of non model fields? Why is Pytest not raising an error, since the Project model does not have non_model_field field? What am I missing here? -
Difference between a File and Record
Please what's the difference between File and Record I have searched the whole Google and I have not seen any answer. -
Running django view/function on button click
I have the following button: <a class="btn btn-success">Accept</a>. Like this previous stack overflow question, I want to call my view after the button is clicked, but I can not seem to get it to work. What I have tried: Using AJAX, treating button like a form, requesting post data, but this does not seem to work. How can I make it so when my button is clicked, I call the bellow view? def acceptdonation(request, pk): Donation.objects.filter(pk=pk).update(views=F('views')+1) return HttpResponseRedirect(request.GET.get('next'))) -
innerHTML not working for select tag when i want to change new options
html code: <div class="row clearfix"> <div class="col-sm-12"> <div class="form-group"> <select id="domain" class="form-control show-tick" onchange="myFunction1()"> {% for item in domains %} <option value=" {{item.0}} ">{{item.1}}</option> {% endfor %} </select> </div> </div> </div> <div class="row clearfix"> <div class="col-sm-12"> <div class="form-group"> <select id="2"> <option></option> </select> </div> </div> </div> js function: <script> function myFunction1() { x = document.getElementById("domain").value; document.getElementById("2").innerHTML += "<OPTION>1</OPTION>"; alert(x); } </script> I am trying to change the drop-down box with id set as 2 when an on-change function is called in other drop-down box. Code looks good but i cant see the new options added. -
Django error SyntaxError: Non-ASCII character '\xff'
I am trying to run the django_tables2 tutorial but it shows error. Unhandled exception in thread started by <function wrapper at 0x7fd6677b4c80> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/__init__.py", line 28, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 86, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/config.py", line 95, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 38, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django_tables2/__init__.py", line 20, in <module> from .tables import Table, table_factory File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django_tables2/tables.py", line 1 SyntaxError: Non-ASCII character '\xff' in file /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django_tables2/tables.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details -
i am making a django website with multiple forms also used foregin key ValueEror :The view Capp.views.InsertProduct didn't return anHttpResponseobject
i am making a django website with multiple forms also used foregin key(user_id) to link one form with other in the database but at the last i get value error the error is:Exception Type: ValueError Exception Value: The view Capp.views.InsertProduct didn't return an HttpResponse object. It returned None insteated , the following is view.py file code(not complete code but only where error can lie)models.py part def InsertProduct(request): if request.method == 'POST': if request.POST.get('user_id') and request.POST.get('pname') and request.POST.get('pcategory') and request.POST.get('pdetails') and request.POST.get('foundedin') and request.POST.get('orderoftest') and request.POST.get('t1') and request.POST.get('t2') and request.POST.get('t3') and request.POST.get('f1') and request.POST.get('f2') and request.POST.get('f3') and request.POST.get('f4') and request.POST.get('f5'): saveproduct = ProInsert() saveproduct.user_id = request.POST.get('user_id') saveproduct.pname = request.POST.get('pname') saveproduct.pcategory = request.POST.get('pcategory') saveproduct.pdetails = request.POST.get('pdetails') saveproduct.foundedin = request.POST.get('foundedin') saveproduct.orderoftest = request.POST.get('orderoftest') saveproduct.t1 = request.POST.get('t1') saveproduct.t2 = request.POST.get('t2') saveproduct.t3 = request.POST.get('t3') saveproduct.f1 = request.POST.get('f1') saveproduct.f2 = request.POST.get('f2') saveproduct.f3 = request.POST.get('f3') saveproduct.f4 = request.POST.get('f4') saveproduct.f5 = request.POST.get('f5') checkpname = ProInsert.objects.filter( pname=saveproduct.pname).first() if checkpname: msgpname = messages.success(request, 'The user with Product Name ' + request.POST['pname']+' already exist...!') return render(request, 'product_details.html', {'msgpname': msgpname}) saveproduct.save() messages.success(request, 'Product Added..!') return render(request, 'product_details.html') else: return render(request, 'product_details.html') -
Module "django.core.mail.backends.console" does not define a "EmailBacked" attribute/class
i am trying to code reset password of my web application now I am facing this error mentioned in tagline. in my settings.py I have. EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBacked' my URLs are: path('password-reset/', auth_views.PasswordResetView.as_view(template_name='app/password_reset.html', form_class=MyPasswordResetForm), name='password_reset'), path('password-reset-done/', auth_views.PasswordResetDoneView.as_view(template_name='app/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='app/password_reset_confirm.html', form_class=MySetPasswordForm), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='app/password_reset_complete.html'), name='password_reset_complete'), -
how can I serialize a multi user model that uses proxy
so I am setting up an app that has 3 types of user admin, customer and Agent I have my model setup this way class UserManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email') user = self.model( email=self.normalize_email(email), name=name, ) user.set_password(password) try: user.save(using=self._db) except IntegrityError: raise IntegrityError('A user already uses this email') return user def create_superuser(self, email, name, password=None): user = self.create_user(email, name, password=password) user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): class Types(models.TextChoices): COSTUMER = "CUSTOMER", "Customer" AGENT = "AGENT", "Agent" type = models.CharField(_('Type'), max_length=50, choices=Types.choices, default=Types.CUSTOMER) email = models.EmailField(_('Email of the user'), unique=True) name = models.CharField(_('Name of the user'), max_length=100) phone_number = PhoneNumberField(_('Phone number of the user'), blank=True, null=True, unique=True) date_joined = models.DateField(_('Date joined'), auto_now_add=True) last_login = models.DateTimeField(_('last login'), null=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def __str__(self): return self.email class CustomerManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args **kwargs).filter(type=User.Types.CUSTOMER) class AgentManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args **kwargs).filter(type=User.Types.AGENT) class Customer(User): '''proxy class for registering customer''' objects = CustomerManager() class Meta: proxy = True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.CUSTOMER … -
How can I mix __str__ and @property?
I have question: I have some property decorator on model in Django: @property def replace_name(self): if not self.name: if self.pay: return self.registration_number else: return self.number else: return self.name When I get my data on page - If I do not use NAME.It means that when I enter data I leave field Name empty it returns me ID of model!But I want that it will return me registration_number! How I understand on this involves this method: def __str__(self): return f'{self.name}' Now it looks like this!But I have idea to added here: def __str__(self): return f'{self.name}{self.registration_number}{self.number}' After I added this it returns me what I want!This data!But!The problem is that @property does not working!It is returns me all data !How to mix this 2 methods to have normal working code?Can anybody explain!I know this way in str add is not correct!Please help! -
django forms .clean method is not getting invoked
Django forms clean method not getting invoked, I read django's full clean doc and other relevant stackoverflow questions. but could not get the answer at all. Frankly speaking, I am not getting what documentation is saying. In my case, few custom checks are required on my hidden form fields, So I need to call django forms .clean method, but .clean is not getting invoked. function is going to clean_client but not in .clean. Looks like its going to .clean_client through full_clean method, but not sure how to add custom checks for my hidden form fields. Here is my forms.py class EnquiryForm(forms.ModelForm): name = forms.CharField(label='Full name', required=True, max_length=100, widget=forms.TextInput(attrs={ 'class': 'form-control input-custom', 'id': 'name', }) ) mobile = forms.CharField(label='Mobile', required=True, widget=forms.TextInput({ "type": "tel", "class": "form-control input-custom", "name": "mobile", "placeholder": "eg. 9823523461" })) ... hidden_enq_code = forms.CharField( required=False, widget=forms.HiddenInput()) hidden_bhks = forms.CharField(required=False, widget=forms.HiddenInput()) hidden_conditions = forms.CharField( required=False, widget=forms.HiddenInput()) class Meta: model = Enquiry fields = ('client', 'if_other', ..., 'notes') def clean(self): print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>In Clean Method") self.cleaned_data = super().clean() client = self.clean_client() if not client: raise forms.ValidationError("Invalid client details", code="invalid") self.cleaned_data['client'] = client self.clean_hidden_fields() return self.cleaned_data def clean_hidden_fields(self): try: hidden_bhks = self.cleaned_data['hidden_bhks'] hidden_conditions = self.cleaned_data['hidden_conditions'] if hidden_bhks: hidden_bhks = hidden_bhks.split(',') self.cleaned_data['bhk'] = BHK.objects.filter( id__in=hidden_bhks) … -
how to make the slug auto in making URL articles in Django
im being making a blog i need to make the slug automatic in making the URL as title of each article without that i have everytime to copy the title and put it and edit it to make it slug manually -
python-django not able to create dir and file
This code snippet gives me error , i don't have idea why it's throwing error because i am opening file '+w' so if file not present there then python will create. response is file path and default_storage from Django anyone have idea why it is not working with default_storage.open(response, 'w+') as csv_file: writer = csv.writer(csv_file) writer.writerow(['First row', 'Foo', 'Bar', 'Baz']) writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) log.info(writer) -
Django: right-align output in admin listview
How can I output a DecimalField right-aligned in Django admin listview? It makes much more sense to have column of, say, prices, right-aligned. I tried this: django align right cannot align, but it doesn't work, presumably, because it doesn't change the output behaviour. -
how to check if I got the right function
I have a model that has 2 foreign keys, therefore I also have a function in view which has to get one of 2 different functions. That's what I want to verify and I wonder how it is possible? models.py class HotelFacilities(models.Model): name5 = models.ForeignKey(HotelSingleRoom, related_name='name', on_delete=models.CASCADE, blank=True, null=True) name_5 = models.ForeignKey(HotelDoubleRoom, related_name='name_2', on_delete=models.CASCADE, blank=True, null=True) views.py @login_required def hotel_facilities(request, id): if request == 'HotelSingleRoom.objects.get(id=id)': hotel = HotelSingleRoom.objects.get(id=id) else: hotel = HotelDoubleRoom.objects.get(id=id) form = HotelFacilitiesForm() if request.method == "POST": form = HotelFacilitiesForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.name5 = hotel data.save() return redirect('hotel:photos', data.id) context = {'form':form,} return render(request, 'hotel/facilities.html', context) I just tried this and of course it is not working... :) -
Django overriding the save method gives error
Disclaimer, I'm still new to a lot of concepts in Django so patiance please. So what I'm trying to do is the value of name from Counter model, assign it to the value of code from Order model. In the counter, I run a function that checks if the code year is 2020, then it gets me a value and concatinates that to make up the name of the Counter. Now when I run this code, it all fills up and instead of getting a value for the code, i get this as the value: django.db.models.query_utils.DeferredAttribute object at 0x04388250> Furthermore, I did some debugging, and when I ran a debug line on the save method in the Order model, it gave me this: queryset = {NameError}name 'queryset'is not defined. But I'm not sure what I need to do exactly. Any help would be appreciated, thanks. class Order(model.Models): code = models.CharField(unique=True) code_year=models.IntegerField def save(self, *args, **kwargs): self.code = Counter.name super().save(*args, **kwargs) class Counter(models.Model): name = models.CharField(max_length=10) value = models.IntegerField def save(self, *args, **kwargs): if Order.code_year == 2020: try: c_2020 = Order.objects.latest('id').id + 1 except Order.DoesNotExist: c_2020 = 1 self.value = c_2020 temp_value = f"P - {c_2020} - 2020" self.name = temp_value … -
Unable to put spacing between rows in Bootstrap while using Django framework
I've read a lot of answers and tried their solutions but nothing seems to work. Here is my code. I've tried using mt-10, row-padding and other custom css using margin-top:10. But nothing works.The image shows no space between rows using mt-10 {% block content %} {% for playlist, progress in user_playlists.items %} <div class="row justify-content-between rounded m-auto"> <div class="col-6 m-auto"><a> {{playlist}}</a></div> <div class="col-6 m-auto"><a>{{ progress }}</a></div> </div> {% endfor %} {% endblock %} -
How to cache a dictionary in Django?
I am using Django as my Webframework. I have a method that takes really long ~10 sec to complete. It returns a Dictionary which I then display in the templates. This method is called on a POST request after a button click. When the user reloads the page the View gets a GET request and all the results from before dont get displayed anymore. How can I somehow cache the Dictionary so I can even display it on a get request when the user once did the POST request? -
Docker django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution
Seems like a common error. I followed every possible suggestion on Stackoverflow(adding links, network etc), but it makes no difference in my case. I am running on Windows. My Dockerfile: #Pull base image. FROM python:3.9.5-slim #Usefull to get logs ENV PYTHONUNBUFFERED 1 #Make local dir RUN mkdir -p /app #set as the working directory WORKDIR /app #https://luis-sena.medium.com/creating-the-perfect-python-dockerfile-51bdec41f1c8 COPY requirements.txt . #now copy all the files in this directory to \code ADD . . #https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/ RUN apt-get update && \ apt-get install -y postgresql-server-dev-all gcc python3-dev musl-dev && \ pip install -r requirements.txt && \ adduser --disabled-password --no-create-home app USER app #CMD python manage.py runserver CMD gunicorn --bind 0.0.0.0:8000 app.wsgi:application -k eventlet Next, my docker-compose.yml: services: web: build: . ports: - "8000:8000" volumes: - .:/app links: - db:db container_name: heritageapi_web_1 depends_on: - db networks: - heritage-network db: image: postgres:13.3 container_name: db restart: always networks: - heritage-network environment: POSTGRES_DATABASE: admin POSTGRES_USER: root POSTGRES_PASSWORD: root POSTGRES_ROOT_PASSWORD: root volumes: - .dbdata:/var/lib/postgres ports: - "32768:5432" networks: heritage-network: driver: bridge My .env: DB_NAME=admin DB_USER=root DB_PASSWORD=root DB_HOST=db DB_PORT=5432 Finally my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), } } -
(python) Github Actions test selenium copy paste
I am testing my python application with e2e tests and use github actions as part of my CI. Normal selenium tests work totally fine. I added a click to copy functionality and want to test it via a unit test. So far I am using pyperclip to do this: import pyperclip link = pyperclip.paste() assert link == "target link" Locally on my machine (OSX) everything works fine. Unfortunately, I am not able to get this library working with ubuntu on github actions. I get this error: Pyperclip could not find a copy/paste mechanism for your system. Please see https://pyperclip.readthedocs.io/en/latest/introduction.html#not-implemented-error for how to fix this. I've checked the page but I am not able to get it working. Does someone know a way how to access the clipboard in github actions?