Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
form data getting displayed in url despite using http method post
i am learning django app development and have written a simple code to add two numbers. the form data is geting displayed in the url despite using http request method post. i dont want form data to be displayed in the url. Kindly help. views.py from django.shortcuts import render # Create your views here. def home(request): return render(request,'home.html',{'name':'pavan sunder'}) def add(request): val1 = int(request.POST["num1"]) val2 = int(request.POST["num2"]) res = val1 + val2 return render(request, 'result.html',{'result':res}) home.html <!DOCTYPE html> <html lang="en"> <body> {% extends 'base.html' %} {% block content %} <h1>hello {{name}}</h1> <form action="add" method='POST'> {% csrf_token %} Enter 1st number:<input type="text" name="num1"><br> Enter 2nd number:<input type="text" name="num2"><br> <input type="Submit"> </form> {% endblock %} </body> </html> results.html <!DOCTYPE html> <html lang="en"> <body> {% extends 'base.html' %} {% block content %} Result:{{result}} {% endblock %} </body> </html> ```[![formdata in url][1]][1] [1]: https://i.stack.imgur.com/YWQcD.png -
Displaying JSON Data from API in Django
I am looking for a simple way to display JSON values coming from an API in a Django project. I've got everything working to read the JSON data into an object and store as variables, etc. but I am wondering how to make a dynamic way to display the values from the JSON Object. Say for example the JSON looks like this { "status":"OK", "copyright":"Copyright (c) 2017 Pro Publica Inc. All Rights Reserved.", "results":[ { "num_results": 10, "offset": 0, "bills": [ { "bill_id": "hr2739-113", "bill_type": "hr", "number": "H.R.2739", "bill_uri": "https://api.propublica.org/congress/v1/113/bills/hr2739.json", "title": "Efficient Use of Government Spectrum Act of 2013", "sponsor_title": "Rep.", "sponsor_id": "M001163", "sponsor_name": "Doris Matsui", "sponsor_state": "CA", "sponsor_party": "D", "sponsor_uri": "https://api.propublica.org/congress/v1/members/M001163.json", "gpo_pdf_uri": "http://www.gpo.gov/fdsys/pkg/BILLS-113hr2739ih/pdf/BILLS-113hr2739ih.pdf", "congressdotgov_url": "https://www.congress.gov/bill/113th-congress/house-bill/2739", "govtrack_url": "https://www.govtrack.us/congress/bills/113/hr2739", "introduced_date": "2013-07-18", "committees": "House Armed Services Committee", "committee_codes": ["HSAS","HSIF"], "subcommittee_codes": ["HSAS26","HSIF16"], "primary_subject": "Science, Technology, Communications", "summary_short": "Efficient Use of Government Spectrum Act of 2013 - Directs the Federal Communications Commission (FCC), within three years after enactment of the Middle Class Tax Relief and Job Creation Act of 2012, to: (1) reallocate electromagnetic spectrum between the frequencies from 1755 to 1780 megahertz (currently, such frequencies are occupied by the Department of Defense [DOD] and other federal agencies); and (2) as part of the … -
Django admin : extending the existing user model. doesn't show in admin site
I'm a very beginner to Django. Using: Django 2.2.6 with python 3.6.3 Here is my problems with extending the existing user model. I've read this https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#extending-the-existing-user-model what I wanted to do is to use default auth. extends user model. see/manage the model I've extended in /admin However I cannot see what I extended in /admin. I've done the following: user.models.py: from django.db import models from django.contrib.auth.models import User class UserInfo(models.Model): user = models.OneToOneField(User, unique = True, verbose_name = '學號', on_delete = models.CASCADE) sNickName = models.CharField(max_length = 16, verbose_name = "暱稱") iArticleNumber = models.PositiveIntegerField(verbose_name = "文章數") # from 0 to 2,147,483,647 sShortIntroduction = models.TextField(verbose_name = "短自介") create an one to one model refer to User user.admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from user.models import UserInfo class UserInfoInline(admin.StackedInline): model = UserInfo can_delete = False verbose_name_plural = 'UserInfo' class UserAdmin(BaseUserAdmin): inline = [UserInfoInline, ] admin.site.unregister(User) admin.site.register(User, UserAdmin) add UserInfo in User And my /admin show like this: This page is the same as I did not add changes in user.admin.py. cannot find 'UserInfo' here. What I expect is when I click specific user, like '410431135' in picture, I can see and manage the 'UserInfo', … -
Customize a view handle POST and DELETE method in django rest framework
I created a View that can handle POST and DELETE method class MyView(APIView): def valid_method(self,data): method = self.request.method if method == 'POST': ser = self.PostSerializer(data=data) elif method == 'DELETE': ser = self.DeleteSerializer(data=data) else: raise MethodValidationError(errormessage) return ser def post(self, request): ser = self.valid_method(dara = request.data) other code def delete(self, request): ser = self.valid_method(dara = request.data) other code Is there any better way to implement MyView? Should I create a new base view? Or is there any simple way to define the legal HTTP method in APIView? -
AH01630: client denied by server configuration: /djangoDeployments
I am deploying a django application but I am having problems with the apache2 configuration. It gives me the error: AH01630: client denied by server configuration: /djangoDeployments I already folllowed some tutorials and tried implementing various ways that the documentation talks about Here is my conf file ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /djangoDeployments/tracker/printertracker> <Files wsgi.py> Require all granted </Files> </Directory> ServerName tracker.domain.com ServerAlias www.tracker.domain.com WSGIScriptAlias / /djangoDeployments/tracker/printertracker/wsgi.py WSGIDaemonProcess tracker python-home=/djangoDeployments/tracker/venv python-path=/djangoDeployments/tracker WSGIProcessGroup tracker I want to see it in the subdomain but when I am entering I get a 403 Forbidden access. -
How to have a stopwatch in django template?
I have a bunch of patients visiting a doctor in my WebApp. I want to have a timer that shows the time they have spent waiting. I should be able to pause and continue the timer and stop it and reset it. How do I implement this thing in my Django webapp? Do I use javascript? -
Saving new django model object gives duplicate key
Django 2.2.3 on Python 3.7, with Amazon RDS Postgres Database. Saving a new object doesn't work for this Company model: class Company(models.Model): name = models.CharField(max_length=255, unique=True) comp = Company(name='test') comp.save() Gives UniqueViolation: duplicate key value violates unique constraint "appname_company_pkey" DETAIL: Key (id)=(29) already exists I can confirm that yes, there is an entry with id=29 in the table. Why is Django trying to use that as the ID, and how do I stop it? -
How to pass a function from view.py to html
views.py def detect_full_text(tweet): if 'retweeted_status' in tweet.*_json*: analysis_tweet = tweet._json['retweeted_status']['full_text'] else: analysis_tweet = tweet.full_text return (analysis_tweet) public_tweet.html {% for analyze in analysis %} <tr> <td> {{ detect_full_text(analyze) }} </td> <td> {{ analyze.created_at }} </td> <td> {{ analyze.favorite_count }} </td> <td> {{ analyze.retweet_count }} </td> </tr> {% endfor %} I want to call python function from view.py in the html page -
Django testing with Multithreading, changes to database don't persist
I am attempt to replicate an issue we are experiencing on our production server where it seems if two requests are made to save or update and existing object, if made at a very close interval, results in duplicates. To test whatever solution we come up to prevent this, I am attempting to replicate this happening via multiprocessing. The only problem I am experiencing is after the two processes run and complete, when I query the database in the main function the changes supposedly made in the subprocesses haven't persisted, despite the same tests passing in the subprocesses. Code extract: def save_a_generic_model(self, id): data = {'value': '1'} request = RequestFactory().post('/api/responses/', data=json.dumps(data), content_type='application/json') request.user = self.user print(f'Process {id} started at {time()}') response = self.view(request) self.assertEqual(response.status_code, 202) self.assertEqual(len(models.GenericModel.objects.all()), 1) print(f'Process {id} finished at {time()}') def test_multiple_post_to_api(self): jobs = [] db.connections.close_all() for i in range(0, 2): jobs.append(Process(target=self.save_a_generic_model, args=(i,))) for i in range(0, 2): jobs[i].start() for i in range(0, 2): jobs[i].join() self.assertEqual(len(models.GenericModel.objects.all()), 1) # Fails here -
my url giving me this error invalid literal for int() with base 10
Hey guys i need some help in my url, im having trouble with url path, as you can see in my code i want my url /invitobidetails/ "id" = 1/"title" = Re-bidding of the Procurement for the Supply, Delivery and Installation of ICT Equipment and Software for 3D Modeling and Rendering/, i did not create slug in my database. I use the title of the file.. I tried this; path('invitobidetails/<int:mid>/<slug:title>/', views.invitobidDetails, name='invitobidetails'), ``` but this giving me and error : NoReverseMatch at / Reverse for 'invitobidetails' with keyword arguments '{'mid': 1, 'title': <MajorProjects: Re-bidding of the Procurement for the Supply, Delivery and Installation of ICT Equipment and Software for 3D Modeling and Rendering>}' not found. 1 pattern(s) tried: ['invitobidetails/(?P<mid>[0-9]+)/(?P<title>[-a-zA-Z0-9_]+)/$'] so i switch to "str:title" at first it shows no error but when i click the url it giving me this error: ValueError at /invitobidetails/1/Re-bidding of the Procurement for the Supply, Delivery and Installation of ICT Equipment and Software for 3D Modeling and Rendering/ invalid literal for int() with base 10: Here's my code btw. my url.py: path('invitobidetails/<int:mid>/<str:title>/', views.invitobidDetails, name='invitobidetails'), my views.py : def invitobidDetails(request, mid, title): try: invitobidetails = InviToBid.objects.get(id=mid, ProjectName=title) major_projectslists = ProjectNameFileType.objects.filter(ProjectName__in=MajorProjects.objects.filter( invitobid__NameOfFile=invitobidetails)) except InviToBid.DoesNotExist: raise Http404("file does … -
Why cann't i not access media
I seem do not understand what i am doing wrong. I have done research online to see if there is any changes, but yet none. Bellow is what i did settings.py STATIC_URL = '/static/' STATIC_ROOT=[ os.path.join(BASE_DIR,"static"), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') url.py urlpatterns +=static (settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) model.py class product(models.Model): imageone = models.ImageField(upload_to="productimage",null=True,blank=False) When i upload image from the admin, i get image location at http://127.0.0.1:8000/media/productimage/homepagebizalAfric.jpg, but image does not display. What i my doing wrong ? -
Weather API not getting data from other locations
**I am creating a weather app in django and i want the users to be able to search for weather on any locations using the API...i have tried multiple times to use the HTML input but it's not working def home(request): choose_city = "London" #selected city url = f"https://openweathermap.org/data/2.5/weather?q= {choose_city}&units=imperial&appid=b6907d289e10d714a6e88b30761fae22" #open weather url response = requests.get(url) get_weather = response.json() for weather in get_weather["weather"]: pass temperature = get_weather["main"] city_name = get_weather["name"] weatherContext = { "main" : weather["main"], "description": weather["description"], "temp": temperature, "city_name": city_name, "city": choose_city, "url": url } return render(request, "MyWeather/base.html", weatherContext) here is the HTML Blockquote <div class="wrapper"> <div class="container"> <nav class="navbar navbar-light bg-light" id="nav"> <form class="form-inline" action={{url}}> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" > <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search </button> </form> </nav> <br> <div> <h2> City: {{city_name}} </h2> </div><br><br> <h4>Weather: {{main}}</h4><br><hr> <h4> Description: {{description}}</h4><br><hr> {% for temperature, key in temp.items%} {%if temperature == "temp"%} <h4>Temperature: {{key}} °F</h4><br><hr> {%endif%} {%endfor%} How can i be able to resolve this issue -
How to find the acme challenge response?
I'm using a django-letsencrypt and it requires me to enter in the acme challenge and the acme challenge response. I'm able to find the challenge but I'm not able to find the proper response to use. Where can I find the response? I'm using acme V2 -
Creating Django´s blog Post custom fields
I am new to django, I am trying to add custom fields to the regular django blog Post App. This is the blog fields out of the box: models.py from django.db import models from django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title I need to create 4 fields: Types (charfield length=200) Status of item (combobox with OK and NOK options) Ranking (numbers, 1-10) Deployed (charfield length=200) I have tried simply adding those fields to my models.py below but it breaks the website: title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) Types = models.CharField(max_length=200, unique=True) etc Error on my anaconda prompt: TabError: inconsistent use of tabs and spaces in indentation Where else do I need to add the fields? DO I need to create a separate class? If so, how do I add to the create post backend? -
How to Use Django File Storage to Share Files Between an API and a Worker
Goal I want to build a local docker compose deployment such that I have 5 services. Redis Postgres RabbitMQ Django API Django Worker In this deployment the user uploads a file via the API endpoint. This endpoint will store the file in a FileField field in a model. In a separate transaction the user will trigger an asynchronous task via a separate endpoint. This task will be responsible for downloading the file extracting the file kicking of sub tasks to perform intermediate processing steps upload the results of the processing to the database The intermediate processing steps are NOT supposed to upload any of the files to the database. The intermediate processing steps are to use django's internal file storage solution to download and upload files there. This is implemented with a file system hierarchy that is not relevant to this question. The Problem I have managed to get my local file system working with this configuration. If I run the backend of redis, postgres, and rabbitmq. And then, I run the API and Worker on my machine locally everything runs fine. When I create a docker-compose configuration and decouple everything. The operation seems to break. And in my docker-compose … -
MySQL startup ERROR! The server quit without updating PID file
I'm trying to start mysql in a Mac using sudo /usr/local/mysql/support-files/mysql.server start. I keep getting the following error - ERROR! The server quit without updating PID file (/usr/local/mysql/data/My-MacBook-Pro.local.pid). How do I solve this? I have tried uninstalling and reinstalling mysql using home-brew. I have also tried sudo chown _mysql /usr/local/var/mysql/* and other things mentioned in other answers. My-MacBook-Pro:~ myusername$ sudo /usr/local/mysql/support-files/mysql.server start Starting MySQL ... ERROR! The server quit without updating PID file (/usr/local/var/mysql/My-MacBook-Pro.local.pid). -
how do I add a friend system to my carpooling app
I am creating a website for carpooling as a class project. I need to implement a friend system on my website. It is just a simple friend system where users can add or remove another user as friend, no friend requests necessary. I would also need to display the list of friends for a user in the HTML template. I am very new to Django and web development. I am using AbstractUser from django.contrib.auth.models as my user model. from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass def __str__(self): return self.email class UserFriends(models.Model): current_user = models.ForeignKey(CustomUser, related_name='owner', null=True, on_delete=models.CASCADE) users = models.ManyToManyField(CustomUser, blank=True) def add_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create(current_user=current_user) friend.users.add(new_friend) def remove_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create(current_user=current_user) friend.users.remove(new_friend) def __str__(self): return str(self.current_user) -
Removing newlines from the end of base.html file makes some elements disappear from DOM
This is a strange bug. I have an html file that extends a base template called base.html. I noticed that a script tag right before the end body tag in the base template doesn't show up in the DOM in the Elements tab of the Chrome dev tools, and the tag is cut off completely along with the rest of the html file in the Sources tab. This happens in Chrome, Mozilla, and Safari, so it must be a problem on the Django side. And obviously the observable effects on the page that the script should create aren't happening either. Here's the end of that base template in the Sources tab: <section> what is going on </section> <footer></footer> <script src="/static/home/js/ba Completely cut off. Here's the end of that base template: {% block main %}{% endblock %} <footer></footer> <script src="{% static 'home/js/base.js' %}"></script> {% block js %}{% endblock %} </body> </html> Now, here's where it gets funny. The trouble is at the end of the file, so I just added some newlines to see if there's any difference in the DOM is rendered: {% block main %}{% endblock %} <footer></footer> <script src="{% static 'home/js/base.js' %}"></script> {% block js %}{% endblock %} … -
Django: how to have dynamic values in separate javascript files?
I would like to keep the javascript logic in separate files from the Django templates. However, some of the logic contains dynamic values which I would like to still be rendered just like templates. For example, ajax calls will contain urls url: "{% url 'app:list' %}", When the script is directly in the template, this is replaced by the proper url. When the code is in a separate .js file and is included this way: <script type="text/javascript" src="{% static 'js/list.js' %}"></script> The url is not replaced and the code appears just as it is. How to solve this? Thank you -
Howto configure Gmail account / Django Mailbox to receive incoming mails
I want to process email from a gmail account via Django. I installed latest django-mailbox. I created a gmail account, and created a Mailbox in django admin: imap+ssl://EMAILADDRESS%40gmail.com:PASSWORD@imap.gmail.com according to the manual. But django mailbox doesn't receive any mails. I think I have to tell gmail to allow django to access the mails. Any hints are appreciated, thanx in advance, Jan -
Can't get Django's get_absolute_url to set up the link properly
I am trying to use the get_absolute_url function in one of my templates like so: template.html <div class="card-columns"> {% for category in main_categories %} <div onclick="document.location = {{ category.get_absolute_url }};" class="card"> I'm fairly new to programming in general so I'm not sure if that is the correct way to do it, but I have been able to get it to return a couple views individually by using if statements like this: models.py def get_absolute_url(self): if self.pk == 1: return reverse('forum:index') if self.pk == 2: return reverse('tutorials:cybertips') return reverse('tutorials:subjects', args=[str(self.pk)]) I don't get any errors, and when clicking on the cards with pk=1 & pk=2 it returns the correct url pattern. The other cards loads fine but don't link to anything. When inspecting the html it looks like it returns a url so I'm wondering if i'm not understanding the onclick function? Here are my urls(in this app): urls.py app_name = 'tutorials' url_patterns = [ path('category/<int:pk>/', views.SubjectView.as_view(), name='subjects'), path('cybertips/', views.cybertips, name='cybertips'), ] views.py class MainCategoriesView(ListView): model = MainCategory context_object_name = 'main_categories' class SubjectView(ListView): model = Subject context_object_name = 'subjects' Any help is appreciated. Or if there is a more efficient and safe way to do it. Thank you. -
Filter json records in Django Rest Framework
I created a DRF API endpoint in order to be able to grab some data to my database and show it on my Django page using Jquery. My sample data looks like this: { "item": "Someitem", "Price": 120, "Status": "Free" }, { "item": "SecondItem, "Price": 90, "Status": "Taken" }, So if i retrieve the endpoint from JQuery to this link: http://127.0.0.1:8000/tst/, i'll get all the records and have all of them shown in my web page. But what if, for example, i only want to retrieve only the records whose Status field is set to Taken? Is there any way to edit the DRF request so that it points to http://127.0.0.1:8000/tst/Taken? Yes, i can do it with Jquery, but i would rather do it from Django instead. I'm fairly new to DRF, so my setup is pretty basic: views.py class tstList(generics.ListCreateAPIView): queryset = tst.objects.all() serializer_class = tstSerializer class tstDetail(generics.RetrieveUpdateDestroyAPIView): queryset = tst.objects.all() serializer_class = tstSerializer url.py path('tst/', views.tstList.as_view()), path('tst/<int:pk>/', views.tstDetail.as_view()), models.py class tst(models.Model): item = models.CharField() Price = models.FloatField() Status = models.CharField() def save(self, *args, using=None, **kwargs): super(tst, self).save(*args, **kwargs) -
Bootstrap 4 Multifield Equivalent
Django Crispy Forms has a multifield layout for the uni-form template pack - https://django-crispy-forms.readthedocs.io/en/latest/layouts.html#uni-form-layout-objects. Errors in the form are shown in a list at the top of the form. Whereas normally errors are shown beneath the field they concern. It doesn't seem such an option is supported in bootstrap4 (having read the docs for the first time) so I wondered if anybody knew a way of achieving this easily? -
I don't know why Nginx server is not working
Hi there i'm trying to put in production some django app using nginx + gunicorn + supervisor. Following this guide i was able to reproduce all steps with success but for some reason i can't make it work. I believe that the problem is with the nginx part of the project since i'm not able to even serve a static file for testing. It's my first time using all these tools. Config files are as follows: nginx.conf: worker_processes 1; user nobody nogroup; # 'user nobody nobody;' for systems with 'nobody' as a group instead error_log /home/seba94/log/nginx/nginx.error.log warn; #pid /run/nginx.pid; events { worker_connections 1024; # increase if you have lots of clients accept_mutex off; # set to 'on' if nginx worker_processes > 1 # 'use epoll;' to enable for Linux 2.6+ # 'use kqueue;' to enable for FreeBSD, OSX } http { include /etc/nginx/mime.types; # fallback in case we can't determine a type default_type application/octet-stream; access_log /home/seba94/log/nginx/nginx.access.log combined; sendfile on; upstream app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response # for UNIX domain socket setups server unix:/tmp/gunicorn.sock fail_timeout=10s; # for a TCP configuration #server 127.0.0.1:8000 fail_timeout=0; } server … -
I am having issues uploading a Python project (using Django) to Heroku
I am trying to deploy a Python project to Heroku. When i press the "Deploy Branch" button on the Heroku website ... https://dashboard.heroku.com/apps//deploy/github i get this error. Installing requirements with pip $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blog' Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets Push rejected, failed to compile …