Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implement jquery in a slider that uses dynamic data
I am trying to add a slider with dynamic data to my django project using jquery and ajax to do it, I recieved help to make the previous and next button wich gives the avility to swipe throw profiles but I am now focusing on the previous one, in the process I realized that there is a NoReverseMatch error in the code and I dont know how to fix them because I am very new at jquery and ajax. If there are any questions please let me know in the comments;). views.py def matesmain(request): contents = Mates.objects.all() context = { 'contents': contents, 'form_mates': MatesForm(), } print("nice3") return render(request, 'mates.html', context) def previous(request): id= request.GET.get("id", None) if id != 1: previous_id= id-1 prev_user= Mates.objects.filter(user= previous_id) data={ "username": prev_user.user, "req_bio": prev_user.req_bio, "req_image": prev_user.req_image, } return JsonResponse(data) models.py class Mates(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usermates') users_requests = models.ManyToManyField(User, related_name="users_requests") req_bio = models.CharField(max_length=400) req_image = models.ImageField(upload_to='requestmates_pics', null=True, blank=True, default=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png') bio = models.CharField(max_length=400, default=1, null=True) connection = models.CharField(max_length = 100, blank=True) follower = models.IntegerField(default=0) following = models.IntegerField(default=0) urls.py urlpatterns = [ path('mates', views.mates, name='mates'), path('mates-main', views.matesmain, name='mates-main'), path('previous', views.previous, name='previous'), ] html <div … -
Multiple App directories in the project folder
Dears, I was following the Django official tutorial to build a poll app. However, as I was learning, I tried to create other apps to practice some aspects of Django. In the end, my directory looks like this. Is it correct to organize directories this way? It seems to me that APP polls, generic_practice, practice are sharing the settings.py, urls.py, the database,etc. Any recommended reading material about organizing multiple apps in one project? -
Attribute Error while runserver command on Django Site
Any help would greatly be appreciated The browser gives me this error: AttributeError at /blog/ type object 'Post' has no attribute 'published' Request Method: GET Request URL: htp://mysite.com/blog/ (spelling errror on purpose) Django Version: 3.0.7 Exception Type: AttributeError Exception Value: type object 'Post' has no attribute 'published' Exception Location: /root/mysite/blog/views.py in post_list, line 4 Python Executable: /root/my_env/bin/python3 Python Version: 3.6.9 Python Path: ['/root/mysite', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/root/my_env/lib/python3.6/site-packages'] Server time: Tue, 30 Jun 2020 21:31:42 +0000 The server gives me this error Quit the server with CONTROL-C. Internal Server Error: /blog/ entTraceback (most recent call last): File "/root/my_env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/root/my_env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/root/my_env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/mysite/blog/views.py", line 4, in post_list posts = Post.published.all() AttributeError: type object 'Post' has no attribute 'publisheder code here I hate when I buy digital books (even the ones with good reviews or by established companies) and they don't work out well I got this from a sample of the django3 book by A. Mele. It would be nice if they gave you insight into the error you can get. -
Django Rest Framework & Angular Dev vs Prod string & byte issue on json.loads()
On releasing my site to staging server certain server calls have stopped working. They now need to be decoded utf-8. Backend is running Django Rest Framework, Frontend is Angular 9. I can't see why two similar setups on two different machines is causing such a random issue. Headers include settings the charset to utf-8 (below) headers = headers.set('Content-Type', 'application/json; charset=utf-8'); But this doesn't effect the dev server. Does anyone have any experience in this issue? -
how can i remove keyerror in my django views?
i am getting error in my views.py file on line 10. it says that keyerror:'nickname' i think i am calling the wrong key or something! if you want other code i can also attach that with it also Here is my code below if anyone can help me with it? here is my problem/views.py file from django.shortcuts import render from django.http import HttpResponseRedirect from problems.models import Problems from problems import utils # Create your views here. def showProblems(request): nickname = request.session['nickname'] problems = Problems.objects() return render(request, 'showProblems.html', locals()) def addProblem(request): return render(request, 'addProblem.html') def addProblems(request): return render(request, 'addProblems.html') def addProblemCheck(request): try: rawProblem = request.POST['problem'].strip('\r\n') rawOptions = request.POST['options'].split('\r\n') rawAnswer = request.POST['answer'].strip('\r\n') rawType = request.POST['type'] except: return render(request, 'info.html', {'info': '提交内容不完整', 'link': '/showProblems/'}) myID = IDGenerator().getRandomID() problem = Problems(myID = myID, problem = rawProblem, options = rawOptions, answer = rawAnswer, type = rawType) problem.save() return HttpResponseRedirect('/showProblems/') def addProblemsCheck(request): try: problems = request.POST['problems'] rawType = request.POST['type'] except: return render(request, 'info.html', {'info': '提交内容不完整', 'link': '/showProblems/'}) problems = problems.split('\r\n\r\n') #warning: this may be different in different browsers for problem in problems: arr = problem.split('\r\n') rawProblem = arr[0] rawAnswer = arr[-1] rawOptions = arr[1: -1] myID = IDGenerator().getRandomID() newProblem = Problems(myID = myID, problem = rawProblem, … -
Celery not connecting to RabbitMQ on AWS Elastic Beanstalk when deployed using Docker containers
I have 3 docker containers - my_django_app, rabbitmq, and celery_worker. I have implemented it on my local system using docker-compose.yml which is as follows: version: '3' services: web: &my_django_app build: . command: python3 manage.py runserver 0.0.0.0:8000 ports: - "80:8000" depends_on: - rabbitmq rabbitmq: image: rabbitmq:latest celery_worker: <<: *my_django_app command: celery -A MyDjangoApp worker --autoscale=10,1 --loglevel=info ports: [] depends_on: - rabbitmq When I run this on my local system, it works perfectly fine. And then I deployed these images to AWS Elastic Beanstalk (Multi container environment) using Dockerrun.aws.json which is as follows: { "AWSEBDockerrunVersion": 2, "Authentication": { "Bucket": "cred-keeper", "Key": "index.docker.io/.dockercfg" }, "containerDefinitions": [{ "Authentication": { "Bucket": "cred-keeper", "Key": "index.docker.io/.dockercfg" }, "command": [ "celery", "-A", "MyDjangoApp", "worker", "--autoscale=10,1", "--loglevel=info" ], "essential": true, "image": "myName/my_django_app:latest", "name": "celery_worker", "memory": 150 }, { "essential": true, "image": "rabbitmq:latest", "name": "rabbitmq", "memory": 256, }, { "Authentication": { "Bucket": "cred-keeper", "Key": "index.docker.io/.dockercfg" }, "command": [ "python3", "manage.py", "runserver", "0.0.0.0:8000" ], "essential": true, "image": "myName/my_django_app:latest", "memory": 256, "name": "web", "portMappings": [{ "containerPort": 8000, "hostPort": 80 }] } ], "family": "", "volumes": [] } I saw the logs for the 3 containers by downloading the logs from AWS Elastic Beanstalk, and the containers web as well as rabbitmq are … -
Django ORM vs PostgreSQL raw sql
I have my django app running on server 1 which is connected to Amazon RDS (PostgreSQL) present on server2. On a day-to-day basis, I have to interact with database often to write/fetch/query data. Currently, I am following the django ORM way across the app. I just wanted to know if there would be any improvement in the performance if I use PostgreSQL raw sql quereis using django.db connection cursor over ORM? Following are the proposed ways for one sample query. Django ORM table_name.objects().all() PostgreSQL raw sql quereis using django.db connection cursor Can someone please suggest which one of the above will lead to a faster increased in performance provided I have my database running on RDS in another server -
django selenium firefox webdriver only stores crsftoken
Just like the title explains. When I run tests using Django and selenium the firefox web driver only stores the csrftoken as a cookie but the sessionid and the django_language are not saved. Inside Firefox itself they were saved. -
Local vs. Global list in Django
I'm saving a list of values in Django using JSONField, taken from a daily survey. The List model is saving incorrectly whether I call it globally or locally in my views. Here is my model: class List(Model): score_list = JSONField(default=list) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True,blank=True) def __str__(self): return self.score_list class Answers(Model): responder = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True,blank=True) score = models.IntegerField(default=0) def __str__(self): return self.score While my Answers model is saving correctly, I can't figure out how to save the List model. Calling List globally (l = list()) in views.py leads to a single list shared amongst all users. Calling it locally creates a new list for every value that is added, instead of adding these values to a single list for each user. Here is views.py: @login_required def add(request): l = List() r = Answers() r.responder = request.user l.user = request.user if request.method == 'POST': selected_option = (request.POST['rating']) list_length = len(l.score_list) if selected_option == 'option1': r.score = 1 elif selected_option == 'option2': r.score = 2 elif selected_option == 'option3': r.score = 3 elif selected_option == 'option4': r.score = 4 elif selected_option == 'option5': r.score = 5 else: return HttpResponse(400, 'Invalid form') l.score_list.append(r.score) r.save() l.save() return redirect(add) context = { 'r' : … -
How to upload python script in django form and use it for some processing?
I want to upload python file through django form and read the function available inside and use it for processing. Till now what i had done is: Taken file from the user and saved in the media folder. taken function name (so that i can use it if required for calling funtion) Index.py <form method="POST" enctype="multipart/form-data" action="/result">Enter function name {% csrf_token %} <input type="text" name="functionname"><br> Upload your .py file here <input type="file" name="functionfile"> <input type="submit" value="Submit"> </form> views.py def result(request): if request.method == 'POST': functionname=request.POST['functionname'] functionfile=request.FILES['functionfile'] fs= FileSystemStorage() modulename=fs.save(functionfile.name,functionfile) url=fs.url(modulename) print(url) return render(request,'result.html') I don't have any clue how to use that the function of the uploaded file in the backend Desired result would be something like. for eg. example.py file contains a function def add(data): p=10+data return p i upload a example.py file suppose in background i have d = 100 django calls result=add(d) print the result any reference or resource will also be helpful. Thanks -
The best way to sort by custom index
I think about the best way to sort by index column. I have model: class ProductCategory(models.Model): name = models.CharField(_("Category name"), max_length=200) description = models.TextField() index = models.IntegerField(_("Index order"), default=0) def __str__(self): return self.name Can I set index on model level? In this case I would like let user to set order categories in menu. -
How do ASP.NET , ASP.NET Zero, ASP.Net Boilerplate and Django compare to each other?
Does anyone have experience in all of them? How do their features compare to each other and what are advantages and disadvantages of each of the frameworks (e.g. if you needed to set up a professional business project, which of those frameworks would you choose and why?) -
Can't log in after creating superuser in Django
I was following this tutorial: https://www.youtube.com/watch?v=F5mRW0jo-U4 (time: 31.00) where I ran into the error that i can't login at the admin page after creating a superuser through the command: python manage.py createsuperuser I have tried creating multiple superusers but for some reason it does not seem to work. When I use the command above everything goes as expected but whenever I try to enter the username and the password I only get the following response back from the server: "POST /admin/login/?next=/admin/ HTTP/1.1" 200 2014 Then the page asks me to "Please enter the correct username and password for a staff account.". But I never receive an error at any point during this and when I generate the superuser the response I get is that "Superuser created successfully." so everything seems to be in order. My Python version is Python 3.6.5 and django version is 2.0.7 and my OS is macOS Mojave. As nothing seems to indicate that something is wrong I don't understand why it doesn't work. -
Django model: How to avoid referencing the same record when using with 2 foreign keys from the same table
I have two Django models that look like this: class Team(models.Model): name = models.CharField(max_length=30) ... class Game(models.Model): teamA = models.ForeignKey(Team, on_delete=CASCADE, related_name='teamA') teamB = models.ForeignKey(Team, on_delete=CASCADE, related_name='teamB') .... Game model has 2 foreign keys to Team model. Of course, it is not possible for a team to play against itself, so I would like to prevent teamA and teamB from referring to the same record in DB. What is the best way to do this? -
Connecting postgres DB with heroku
During development, I used postgres DB where I had to pip install psycopg2. Most of my post I updated during the course of development was on postgres DB. Now during deployment, I discovered that a part of the installation when I did heroku push master is installing sqlite. Now my problem is, how can I deploy my postgres DB for development in heroku, knowing that most of my post on development are really important.. thanks -
formset_factory is located in formsets.py, so why call from django.forms?
Why is "from django.forms import formset_factory" used to import the "formset_factory" function when the function is located in django/forms/formsets.py? Wouldn't you have to import from formsets.py? -
Django 2/3 only one post_save generated celery signal received each time model is saved
I use multiple post_save functions to trigger different celery tasks and tried django 2 and 3. For some strange reason celery stopped executing all tasks in parallel instead only one task gets received each time model is saved. To run all the tasks, I have to save the model multiple times. It was working before and I have no idea why the behavior changed all of a sudden. I am starting the queue with: celery -A appname worker -l info -E My post save functions: @receiver(models.signals.post_save, sender=RawFile) def execute_rawtools_qc(sender, instance, created, *args, **kwargs): rawtools_qc.delay(instance.path, instance.path) @receiver(models.signals.post_save, sender=RawFile) def execute_rawtools_metrics(sender, instance, created, *args, **kwargs): rawtools_metrics.delay(instance.abs_path, instance.path) And my tasks: @shared_task def rawtools_metrics(raw, output_dir): cmd = rawtools_metrics_cmd(raw=raw, output_dir=output_dir) os.system(cmd) @shared_task def rawtools_qc(input_dir, output_dir): cmd = rawtools_qc_cmd(input_dir=input_dir, output_dir=output_dir) os.system(cmd) Before those tasks where executed in parallel as soon as the model was saved. Now, the first task gets executed when the model instance is saved, and the second instance is executed the second time the model is saved. And then the functions alternate each time. Any idea what may cause this strange behavior? UPDATE: I think both task are executed randomly, but only one for each save. -
How to fix cors error when loading static script served by Django runserver
I have installed django-cors-headers and added it to enabled apps and added the middleware to middleware settings as first middleware. I have also configured the settings: INSTALLED_APPS = [ ... "corsheaders", "rest_framework", "django.contrib.admin", ... ] MIDDLEWARE = [ ... "corsheaders.middleware.CorsMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", ... ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True My setup has 2 projects running on different ports. Django server running on 8000 and my front-end running on 8080. All API requests the front-end sends against back-end work just fine. But when I try to load one.js file served by the back-end project it fails with this error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/static/myscript.js. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing) The way I load the script is by creating a new script element and add the URL http://127.0.0.1:8000/static/myscript.js as value for the src attribute on the script tag. This error does not occur when I use a value like https://code.jquery.com/jquery-3.5.1.min.js instead of http://127.0.0.1:8000/static/myscript.js so it looks like there is some issue with static files being served by Django runserver, but what exactly and why is beyond me. I know that there is a bunch of cors related issues like Django CORS on … -
Django: Image from static folder doesn't load
I need help=) Image from static folder doesn't load. Version: Django 1.11.3 This is my code: first_project/first_project/settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR=os.path.join(BASE_DIR,"templates") STATIC_DIR=os.path.join(BASE_DIR,"static") ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app', ] ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS=[ STATIC_DIR, os.path.join(BASE_DIR,"first_app","static","first_app"), ] first_project/templates/first_app/index.html: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Yp</title> </head> <body> <h1>This is yp picture!</h1> <!--It works --> <img src="/static/first_app/yp.jpg" alt="oh oh"> <!--It doesn't work--> <img scr="{% static "first_app/yp.jpg" %}" alt="oh oh"> </body> </html> first_project/static/first_app/yp.jpg - the path to the image. Thank you! -
Django template reading individual keys from dictionary instead of iterating
I'm having trouble passing data from a Django model to a a Django template. The code below works, but I'm it seems clunky and I'm a bit confused by why it works. I'm trying to read a random entry from my database for each one of my models. I then want to print the data from each model on my home template. I thought I could add each model to a single dictionary, then iterate through the dictionary of dictionaries in my template, but that didn't work ( I know the models have different fields, but I was planning on working around that later). I played around with it for a while, and realized that my for loops weren't actually iterating through the dictionary of dictionaries, but was actually just reading each individual entry in the dictionary through its key. Additionally, it doesn't seem like the for loops are doing any iterating, since I can access the fields of my model directly with the .field notation. This seems to be the only method that works but I'm still not entirely sure why. Could anyone clarify why this works, or let me know if there is a more straightforward way of … -
Display total price in HTML template
I have a cart app. When I add products I want to find total price. But I cannot display in my template. But I display in console it shows true value. solved And I have a delete button when I click this I want to give alert with "Are you sure?" but it doesn't work. How can I fix it? solved views.py def cart_view(request): current_user = request.user carts = MedicineOnCart.objects.filter(cart__user=current_user) cart = Cart.objects.get(user=current_user) dictionary = {} for cart in carts: if cart.med in dictionary.keys(): dictionary[cart.med] += 1 else: dictionary[cart.med] = 1 new_total = 0.00 for item in MedicineOnCart.objects.all(): new_total += item.med.medicine_price cart.total = new_total cart.save() context = { "carts": dictionary, "user": current_user, } template = "cart.html" return render(request, template, context) template.html <td> Total: {{carts.total}} </td> <button class="btn btn-danger myButton" onclick="deleteMess()" > Delete </button> <script> function deleteMess() { alert("Are you sure?"); } </script> -
onclick auto-comments Google Analytics code on hyperlinks
I'm trying to add links on a web page on a Django app where I can track when the user clicks those outbound links on Google Analytics, as well as have the links open in a new tab. Right now, some links open alright in the same tab, and some links give a django error as the site tries to redirect to the page within the app (like this error). Above all, <li> <a href="https://www.moneysavingexpert.com/travel/" onclick="getOutboundLink('https://www.moneysavingexpert.com/travel/'); return false;" >MoneySavingExpert</a >: Travel-related personal finance advice! </li> The // after the https in the getOutboundLink that I've put in to track clicks on outbound links is being treated as a commend by VSCode, maybe I think because getOutBoundLink() is JavaScript? In any case, I don't think that code is working when I push to Heroku, and consequently no outbound click events are registering on Google Analytics. Getting the links to open in new tabs (tried _blank but I think I have to somehow change the onclick to make that work), and knowing why some links try to open the href within the app and thus give an error (despite the http/s being there in the href) is another question altogether, though I … -
built in methods for Django CBV's
I am learning Django out of pure passion and I seem to have trouble understanding some core principles of Django that really give me headackes and i tried searching online and reading the docs but i don't seem to fully understand. I'll just simply shoot the questions and try to be clear . I apologise for anything stupid I say . I am just trying to get my knowledge straight. 1. What is a "request"? OK, so I am thinking of a GET request for a webpage but online i see python code like self.request.user.is_superuser and i am thinking of an User object fetched and displayed to the template to which i can apply User methods. It is clearly more to this request than i already know. 2. CBV's built in methods. The get methodds. How do they execute? In wahat order. I noticed programmers override these methods sometime . If i redefine more than one method in a CBV i start getting weird behaviour. For example if i declare and redefine 2 methods in a Detail View get_object() and get_queryset() which of them will be executed first after calling the view? Being a method it should be called somehow … -
selenium.webdriver.firefox.options get language
It is possible to set the language when creating the WebDriver using add_argument('--lang=en'). But is it possible to read out the language of the WebDriver after it was created? -
Dynamic show message from zeromq(ZMQ) in Django
I am new to Django and ZMQ. I am developing a webapp. What I want is that there is a ZMQ client(sub, req or poll) which will get message from ZMQ server and then dynamicly show in web. I am not sure if it possible. I know probably I need to use AJAX. But does need to click some button to trigger it and then it can get messgae. Can I get a new message showing in web when I get message from ZMQ server? Thanks in advance