Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I do to convert OrderedDict to Dict
I have a this list a = [OrderedDict([('a','b'), ('c','d'), ('e', OrderedDict([('a','b'), ('c','d') ]))])] and I want to convert the OrderedDict in Dictionnary. Do you know how could I do ? Thank you ! -
I want to show 'pdf' print link with a function that prints pdf file of a particular contract
I want to show a pdf print link which shows a link to print a PDF file in admin page for each contract item. an example an example image h I tried changing the links for the to highlight the contract but i got the error 'reverse match error for contracts/contract. models.py from django.db import models from tenants.models import Occupant from landlords.models import Landlord import uuid class Contract(models.Model): # Function to tell the contract amount occupant = models.ForeignKey(Occupant, on_delete=models.CASCADE, null=True) landlord = models.ForeignKey(Landlord, on_delete=models.CASCADE, null=True) # contract_key = models.CharField(max_length=15, default=uuid.uuid4().hex[:15], editable=False, unique=True) contract_key = models.CharField(max_length=15, default='ak2354') contract_date_from = models.DateField() contract_date_to = models.DateField() active = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-updated', ) def __str__(self): return self.contract_key urls.py from django.urls import path from . import views app_name = 'contracts' urlpatterns = [ path('admin/contract/<int:contract_id>/pdf/', views.admin_contract_pdf, name='admin_contract_pdf'), ] views.py from django.contrib.admin.views.decorators import staff_member_required from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from django.utils.text import slugify # Weasy print. from weasyprint import HTML from weasyprint.fonts import FontConfiguration from .models import Contract @staff_member_required def admin_contract_pdf(request, contract_id): contract = get_object_or_404(Contract, id=contract_id) response = HttpResponse(content_type="application/pdf") response['Content-Disposition'] = "inline; filename={date}-{name}-donation-receipt.pdf".format( date=contract.created.strftime('%Y-%m-%d'), name=slugify(contract.contract_key), ) html = render_to_string("contracts/contract/pdf.html", { 'contract': … -
Unable to update db using xeditable with django
I am trying to achieve inline editing using x-editable and the UI is rendering fine. But, when I click on the submit(tick mark), the data is not getting posted to db. I am new to django. I am using Jquery-UI. I tried debugging using the browser console. I am able to see the 'POST' method in browser console, and the value. I have tried setting $.fn.editable.defaults.send = "always"; @method_decorator(csrf_exempt) def edit_status(request, pk): post = get_object_or_404(BlacklistModel, pk=pk) if request.method == 'POST': form = BlacklistStatusForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.status = request.status post.save() return HttpResponseRedirect('/esredashboard/blacklist') # Redirect after POST else: form = BlacklistStatusForm(instance=post) #HTML for inline edit <a href=\"#\" data-name=\"status\" data-type=\"text\" data-pk=\"{pk}\" data-url=\"{pk}/edit_status\" data-title=\"Enter username\">{value}</a> #Javascript in template <script type="text/javascript"> $.fn.editable.defaults.mode = 'inline'; $(document).ready(function() { $('[data-name=status').editable({ ajaxOptions: { type: 'post' } } ); }); </script>``` I am able to edit it in the UI but no value is getting updated in the db. I am not sure if my view is correct. -
Django Get() Returned More Than One Object
I am receiving the following error: get() returned more than one Manifests -- it returned 2! I understand this is because there are multiple records in the database with the same value, but I want to return ALL of those records, so I assume I need to use something other than .get but I'm not sure what/how. def write_pdf_view(request): if request.method == 'POST': reference = request.POST.get('Reference_IDs') y = Orders.objects.all() z = Manifests.objects.all() order = y.get(reference=reference) manifest = z.get(reference=reference) .... .... #Manifest p.drawString(30,620,'MANIFEST: ') p.drawString(30,605,manifest.description) The issue is the manifest.description line. There are more than one records with the same "reference" in the database, and so they won't print. So my question is 2 parts: 1) how can I change manifest = z.get(reference=reference) so that I can access multiple records 2) how can I then access those records in place of "manifest.description" -
Problem with `python manage.py runserver` command An attempt was made to access a socket
I have an issue which says An attempt was made to access a socket in a way forbidden by its access permissions. This issue is appearing when I use python manage.py command to run the server. Here is a picture with the problem . Give some advice, tutorial or anything which could help me to fix it. -
How to re-write polls application built in django tutorials in django documentation using django.forms
I have built the polls application given in Django tutorials under Django documentation. How to recreate polls page where user could vote for a question, using Django forms? Please note: My Question & Choice Model remains unchanged. However I want to create the form to submit votes for a question using django.form (not ModelForms). -
Django: Run model function on button click
Hi I've got a webapp that provides movies to the users. I created a list that shows the lately watched movies of the user. Now I want that the user is be able to add the movies to this list by pressing a button. How can I achive that? I'm working with model based views. And I've got the following code: App "users" models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) movieList = models.ManyToManyField('movies.Movie') App "movies" models.py class Movie(models.Model): title = models.CharField(max_length=120) desc = models.CharField(max_length=1000, null=True) movie = models.FileField(upload_to=movie_dir_path) views.py class MovieDetailView(LoginRequiredMixin, DetailView): model = Movie movie_detail.html <!-- This button should add it to the list --> <button>Add to List</button> I'm grateful for any help. -
How do I count number of visitors on my website?
How do I count visitors on my website so that it increments every time a user visits the website. I can count number of views by visitors using following codes: def blog_detail(request, blog_slug): blog = get_object_or_404(Blog, slug=blog_slug) session_key = 'blog_views_{}'.format(blog.slug) if not request.session.get(session_key): blog.blog_views += 1 # here blog.save() request.session[session_key] = True context = { 'blog': blog, 'categories': get_category_count() } return render(request, 'blogs/blog-detail.html', context) while having blog_views field in my models. I don't know if there is any similar way of doing it just to count number of times my website is visited. Some suggested using hitcount but I couldn't use it anywhere other than generic views. If you suggest it as well please elaborate it further with some codes thank you. Thank you so much. -
Why am I getting this error in the bowser net::ERR_CONNECTION_REFUSED?
I'm using Djangorestframework, nginx, vue.js in my demo_blog on my vps server. When I'm trying to log in to my demo_blog getting http://localhost:8000/rest-auth/login/ net::ERR_CONNECTION_REFUSED. I can log in to my admin panel without any problem, but my rest api is getting that error. In my vue.js app my baseURL at that moment looks like axios.defaults.baseURL = 'http://ip_of_my_server/. I made npm run build and then put the dist to the server. In my /etc/nginx/sites-available/ I have that server { listen 80; server_name ip_of_my_server; access_log /var/log/nginx/demo_blog.log; location /static/ { alias /var/www/demo_blog/staticfiiles/; } location /dist/ { alias /var/www/demo_blog/dist/; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } In my file demo_blog/gunicorn.conf.py I have that bind = '127.0.0.1:8000' workers = 3 user = "nobody" I really cannot figure it out. -
how to display uploaded image on the screen using django and ajax
I'm trying to upload image in django using ajax and to save it in a specified path. the image is uploaded and saved but the problem is that it doesn't display in the template. i added to the settings file the MEDIA ROOT & Media URL i create a model i create a path in the urls file i create a function in the views file i create a template with html and use the ajax and jquery. models.py class photo(models.Model): title = models.CharField(max_length=100) img = models.ImageField(upload_to = 'img/') urls.py from django.contrib import admin from django.urls import path, include from.views import * from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', home2), path('upload/', upload), views.py from django.shortcuts import render,redirect from django.http import HttpResponse,JsonResponse from testapp.models import * import json as simplejson def upload(request): if request.method == 'POST': if request.is_ajax(): image = request.FILES.get('img') uploaded_image = photo(img = image) uploaded_image.save() return render(request, 'home2.html') home2.html <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script> <script> function upload(event) { event.preventDefault(); var data = new FormData($('#ajax').get(0)); console.log(data) $.ajax({ url: '/upload/', type: 'POST', data: data, contentType: 'multipart/form-data', processData: false, contentType: false, success: function(data) { alert('success'); } }); return false; } </script> </head> … -
Pycharm django debug : improperly configured
Pycharm 2018.3 Python 3.7.1 I am having error in the console when I am trying to debug my views.py. django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. servers runs fine when I use python manage.py runserver but it fails with an error ModuleNotFoundError: No module named 'website' where website is my project name. -
How to fix: Page not found (404) in django
I'm new in Django. My problem is when I click the title which is in a.html, it's directing me to this URL; http://localhost:8000/aba/R%C3%BCyada%20Aba%20G%C3%B6rmek in this URL I'm getting an error message; Page not found 404 Here is I wanna do; When I click the title, I wanna show my article details dynamically urls.py from django.contrib import admin from django.urls import path, re_path from dreamarticle import views app_name = "Dreamarticle" urlpatterns = [ re_path('/aba/(.*?)/',views.aba,name="aba"), ] dreamarticle/views.py def aba(request, title): context = dict() context.update( dreamarticlesaba=get_object_or_404(dreamarticle, title=title), ) return render(request, "aba.html", context) aba.html {% extends "layout.html" %} {% block body%} <!-- Content here --> <br> <div class="container"> <div class="row"> {% if dreamarticlesaba %} {% for dreamarticle in dreamarticlesaba %} <div class="col-md-12 dreamdetail"> <h1>{{dreamarticle.title}}</h1> <hr> <p>{{dreamarticle.content|safe|escape}}<p> </div> {% endfor %} {% endif %} </div> </div> a.html {% extends "layout.html" %} {% block body%} {% include "includes/searchbar.html" %} <!-- Content here --> <br> <div class="container"> <div class="row"> {% if dreamarticles %} {% for dreamarticle in dreamarticles %} <div class="col-md-4 text-center bg-primary"> <a href="/aba/{{dreamarticle.title}}" class="titlerenk text-white"><br><b>{{dreamarticle.title}}</b></a> <b>{{dreamarticle.title}}</b> </a> </div> {% endfor %} {% endif %} </div> </div> {% endblock body%} Page not found (404) Request Method: GET Request URL: http://localhost:8000/aba/R%C3%BCyada%20Aba%20G%C3%B6rmek Using the URLconf defined in blog.urls, … -
DATABASE_ROUTERS not working as expected for multiple databases
I have setup setting.py and wrote and specified database_routers but the code keeps taking default_db as the database to apply migrations to. I am trying to connect to multiple databases for same app over different models. Am I doing anything wrong? How can I fix this. I worked this out as per the documentation. -
Django-Ajax giving error "Method Not Allowed (POST): /post/like/"
I am new to django i am using ajax and django for very first time. I have tried by best to search here and there but i couldn't get to solution this answer didn't help as well Django and ajax request Method Not Allowed (POST) the error i am getting is Method Not Allowed (POST): /post/like/ [07/Jun/2019 16:06:16] "POST /post/like/ HTTP/1.1" 405 0 below are the codes likes_section.html {% if request.user.is_authenticated %} <form action="{% url 'like_post' %}" method="post"> {% csrf_token %} {% if is_liked %} <span class="mr-2" style="color:black;">{{ post.total_likes }} Like{{ post.total_likes|pluralize }}<button type="submit" id="like_the_post_by_user" class="btn btn-primary ml-2" name="post_id" value="{{ post.id }}">DisLike</button></span> {% else %} <span class="mr-2" style="color:black;">{{ post.total_likes }} Like{{ post.total_likes|pluralize }}<button type="submit" id="like_the_post_by_user" class="btn btn-primary ml-2" name="post_id" value="{{ post.id }}">Like</button></span> {% endif %} </form> {% else %} <span class="mr-2">{{ post.total_likes }} Like{{ post.total_likes|pluralize }}<button type="submit" id="like_the_post_by_user" class="btn btn-primary ml-2" name="post_id" value="{{ post.id }}" disabled>Like</button>Please Login to enable Like button</span> {% endif %} Ajax $(document).ready(function(event){ $(document).on('click',"#like_the_post_by_user", function(event){ event.preventDefault(); console.log($("#like_the_post_by_user").val()) console.log("from jquery section") var pk = $(this).attr('value'); $.ajax({ type : "POST", url : "{% url 'like_post' %}", data : {'id': pk , "csrfmiddlewaretoken": '{{ csrf_token }}' }, dataType : 'json', success : function(response){ $('#like-section_user').html(response['form']) console.log($('#like-section_user').html(response['form'])); }, error : function(rs, e){ … -
Is it possible to manually disconnect Django's database connection?
In order to debug a problem with Django's mysql connection timing out during a long celery task (Long celery task causes MySQL timeout in Django - options?) I would like to manually close the connection so I can see if my reconnect attempt works. Is this possible? -
How to add 'mobile' field to default auth_user table in User model in django?
I want to add Mobile filed to be saved to auth_user table when i register. models.py from django.db import models from django.contrib.auth.models import User class UserRegModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=100) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): mobile = forms.CharField(max_length=15) class Meta: model = User fields = ['username','email','mobile','password1','password2'] -
How to store an object in a django model?
I am receiving an object from the frontend as a parameter alongside with other parameters. How can I store that object into m model? I've tried JSONfield but not sure if its the best way to do it. This will be a tracking service like Mixpanel etc. this is roughly the object looks like in the front end: myObj = { context: ["Home Page"] dropDown: "navigated to main screen" side: "creator-side" withSelection: false } and I want to have it in Django: @reversion.register() class TrackedEvents(models.Model): ... event_name = models.TextField(max_length=250, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) myObj = { what to add here } I want to be able to filter the events based on the properties in the object on admin panel. -
How to give access to admin to add buttons in side bar in Django?
I am creating a website in which i have designed a static side bar (in which have added options through code). However, i want the admin to add options\choices in the side bar. Please if anyone could help? -
Server error 500 after deployment complete on Heroku + possible trouble with ALLOWED_HOSTS
I ran into problem in deploying my app to Heroku. After deploying it I got server error (500). Admin work, celery work, DB work. I have checked settings.py on Heroku and it says: PS F:\GitHub\myproject> heroku run python manage.py shell >>> ALLOWED_HOSTS ['*'] I got curious why is that as I remember me changing it. I checked both production and local settings and it says: ALLOWED_HOSTS = ["127.0.0.1", 'localhost', 'testserver'] # development settings.py ALLOWED_HOSTS = ["boatsproject.herokuapp.com", '127.0.0.1'] # production settings.py. well, I decided to check shell and shell says: # import settings.py settings.ALLOWED_HOSTS # wtf?? ['*'] ok, then I checked django.conf >>> from django.conf import settings >>> settings.ALLOWED_HOSTS ['*'] same result for production and development settings. Settings are switched very simple by commenting ones that dont needed now: # settings.py from .production_settings import * #from .development_settings import * Question is : Does ALLOWED_HOSTS = [''] might be possible couse of the server error 500 on Heroku and why when in both settings I have configured ALLOWED_HOSTS I still have them in HEROKU or locally in shell() as [“”]. Thank you -
Preventing django form to refresh whole page on submit
I have a form in Django which is embedded in a bootstrap modal element. The input of the form is a client id which I check if it is in the database. Everything works fine on submit except that in case the client id is not in the database the page gets reloaded and I have to open the modal element again to see the error message. I tried to simple prevent the page refresh by adding a script to my html: $('#modalform').on('submit', function (e) { e.preventDefault(); }) But this breaks the form behaviour on submit. The modal div with the form in my home.html looks like this: <div class="modal fade" tabindex="-1" role="dialog" id="mymodal" aria-labelledby="myLargeModalLabel"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <form action="" method="POST" id="modalform"> {% csrf_token %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" … -
I am getting this error, can some suggest how to fix it
Deploying my machine learning model on domain Can someone suggest anything to resolve this or any pathway to deploy my ML model written in Jupyter Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/opt/apps/glasswing_priceforecast_python/Glasswing_venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/opt/apps/glasswing_priceforecast_python/Glasswing_venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/opt/apps/glasswing_priceforecast_python/Glasswing_venv/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/opt/apps/glasswing_priceforecast_python/Glasswing_venv/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/opt/apps/glasswing_priceforecast_python/Glasswing_venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/opt/apps/glasswing_priceforecast_python/Glasswing_venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/opt/apps/glasswing_priceforecast_python/Glasswing_venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/opt/apps/glasswing_priceforecast_python/Glasswing_venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in check for pattern in self.url_patterns: File "/opt/apps/glasswing_priceforecast_python/Glasswing_venv/lib/python3.6/site-packages/django/utils/functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "/opt/apps/glasswing_priceforecast_python/Glasswing_venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/opt/apps/glasswing_priceforecast_python/Glasswing_venv/lib/python3.6/site-packages/django/utils/functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "/opt/apps/glasswing_priceforecast_python/Glasswing_venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 572, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in … -
How to get a particular foreign key to appear from def __str__ function?
I have a class(table4) with two foreign keys(topic and question) to another class(table3). Now when I enter the data in the django admin site for table4, I want only then topic names inserted in table3 to come and only the questions inserted in table3 to come in the slider. Is there anyway to do it? class table3(models.Model): id1=models.IntegerField(default=0) topic=models.CharField(max_length=222) question=models.CharField(max_length=222) answer=models.CharField(max_length=222) def __str__(self): return self.question #for the user to enter class table4(models.Model): username = models.CharField(max_length=222) topic1 = models.ForeignKey(table3, related_name='topic1',on_delete=models.CASCADE) question1=models.ForeignKey(table3, related_name='question1',on_delete=models.CASCADE) answer = models.CharField(max_length=222) def __str__(self): return self.username -
How to fix error in uploading file as chunks in django?
I am trying to write a file in chunks in django. But it seems that the file that is being written to (new file) has written size more than the original.(But the uploaded final size is correct i.e when I go to the folder and check the size) The uploaded file is stored in data base using save() first and then retrieved for writing using chunks. Please Don't tell me save() does the job for me , I have to implement in this way , for a certain job.I'll delete the file from the db anyways afterwards. This is for Windows and Django. I tried printing the file size and written size and the output is shown below. f=FileModel.Objects.get(FileName=fo.name) with open('static\\'+f.FileName, 'wb+') as destination: for chunk in f.File.chunks(chunk_size=2097152 ): #2mb global sizex if(times==0): global sizex #sizex is in bytes format... sizex=chunk times=1 destination.write(chunk) continue destination.write(chunk) sizex+=chunk percent=((((sys.getsizeof(sizex))))/f.File.size)*100 print("\n{}-----------{}----------{}".format(percent,sys.getsizeof(sizex),f.File.size)) destination.close() print("Finished") But Sometimes in huge files what I get is (PERCENT) (NEW FILE SIZE) (Uploaded File size) 102.5722261291232-----------521327953----------508254498 102.98484461223597-----------523425105----------508254498 103.39746309534874-----------525522257----------508254498 and it goes on , and ends at some point of time ( when the whole file is written maybe) and prints Finished This is the kind of Output I get … -
how to customize Verify behavior in django-graphql-jwt
I want to customize the Verify behavior in django-graphql-jwt. the only thing I found in the documentation is customizing the ObtainJSONWebToken behavior. how I can override this class correctly? -
How to count number of times a tag was used and to display it in html?
I want to count the number of times a tag was used and to display it. I tried this solution, but it displays then the number of tags in a post. I understand that i counts like that, because its looking into post for the number of tags used. But i don´t understandt how to tell him that he has to look at all posts. When i try posts.tag.count, then it shows nothing. The .html file: <h1 class="card-title">{{ post.title }}</title></h1> <p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on | date:"d M Y"}} | Tag: {% for tag in post.tags.all %} <a class="mycardtext" href="{% url 'tag' tag.slug %}"> {{ tag.name }} {{ post.tags.count }} </a> {% empty %} None {% endfor %} </p> I also tried just {{tag.count}}, but it also shows nothing. With {{ tag | length}} i tried it also, but of course it then shows the length of the tag an not the number of times.