Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django NoModuleFoundError occurs only when adding a valid path to urls.py of my project folder
I have set up a Django project according to Victor Freitas' excellent post on production ready Django boilerplate here https://simpleisbetterthancomplex.com/tutorial/2021/06/27/how-to-start-a-production-ready-django-project.html It took me a day to refactor my whole project with 7 apps to fit into that boilerplate. All was fine and with everything working until I started developing my urls paths and templates. For some reason when adding a url path to main urls.py file within the main project folder Django fires me a NoModuleFoundError stating 'ModuleNotFoundError: No module named 'categories' . Categories is the name of my app and it is properly installed in base.py config file. Code below: # SIGP3A/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # path('categories/', include('categories.urls')), # <-- THIS LINE RIGHT HERE ] If I uncomment the above pointed line I get the error message. If I comment it out it passes Django checks. See bellow bits and pieces of the code that I believe are relevant to the question: # SIGP3A/Comps/categories/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.categories, name='categories'), ] See below my installed apps where categories is included. Note Comps is INSIDE main project folder and it is … -
In Django I use request.POST and return JSONResponse but the url shows HttpResponse error. I don't want to use render
I'm using Ajax to submit a POST. In views.py I have the following: def color(request): if(request.POST.get('result_data',False)): mylist= request.POST['mydata'] mylist= listt.split(",") request.session['var1'] = mylist[0] request.session['var2'] = mylist[1] return JsonResponse({'success':True}) In url I defined color/, so when I go to localhost:8000/color it shows error: "didn't return an HttpResponse". I should use instead return render(request,'app/color.html',{}) but I do not have a color.html file. I actually don't want to have one. All I want is to post a variable and use it as a session, so how can I avoid using render() and creating the html file? Thanks -
How can i give the user 1 times permission to access the page
How can i give the user 1 times permission to access the page(like a exam page). There is a one problem. When i resize page, its must be reload. Also when he goes to another page couldnt return the exam page like with back button or try to return from url. like a page -> b page x- a page -
Migrating Data from old Database to new one
i am currently building a new version of a web application and i got an existing database. Now i want to have a new database for the new version, since the existing database is not quite optimal. I can't alter the old one tho, since it's currently still used in production. Can i somehow build a new database table and fill it with altered versions of data from the old one? For example lets imagine i got an old model: class UserNumbers(model.Model): id=models.IntegerField(primary_key=True) name=models.CharField(max_length=50, blank=True, null=True) phone_number1=models.CharField(max_length=50, blank=True, null=True) phone_number2=models.CharField(max_length=50, blank=True, null=True) phone_number3=models.CharField(max_length=50, blank=True, null=True) and want to populate my new model: from phone_field import PhoneField class User(model.Model): id=models.IntegerField(primary_key=True) name=models.CharField(max_length=50, blank=True, null=True) class UserNumbers(model.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) phone_number = PhoneField(help_text='Contact phone number') comment = models.CharField() so is there some way like: for data in UserNumbers_old: User_new(id=data.id,name=data.name).save() if data.phone_number1: UserNumbers_new(user_id=data.id,phone_number=data.phone_number1,comment="") ... -
Django Redirect URL that shows in Address Bar
Happy Friday, everyone, How would I be able to use a Django redirect to where it would catch mixed-case URLs and redirect to the page that matches the lowercase version of what the end-user had in their request URL. For example, having "http://www.acme-co.com/Acme" redirect to "http://www.acme-co.com/acme". We are using a CMS system that dispatches the incoming request to match one of the "Pages" in their Page model, so coding the view with lower() or another function to intercept the parameter is not an option (so I believe). Even in a situation like that one, how do I have the URL also change in the address bar, as well, versus just redirecting them to the proper view? I believe I've found where the request address comes in and have been successful in redirecting incoming requests (though I imagine with the expertise of this forum, someone probably has a better way and more efficient of accomplishing the same thing, so will graciously accept any advice) and I'm stuck on changing what's in the address bar. Thank you in advance. -
One membership for each user for each club
I'm creating models to manage clients and sports centers. Each customer can be enrolled in several centers only once of course. how should i proceed for this? class Membership(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='memberships') club = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='memberships') points = models.PositiveIntegerField(default=0, blank=True, null=True) sub_date = models.DateField(auto_now_add=True) #other... If I proceed in this way it is possible to create multiple subscriptions of the user to the same club. How can I solve the problem? -
django form not saving despite success message
I have been trying to teach myself something new this week by following various tutorials on Google APIs. I am hitting a wall on the form saving bit, so helping you can help. Basically, I am trying to offer user the possibility to enter their first line of address for Google to then submit suggestions of addresses. This first bit works (when I enter the first line of an address, I get generated a list of suggestions). However, when I am trying to save the form, this doesn't seem to be saved anywhere. And I am not getting any error message either (if anything I am getting the a "success message" I am supposed to receive when the form is successfully submit). I thought there might be a field that is not getting being populated in the html. So I tried to empty one and tried to save. But on this occasion I received an error message, saying the field is missing. Which makes me thing this hasnt anything to do with the fields in the form but probably how I save my form in the views.py. I must admit I am way out of my comfort zone here (this … -
How to get post argument in django?
I am a complete beginner when it comes to web development. What I want to do is receive a command from the frontend and then print it in the backend to then use it for something else (that I haven't made yet). For the frontend, I use vuejs and send a post request to my django backend using axios like that: const send= {cmd:"cmd"}; axios.post('http://127.0.0.1:12345/app/', send).then(response=>this.rep=response.data); For my backend, here is the app.urls: urlpatterns = [ path('', views.test1, 'cmd', name='test1'), ] and my app.views: from rest_framework.views import APIView from rest_framework.response import Response def test1(request, cmd): print(cmd) return Response("ok!") My problem is that when I do that, I receive an error; the backend receives the post but I get: kwargs.update(self.default_args) ValueError: dictionary update sequence element #0 has length 1; 2 is required "OPTIONS /app/ HTTP/1.1" 500 78701 I tried without the cmd in path('', views.test1, 'cmd', name='test1'), but I had another error saying: TypeError: test1() missing 1 required positional argument: 'cmd' Any idea as to what is causing this error and how I could resolve it? -
Razorpay says seller cannot accept payments in (Live mode)
Im trying to implement razor pay in live mode on a Django Project, on clicking pay button it shows availabe options to pay, but when i select a option and proceed it says this seller cannot accept payments razorpay_client = razorpay.Client(auth=(settings.RAZOR_KEY_ID,settings.RAZOR_KEY_SECRET))[This is my output image][1] def cart(request): l = len(Itemcart.objects.filter(uname=request.session['username'][0])) if request.session.get('username') and l >=1: CurrentUser = "" try: CurrentUser = request.session['username'][0] except: pass CheckOutPrice = 0 try: for each in Itemcart.objects.all(): CheckOutPrice = CheckOutPrice + int(each.icprice) except: print("Error! no cart data found for current user") currency = 'INR' callback_url = 'paymenthandler/' Totalamount = int(CheckOutPrice * 100) razorpay_order = razorpay_client.order.create(dict(amount=Totalamount,currency=currency,payment_capture='0')) razorpay_order_id = razorpay_order['id'] context = {} context['razorpay_order_id'] = razorpay_order_id context['razorpay_merchant_key'] = settings.RAZOR_KEY_ID context['amount'] = Totalamount context['callback_url'] = callback_url return render(request,'cart.html',context=context) return render(request,'cart.html') def paymenthandler(request): print("123") if request.method == "POST": try: # get the required parameters from post request. payment_id = request.POST.get('razorpay_payment_id', '') razorpay_order_id = request.POST.get('razorpay_order_id', '') signature = request.POST.get('razorpay_signature', '') params_dict = { 'razorpay_order_id': razorpay_order_id, 'razorpay_payment_id': payment_id, 'razorpay_signature': signature } # verify the payment signature. result = razorpay_client.utility.verify_payment_signature( params_dict) if result is None: amount = Totalamount try: # capture the payemt razorpay_client.payment.capture(payment_id, amount) # render success page on successful caputre of payment return render(request, 'paymentsuccess.html') except: # if there is … -
Why does my like button return a Json object { liked: true } but doesn't work with my ajax call in Django when a user clicks the like button
I have been trying to create a like button with calling an ajax function in Django, But somehow whenever i click on the like button it redirect me to different page with a json object that return {liked : true }. why am getting this issue! it's been a challenge for me to figure it out and does it having any thing to do with my javascripts or with my function in views.py how better can i do this to stop the effect! and make the page not to reload when users like! Here's my like function! def like(request, pk, c_slug=None): user = request.user if request.POST.get("operation") == "like_submit" and is_ajax(request=request): liked=get_object_or_404(Like,pk=pk) product = Product.objects.get(pk=pk, slug=c_slug) liked= False like = Like.objects.filter(user_like=user, product=product) if like: like.delete() else: liked = True Like.objects.create(user_like=user, product=product) resp = { 'liked':liked, } response = json.dumps(resp) return HttpResponse(response,content_type = "application/json") model.py class Like(models.Model): user_like = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_likes', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='user_likes', on_delete=models.CASCADE) like_date = models.DateTimeField(auto_now=True) This is my scriepts for ajax call <script> $(".like").click(function (e) { var id = this.id; var href = $('.like').find('a').attr('href'); e.preventDefault(); $.ajax({ url: href, data: {'liked': $(this).attr('name'), 'operation':'like_submit', 'csrfmiddlewaretoken': '{{ csrf_token }}'}, success: function(response){ if(response.liked){ $('#likebtn' + id).html("Unlike"); $('#likebtn' + id).css("color", "gray") } … -
How can a refresh_from_db and a manual get differ?
I am currently working on a project I am not very familiar with and trying to remove all of the mentioned reload methods which look like this: def reload(self): return self.__class__.objects.get(pk=self.pk) As they were added when refresh_from_db wasn't in Django yet, they are all over the place and used to get an updated model from the database. Changing the method to def reload(self): self.refresh_from_db() return self should in my understanding produce the same output. However when running the tests they fail because there are apparently changes. What I already investigated is if the refresh_from_db method is overwritten, but the model is a regular django.models.Model. -
cannot GET objects from database Django
i cannot get objects from my database. i'm getting nothing. in terminal i'm not getting error and i'm entering on website without problem. i want get information from . DT = Destination_Tour.objects.all() my Views.py def index(request): min_date = f"{datetime.now().date().year}-{datetime.now().date().month}-{datetime.now().date().day}" max_date = f"{datetime.now().date().year if (datetime.now().date().month+3)<=12 else datetime.now().date().year+1}-{(datetime.now().date().month + 3) if (datetime.now().date().month+3)<=12 else (datetime.now().date().month+3-12)}-{datetime.now().date().day}" citynames = Place.objects.all() slider = Slider.objects.all() DT = Destination_Tour.objects.all() if request.method == 'POST': origin = request.POST.get('Origin') destination = request.POST.get('Destination') depart_date = request.POST.get('DepartDate') seat = request.POST.get('SeatClass') trip_type = request.POST.get('TripType') citynames = Place.objects.all() if(trip_type == '1'): return render(request, 'base.html', { 'origin': origin, 'destination': destination, 'depart_date': depart_date, 'seat': seat.lower(), 'trip_type': trip_type, 'name':citynames, }) else: return render(request, 'base.html', { 'min_date': min_date, 'max_date': max_date }) context = { 'name':citynames, 'sd': slider, 'DT' : DT, } return render(request,'base.html', context = context) -
How to work with xml's in a request django
Is there a way I can work with files in a request on django? My app is going to allow users to upload XML files, to which I want to use XML minidom to parse them and then post the data into the db. is there a way I can do this without saving the uploaded file locally? -
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?