Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot translate errors on Django
I've already set <p>{% trans "Remember" %}</p> on template, XXX.mo are done, and using from django.utils.translation import ugettext_lazy as _ on the errors And when I change the language (due to dropdown) it is not changing... Did i forget some change? Thank you -
How to use django-filter on RawQuerySet?
i have a problem. The error is this AttributeError at /tracker/ 'RawQuerySet' object has no attribute 'all' This is because i am using django-filter on a raw query set from sql query (i cannot use django filtering) this is the code i am having problems with: def track1(request): sql = """ select 1 as id, p.name project, i.title issue, u.name, replace(ROUND(t.time_spent/3600.0, 1)::text, '.', ',') as spent, TO_CHAR(t.spent_at + interval '2h', 'dd.mm.yyyy HH24:MI:SS') date_spent, substring(n.note for 300) note from issues i left join projects p on p.id = i.project_id left join timelogs t on t.issue_id = i.id left join users u on u.id = t.user_id left join notes n on n.id = t.note_id where (t.spent_at + interval '2h') between '2022-06-01' and '2022-06-30 23:59:59' order by 5, 1, 2 """ user_spent_on_project = UsersSpentOnProjects.objects.raw(sql) filter = UsersSpentOnProjectsFilter(request.GET, queryset=user_spent_on_project) user_spent_on_project = filter.qs context = { 'user_spent_on_project' : user_spent_on_project, 'filter' : filter } return render(request, 'trackApp/track1.html', context=context) Is there any way i could convert this raw query set to something that has Model.objects.all() -
I m Using python countries library and want to list and print total states and cities of given country using python is it possible to do it
def Contries(request): for country in pycountry.countries: list.append(country.name) if list: return JsonResponse( {"code": status.HTTP_200_OK, "success": True, "response": list}, status=status.HTTP_200_OK) else: return JsonResponse( {"code": status.HTTP_400_BAD_REQUEST, "success": False, "response":"list"}, status=status.HTTP_400_BAD_REQUEST) Is there any possibility to get the list of cities and states of given country using python -
Charts Not Shown While Running "index.html" In Django
I'm new to django and I just wanted to make some changes to my template file named "index.html" ... here is my scripts in "index.html" : <script src={%static "lib/jquery/jquery.min.js" %}></script> <script src={%static "lib/bootstrap/js/bootstrap.min.js" %}></script> <script src={%static "lib/php-mail-form/validate.js" %}></script> <script src={%static "lib/chart/chart.js" %}></script> <script src={%static "lib/easing/easing.min.js" %}></script> <script src={%static "js/main.js" %}></script> and charts in my templates are not shown when I run server ... Can anyone help me ? -
PrivateRoute Error: <Route> is only ever to be used as the child of <Routes> element, never rendered directly.Please wrap your <Route> in a <Routes>
When i used instead of , error arises [PrivateRoute] is not a component. So i use this solution which is also giving the above route error.Do i need to made changes in PrivateRoute.js PrivateRoute.js ''' import {Route, Redirect} from 'react-router-dom' const PrivateRoute= ({children, ...rest}) =>{ console.log('Private route works!') return( <Route {...rest}>{children}</Route> ) } export default PrivateRoute; '''' App.js ''' import './App.css'; import {BrowserRouter as Router, Routes,Route, Navigate, Outlet } from 'react-router-dom' import PrivateRoute from './utils/PrivateRoute' import HomePage from './pages/HomePage' import LoginPage from './pages/LoginPage' import Header from './components/Header' function App() { return ( <div className="App"> <Router> <Header/> <Routes> <Route exact path='/' element={<PrivateRoute/>}> <Route exact path='/' element={<HomePage/>}/> </Route> <Route exact path="/login" element={<LoginPage />} /> </Routes> </Router> </div> ); } export default App; ''' -
i am following the django tutorial and i am unable to start the deployment server
this is the code i am running in my pycharm terminal this is the code i am running in my pycharm terminal My browser just throws up a 404 error the 404 error please help -
I'm not able to connect postgrasql database into django and here the error?
'django.db.backends.postgresql.psycopg2' i isn't an available database backend or couldn't be imported. Check the above excepti. db\utils.py", line 126, in load_backendon. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is of:ne of: sn't an available database backend or couldn't be imported. Check the above exception. To use o 'mysql', 'oracle', 'postgresql', 'sqlite3 -
Object_list doesn't show the correct template
I have a Django project where users can ask questions and receiving answers. I have three models: Question, Answer and Comment. I don't know why comment template doesn't show the correct data, I dont't hnow where to find the comment data either object.comment, object.comment_set.all or anything else. I had the same problem with fetching Answer data, but I successfully solved it by using '{% for answer in object.answer_set.all %}', but the same method doesn't apply in comment. I noticed that I don't understand where is all the information stucks to retrieve. I'm relatively new to Django, so I'd be grateful to get all answers with description, why am getting this to avoid this in the fitire projects. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=250) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") detail = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', kwargs={'slug': self.slug}) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) detail = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.detail class Comment(models.Model): answer = models.ForeignKey(Answer, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comment_user') detail = models.TextField(default='') date_posted = models.DateTimeField(default=timezone.now) views.py class AnswerView(ListView): model = Answer template_name = 'forum/detail.html' class … -
NGINX 94134#94134 upstream prematurely closed connection while reading response header from upstream - Django, Ubuntu
When a user in my Django application installed on Ubuntu from DigitalOcean (v18+) selects multiple files to send on server, they see below error: 502 Bad Gateway nginx/1.18.0 (Ubuntu) I checked the application logs showing the following error: 2022/08/05 11:13:38 [error] 94134#94134: *108 upstream prematurely closed connection while reading response header from upstream, client: 31**.***,***.23, server: 15**.***.***2, request: "POST /profil/galrtia/apartment-rent/1/ HTTP/1.1", upstream: "http://unix:/home/app/run/gunicorn.sock:/profil/galrtia/apartment-rent/1/", host: "1***.***.***2", referrer: "http://15**8.***.***82/profil/galrtia/apartment-rent/1/" The error occurs after about 3-4 seconds of uploading files to the server. I tried to increase the limits in my NGINX configuration of files and timeout but no results (I still see the error). My configuration looks like below: upstream app_server { server unix:/home/app/run/gunicorn.sock fail_timeout=0; } server { listen 80; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) server_name 1**.**.***.**2; keepalive_timeout 10000; client_max_body_size 10G; access_log /home/app/logs/nginx-access.log; error_log /home/app/logs/nginx-error.log; # Compression config gzip on; gzip_min_length 1000; gzip_buffers 4 32k; gzip_proxied any; gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css; gzip_vary on; gzip_disable "MSIE [1-6]\.(?!.*SV1)"; location /static/ { alias /home/app/static/; } location /media/ { alias /home/app/app/app/media/; } # checks for static file, if not found proxy to app location / { try_files … -
Django: One url for multiple parameters
I am trying to implement a url that can handle multiple parameters. For example: if i want to get the project with id 1 => project/1 if i want to get the project with id 2 => project/2 if i want to get the project with id 1 and 2 => project/1/2 if i want to get the project with id 1, 2, and 3 => project/1/2/3 Is there any way I could implement this logic without hard coding N urls for N possibilities? -
docker-compose django and postgres connection error
I'm trying to make a django microservice with postgres database. and I have a problem which I cant solve it for few days. the docker-compose.yml looks like: version: "3.9" services: # Redis redis: image: redis:7.0.4-alpine container_name: redis # rabbit rabbit: hostname: rabbit image: "rabbitmq:3.10.7-alpine" environment: - RABBITMQ_DEFAULT_USER=admin - RABBITMQ_DEFAULT_PASS=mypass ports: - "15672:15672" - "5672:5672" mongodb_container: image: mongo:5.0.10 ports: - "27017:27017" depends_on: - redis # Main Database Postgres # it should be same as ${DB_HOST} main_postgres_ser: image: postgres:14.4-alpine volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB= postgres # NAME - POSTGRES_USER= postgres # USER - POSTGRES_PASSWORD= postgrespass # PASSWORD container_name: postgres_container restart: always ports: # - 8000:8000 # HTTP port - 5432:5432 # DB port networks: - djangonetwork depends_on: - rabbit # Main Django Application main_django_ser: build: context: . #/main_ms dockerfile: Dockerfile_main_ms container_name: main_django command: "python manage.py runserver 0.0.0.0:8000" environment: PYTHONUNBUFFERED: 1 ports: - 8000:8000 volumes: - .:/main_ms networks: - djangonetwork depends_on: - main_postgres_ser - rabbit links: - main_postgres_ser:main_postgres_ser networks: djangonetwork: driver: bridge volumes: main_postgres_ser: driver: local the Dockerfile for django service looks like: FROM python:3.10.6-buster ENV PYTHONUNBUFFERED=1 RUN apt-get update -y RUN apt-get update && \ apt-get -y install sudo WORKDIR /main_ms COPY requirements.txt ./main_ms/requirements.txt RUN pip3 install -r ./main_ms/requirements.txt and in … -
How to run Django server constantly on windows
I wrote a code for a Django server, and it works perfectly inside the shell of Pycharm. Now, I want to run this server on a local computer constantly without being inside Pycharm's shell. Also, because it's for a client of mine I don't want any open CMD windows or any other weird GUI- I want him to just access the website like any other website. I've seen all kinds of solutions- running runserver with &, creating a virtual machine and running the server on it and etc. I am familiar with Vmware and all, so if the proper solution is this It's OK. But I wonder- are there any other ways to run a server on a PC without installing any additional programs? -
Django object level permission using default auto-created model permissions
By default, Django adds 4 permissions for each registered model: add_modelname change_modelname delete_modelname view_modelname When a user has one of these permissions it applies to all instances of that model. That's not what I want, I want per instance permission. When the creator (created_by in database, or some related table of users with access) has delete_modelname permission he can delete only that instance, and not some other created by another user. I've been looking at other answers and none of them mention the auto-created CRUD permissions that are created for all models, it's mostly new tables or third-party libraries. What about giving creators of models these permissions (add, change, delete, view) which normally would give them access to all other models, but also having a custom auth backend which checks the object: from django.contrib.auth.backends import BaseBackend class ObjectPermissionBackend(BaseBackend): def has_perm(self, user_obj, perm, obj=None): if not obj: return False return obj.created_by == user_obj.pk # or something like this And then using it: AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend', 'path.to.ObjectPermissionBackend'] Is there some downside to this? -
How to pass Dynamic Value in Html anchor tag using Python Django
I am working on Cuckoo Sandbox and I hope that everyone will understand my question as It is going difficult for me to explain the question. I am working on different files and I am facing some issues. The issue is that I want to call dynamic variable in html anchor tag in Django, but, when I pass the dynamic variable the sidebar disappears automatically. I need your help guys: urls.py file url(r"^(?P<task_id>\d+)/$", AnalysisRoutes.redirect_default, name="analysis/redirect_default"), routes.py file: @staticmethod def redirect_default(request, task_id): if not isinstance(task_id, (unicode, str)): task_id = str(task_id) return redirect(reverse( "analysis", args=(re.sub(r"\^d+", "", task_id), "summary")), permanent=False ) include.html file: <li> <a href="{% url 'analysis/redirect_default' 45 %}"> <div class="parent-icon"><i class='bx bx-home'></i> </div> <div class="menu-title">Summary</div> </a> </li> In HTML file you can see that there is a int number 45. Just need to parse task_id dynamic value in html anchor tag. When I pass task_id variable in replace of 45 the sidebar disappears automatically. Kindly help me to resolve this issue. Thank you -
Jr Python Developer
I know that it is a silly question but how to get a job in the software developer position field? it has been 5 months since I have been learning Django and rest-framework. and I created an E-Commerce website project and still working on it. but I do not how to get a job, every time I apply for a job, it rejects. -
Extending django user model with one to one relation
Im very new to dajngo , im trying to get some more data from user and insert them in profile table my model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True,null=True) location = models.CharField(max_length=30, blank=True,null=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() my form from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from users.models import Profile class UserRegistrationForm(UserCreationForm): first_name = forms.CharField(max_length=101) last_name = forms.CharField(max_length=101) email = forms.EmailField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] class ProfileForm(forms.ModelForm): class Meta: model = Profile fields=['bio','location','birth_date'] and my view def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, 'Your profile was successfully updated!') return redirect('home') else: messages.error(request,'Please correct the error below.') else: user_form = UserRegistrationForm() profile_form = ProfileForm() return render(request, 'users/register.html', { 'user_form': user_form, 'profile_form': profile_form }) When i try to save the form i get the error django.db.utils.IntegrityError: NOT NULL constraint failed: users_profile.user_id I know this is because im calling save … -
How to perform annotation in Django model with a many to many relationship?
I have two Django models called Restaurant and RestauranCategory. The Restaurant model has a many-to-many relationship to RestaurantCategory. Please refer to the attached sample model instances. class RestaurantCategory(BaseModel): name = models.CharField(max_length=150) description = models.TextField() class Restaurant(BaseModel): name = models.CharField(db_index=True, max_length=128) is_partner = models.BooleanField(default=True) category = models.ManyToManyField( RestaurantCategory, related_name="restaurant_categories", blank=True, db_index=True, ) Now what I need to do is to perform an annotation from RestaurantCategory to have a new column called restaurant_names and assign a single string that contains all the related restaurants' names. I have added a similar thing that I need to do, new_data = RestaurantCategory.objects.all().annotate( restaurant_names=<should contain all the restaurant names in a single string> ) Is that possible to achieve with annotating? If not what are the options that we can use? I have gone through this StackOverflow question and wasn't able to good idea regarding my issue. -
script.js file location.iataCode failed
In the example made with django on the Amadeus blog page, when writing the script.js file, in the onclick="getLocation(\\'' +location.iataCode+'\\')"> field; I'm getting the error when I look at the codes in the example, it's exactly the same as the code, can you help with this? I'm leaving the script.js file below const toLocationData = document.getElementById("toLocationData"); function handleToLocation(){ let locationE1 = ""; const toInput = document.getElementById("to").value; if(toInput.length >1){ fetch('/api/v1/flight/select_destination/${toInput}').then((response) => response.json()).then((data) => (toLocationArray = data.data)); if(toLocationData) { toLocationData.style.display = "block"; toLocationArray.map((location) => {locationE1 += '<div class="card mb-3 mt-3" onclick="getLocation(\\\\'' +location.iataCode+'\\\\')">\\\\<div class="card-header"><b>Name:<b> ' + location.name + '</div>\\\\ <div class="card-body">\\\\ City Name:' + location.address.cityName + "\\\\ <br />\\\\ Country Name:" + location.address.countryName + '\\\\ </div>\\\\ <div class="card-footer">\\\\ <b>SubType:</b>' + location.subType + "\\\\ </div>\\\\ </div>"; }); } } toLocationData.innerHTML = locationE1; } function getLocation(regionCode){ destinationCode = regionCode; toLocationData.style.display = "none"; } -
No post request with invalid information
in forms.py I have a basic form with 2 fields: class TestForm(forms.Form): name = forms.CharField(max_length=20) email = forms.EmailField() in views.py I just render this form through: def test_form(request): return render(request, 'form.html', {'form':TestForm}) than base.html {% load static %} <head>Testsite</head> {% block content %} {% endblock content %} than form.html {% extends 'base.html' %} {% block content %} <h1>Test!</h1> <form action="" method="post">{% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> {% endblock content %} The problem arises when I click the submit button. When all my information is valid(an @ in mail) a post request gets made and i can retrieve the data with some extra code in the view. But when the information is not valid: no @gmail.com for example this post request doesn't get made. How do I fix this? -
Trying to call .xlsx data in python selenium script 'Object of type Series is not JSON serializable'
This code reads the .xlsx file and collect the mobile number of the user to send message def watbot(request): if request.method == 'POST': file_name = request.POST.get("filename") pre = os.path.dirname(os.path.realpath(__file__)) f_name = file_name path = os.path.join(pre, f_name) f_name = pandas.read_excel(path) count = 0 driver = webdriver.Chrome(executable_path='D:/Old Data/Integration Files/new/chromedriver') for column in f_name['Contact'].tolist(): try: driver.get('https://web.whatsapp.com/send?phone=' + str(f_name['Contact'][count]) + '&text=' + f_name['Messages'][[0]]) sent = False # It tries 3 times to send a message in case if there any error occurred try: sleep(3) click_btn = driver.find_element(By.XPATH, '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[2]/button/span') except Exception as e: print("Sorry message could not sent to " + str(f_name['Contact'][count])) else: sleep(1) click_btn.click() sent = True sleep(2) print('Message sent to: ' + str(f_name['Contact'][count])) count = count + 1 except Exception as e: print('Failed to send message to ' + str(f_name['Contact'][count]) + str(e)) return HttpResponse('messeges') Failed to send message to 7976583223 Object of type Series is not JSON serializable I don't what is wrong with the code as I already tried json.dump() method -
Django aggregate sum of currency (string) + value (float)
I have been doing some calculations using aggregate sum like this: total_value = myModel.objects.aggregate(sum=Sum('price')) The problem is that the field values changed and now instead of floats, the field price is a charfield containing a currency + value. Example: ID price 1 USD 34.33 2 USD 64.33 Expected result: total_value = USD 34 + USD 64 = USD 98.66 What I've tried: I tried to do the sum of price fields ignoring the first 4 characters like this: total_value = myModel.objects.aggregate(sum=Sum('price'[4:])) unfortunately my idea doesn't work. Any help will be highly appreciated -
How to use KafkaConsumer with Django4
I have a Django 4 project and using KafkaConsumer from kafka-python. I want to update django models after receiving a Kafka message. The goal here is to have some Kafka worker running and consuming message, it is also should able to have access to the models in the existing django ASGI app. Is it possible or should this worker be a separate django project? -
DjangoRestFramework: Unit Testing AssertionError: 404 != 200 while Test update
I've started writing unit tests for my API's but am stuck while updating user details received an assertion error of 404!=200. I'm sharing mycode for the reference. Please do let me know my mistake and a brief explanation as I'm new to django rest. I've created only one class "class TestUser(APITestCase):" for testing 2 API is it fine as I'm extending the URL in the update client patch? models.py mport email from pyexpat import model from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser) GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) class UserManager(BaseUserManager): def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None): """ Creates and saves a User with the given email, name and password. """ if not email: raise ValueError('User must have an email address') user = self.model( email=self.normalize_email(email), name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None): """ Creates and saves a superuser with the given email, name and password. """ user = self.create_user( email, name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, password=password, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): … -
Integrate Django with Spring Boot
I'm using gRPC microservices. The backend is built on Spring Boot connected with the Mongo database. The front end is implemented on the Django framework. Can you help with how to connect Django with Spring and pass the CURD operations? Thanks Bhavesh Asanabada -
Django ORM queries
I've these tables: class ContestQuestions(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name='contest_question_contest') quetions = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='contest_question_questions') class UserResponse(models.Model): user = models.ForeignKey(User, on_deleted=models.CASCADE, related_name='user_response') response = models.ForeignKey(Answer, on_delete=models.CASCADE, related_name='user_answer') Other related tables I've: class Contest(models.Model): name = charfield date = charfield is_active = bool class Question(models.Model): title = charfield created_at = datetimefield class Answer(models.Model): question = FK(Question) answer = charfield #4 options of 1 question is_true = bool I need to get some stat about every quiz. So from every quiz, I want to know the top 5 most correctky answered questions and most incorrectly answered questions and total number of people who attempted that question. How can I write a query for it?