Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way in Python to compare variable names with file names in a case insensitive way?
I have a function called get_book which opens requested book by its title argument. Function get_book can receive title in any case (e.g. Foo,FOO,fOo). While this is not a problem in itself, book folder where the function retrieves a book if the title's are matching, also has book titles in a mixed case way. The database folder is dynamic and continuous to receive new book file names (like e.g. Foo.pdf,FOO.pdf,FOo.pdf). My question is how can I compare titles and followingly retrieve requested book without changing file names in the database? Is there an efficient way to open files without worrying about case matching? my code: def get_book(title): """ Retrieves a book by its title. If no such book exists, the function returns None. """ try: f = default_storage.open(f"books/{title}.pdf") return f.read().decode("utf-8") except FileNotFoundError: return None -
Getting email from LoggedIn user with Github
I have successfully setup Django with Django-allauth to register with Github but even if inside the scope on settings and asking for , it does not store the user's email address on the database. Here is the settings block: SOCIALACCOUNT_PROVIDERS = { 'github': { 'SCOPE': [ 'user', 'emails', 'repo', 'read:org', ], } } ACCOUNT_EMAIL_REQUIRED = True Is there any configuration left to do or am I doing something wrong? -
what exactly is django-oauth-toolkit used for?
I am trying to implement google and facebook oauth2 in my django rest framework project. I came across this library django-oauth-toolkit but I couldn't understand much reading through documentation. It didn't even talk about google or facebook auth. Is it used to make an oauth2 provider like facebook or to authenticate users using existing providers ? -
In Django, how do I replace a model's image using a receiver?
I'm trying to convert images uploaded as part of a model to jpgs on save. My code creates the jpg and deletes the original imag (w.g., a tiff) but I can't get it to replace the image in the model. In other words, if I create an Item x and try to display x.image, nothing is there. Any help would be greatly appreciated! models.py: def image_upload(instance, filename): ext = filename.split('.')[-1] filename = "{0}.{1}".format(instance.title, ext) return os.path.join("originals", filename) class Item(models.Model): id = models.AutoField(primary_key=True) owner = models.ForeignKey( get_user_model(), on_delete=models.SET_NULL, null=True, blank=True ) title = models.CharField(max_length=200) image = models.ImageField( upload_to=image_upload, blank=True, validators=[validate_image] ) @receiver(post_save, sender=Item) def image_to_jpg(sender, instance, **kwargs): if kwargs.get('created') and instance.image: filename, file_ext = os.path.splitext(instance.image.path) if file_ext != ".jpg": im = Image.open(instance.image.path) im = im.convert("RGB") im.save(instance.image.path.replace(file_ext, ".jpg")) storage, path = instance.image.storage, instance.image.path instance.image = im storage.delete(path) -
ImportError: cannot import name 'views' from 'learning_log'
I am beginner in django and following a tutorial. got import error even after typing the exact code. here is the code views.py from django.shortcuts import render def index(request): return render(request, 'learning_logs/index.html') urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'',include('learning_logs.urls', namespace ='learning_logs')), url(r'^$', views.index, name='index'), ] error ImportError: cannot import name 'views' from 'learning_log' (C:\Users\hhh\PycharmProjects\learning_log\learning_log\learning_log_init_.py) -
How to delay time in Django
I'm trying to make a delay before redirect to this code return redirect('home'). I have imported time and used time.sleep(5) but it seems it doesn't work with django! def login_page(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') -
noreversematch in Django but URL exists
I get this error when trying to submit my form. The URL exists, so I don't really get it Reverse for '<WSGIRequest: POST '/ideas/'>' not found. '<WSGIRequest: POST '/ideas/'>' is not a valid view function or pattern name. URLS.py urlpatterns = [ url(r'^index/$', views.index, name='index'), url(r'^signup/$', core_views.signup, name='signup'), url(r'^admin/', admin.site.urls), url(r'^delete/$', core_views.skill_delete, name='delete'), url(r'^edit/$', views.edit_skill, name='edit'), url(r'^login/', views.login_user, name='login'), url(r'^add/', views.create_task, name='add'), url(r'^ideas/$', views.ideas_view, name='ideas'), url('logout/', views.logout_user, name='logout'), ] views.py def ideas_view(request): idea = request.POST.get('ideas') if idea == 'itsupport': skills = ['Computer Networking', 'sss'] else: skills = ['sss'] return redirect(request, 'index', {'skills': skills}) html <form action="/ideas/" name="ideasform", id="ideasform" method="post"> -
How to run long tasks in the background od django without pausing the execution of the app
I want to know how to run independently a very long task that takes probably 2 minutes in the backend of django. I used threading in python and it works but as soon as i execute another task in the main django project the task in the background stops and doesn't finish executing. Celery and django background tasks have the same issue as well, i tried them and it didn't work. So please if anyone has an idea how to do that, help me!!!! thanks so much in advance -
How to add IP to Page Visitor Count for Detail View in Django
I am trying to collect data for each visitor count related to every Page View Detail. I have implemented the function which counts the visitors for the page but everytime it is refreshed it will add one more view which is not accurate data. My question is how to add to the function IP adress to show if it does exist the disregard it from the count and the visitor count is only related to new visitors. Here is the models.py class Post(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) -------------------------------------------------- title = models.CharField(max_length=100, unique=True) viewCount=models.IntegerField(default=0) def __str__(self): return self.title def incrementViewCount(self): self.viewCount += 1 self.save() Here is the views.py def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res -
Track Email Opens Sent From Django App Does not work?
Hi all I tried to track the opened mails with Django by gmail. So I'm trying and email sent working properly but but email seen not wokring i guess here is m views.py and urls.py code that i used for email_tracker views.py def image_load(request, pk): META = { header: value for header, value in request.META.items() if header.startswith(("HTTP_", "REMOTE_")) } Blog.objects.filter(pk=pk, seen_at=None).update( request=json.dumps(META), seen_at=now() ) print("\nImage Loaded\n") red = Image.new("RGB", (1, 1)) response = HttpResponse(content_type="image/png") red.save(response, "PNG") return response def test_email(request, pk): et = get_object_or_404(Blog, pk=pk) ctx = {"et": et} ctx["image_url"] = request.build_absolute_uri(reverse("image_load")) tpl = "blog_email_template.html" html_message = render_to_string(tpl, ctx) if request.user.email: try: send_mail( subject=et.title, message="", html_message=html_message, from_email="SimpleIsBest <contact@gmail.io>", recipient_list=[request.user.email], ) except Exception as e: pass return redirect("/admin/blog/blog/{}/change/".format(pk)) urls.py path("/image_load/", views.image_load, name="image_load"), path("/email/test/<int:pk>/", views.test_email, name="driveremail_test"), Thank you. -
Failing to understand how inject crisp_form tags in django template
I am working on understanding Django crispy forms however I do not know if the mistake that I am making is on my forms.py or is on my login.html whereby I am not placing in the crispy form tags properly I get the following error when I load the html page. AttributeError at /login/ 'tuple' object has no attribute 'fields' Code Below: forms.py from django import forms from phonenumber_field.modelfields import PhoneNumberField from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit class UserAccounts(forms.Form): name = forms.CharField(label='First Name', max_length=100) last_name = forms.CharField(label='Surname', max_length=100) phone_number = PhoneNumberField() email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) verify_password = forms.CharField(widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'POST' self.helper.layout = ( 'name', 'last_name', 'phone_number', 'email', 'password', 'verify_password', Submit('submit', 'Submit'), ) Code Below: login.html <!DOCTYPE html> {% load crispy_forms_tags %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> {% crispy form form.helper %} </body> </html> -
how do you go down a route in Django? for example I want to go from wiki/CSS to wiki/CSS/edit
so im trying to go from my route wiki/CSS, or wiki/HTML, etc to wiki/CSS/edit. I dont want to create an entirely new edit function because then I won't be able to pass the entryname variable into the edit function. I need to do this so that it displays the information that will be edited. is there a way I can nest the functions so I can use the same variable? and how do I go from one route and then add another /abcd route after. you can see from my code that in the edit function I have "entryname", but nothing is passed into it because the function doesn't know what entryname is def entry(request, entryname): if request.method == "GET": term = entryname getentry = util.get_entry(term) try: return render(request, "encyclopedia/title.html", { "entryname": markdown2.markdown(getentry) }) except: return render(request, "encyclopedia/title.html", { "entryname": "ERROR: The requested page was not found." }) else: try: getentry = util.get_entry(request.POST['q']) return render(request, "encyclopedia/title.html", { "entryname": markdown2.markdown(getentry) }) except: getentry = request.POST['q'] list=[] entries = util.list_entries() for entry in entries: if getentry in entry: list.append(entry) continue return render(request, "encyclopedia/index.html", { "entries": list }) def edit(request): if request.method == "GET": term = entréname getentry = util.get_entry(term) return render(request, "encyclopedia/edit.html", … -
project type is not showing in python when i try to create a new project
I am using pycharm community edition. I just installed django3.1rc1 version. I can create a new project with command prompt but when i click on new project in pycharm, the project type row at left is not showing. can anyone please tell me how to fix it? -
How to handle API responses(JSON) containing \x00 (or \u0000) in its data, and store the data in Postgres using django models?
I'm making an api call, and trying to store its response in Postgres using Django models. Here's what I have been doing: response = requests.post(url='some.url.com', data=json.dumps(data), headers={'some': 'header'}) response_data = json.loads(response.content.decode('utf-8')) #handler is a object of a model handler.api_response = response_data handler.save() But this used to fail, when my json had fields like 'field_name': '\x00\x00\x00\x00\x00'. It used to give following error : DataError at /api/booking/reprice/ unsupported Unicode escape sequence LINE 1: ... NULL, "api_status" = 0, "api_response" = '{"errorRe... ^ DETAIL: \u0000 cannot be converted to text. CONTEXT: JSON data, line 1: ..."hoursConfirmed": 0, "field_name":... How i tried to resolve this is by using the following: response = requests.post(url='some.url.com', data=json.dumps(data), headers={'some': 'header'}) response_data = json.loads(response.content.decode('utf-8')) #handler is a object of a model handler.api_response = json.loads(json.dumps(response_data).encode("unicode-escape").decode()) handler.save() The initial issue was solved then. But recently, when i got a field with value 'field2_name': 'Hey "Whats up"'. This thing failed by giving error: json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 143 (char 142) Probably because json.loads() got confused with " inside the value as an enclosing " and not an escaped ". Now, If i print the initial response just after json.loads(response.content.decode('utf-8')) statement, it shows the field as \x00\x00\x00\x00\x00. But output of … -
Failed to initialize storage: failed to perform migrations: creating migration table: unable to open database file
I am building a django application and also using dex for Token Authentication. This application is deployed on AWS EC2 but when I run the dex file it gives an error . I am using sqlite3 as a database for dex . This is my dex file This is the error Any help will means a lot. Thank you -
In Django/DRF how do I decide to validate with a constraint, validator or serializer?
An example of this, is I have an integer field which I want to set a max and min. I can do this with a constraint, validator and a serializer. Do I do them with all? How do I choose? I guess if the logic is too advanced for a constraint or validator I default to a serializer, but what is the general rule for this? Thanks -
Django Rest Framework group objects dynamically
My issue is related to Django RestFramework and how to dynamically group objects. The most similar answer I found came from Rex Salisbury here but wasn't adaptable to n number of groups: models.py class Product(models.Model): name = models.CharField(max_length=20) class Ingredient(models.Model): name = models.CharField(max_length=20) class Mix(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) percentage = models.FloatField() class Meta: unique_together = ('product', 'ingredient') serializer.py class MixSerializer(serializer.ModelSerializer): class Meta: model = Mix fields = ('product', 'liquid', 'percentage') views.py class MixView(viewsets.ModelViewSet): queryset = Mix.objects.all() serializer_class = MixSerializer This is an example of the structure I'm currently getting from the API: [ { "product": "White Russian", "ingredient": "Vodka", "percentage": 0.54 }, { "product": "White Russian", "ingredient": "Coffee Liquer", "percentage": 0.27 }, { "product": "White Russian", "ingredient": "Single Cream", "percentage": 0.19 } ] I've been trying to group these in a way which minimises the product name repetition, something like this, { "product": "White Russian", "ingredients": { "Vodka": 0.54, "Coffee Liquer": 0.27, "Single Cream": 0.19 } } by following documentation for Nested Relationship but I'm no longer convinced this is the right course of action. I'm comfortable getting this data from object filters but unable to implement this alongside the serializers/views. -
ValueError: Field 'id' expected a number but got ' '
After manage.py makemigrations, when i migrate the code found this error ValueError: Field 'id' expected a number but got ''. model.py # Create your models here. class Post(models.Model): sno = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) user_post = models.TextField() image = models.ImageField(upload_to = "user_image", blank=True) timeStamp = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return str(self.user) + ' ' + str(self.timeStamp.date()) # handle Query Post class QueryPost(models.Model): sno = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) Query_post = models.TextField() Query_image = models.ImageField(upload_to = "Query_image", blank=True) slug = models.CharField(max_length=30) timeStamp = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return str(self.user) + ' ' + str(self.timeStamp.date()) class QueryAns(models.Model): sno = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) Query_ans = models.TextField() ans_image = models.ImageField(upload_to = "Query_ans_image", blank=True) # post = models.ForeignKey(QueryPost, on_delete=models.CASCADE) # parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) timeStamp = models.DateTimeField(default=now) def __str__(self): return str(self.user) + ' ' + str(self.timeStamp.date()) views.py # Create your views here. # Pages handle def Home(request): #fetching post from database posts = Post.objects.all() data = {'posts':posts} return render(request,'home/home.html', data) def Notification(request): return render(request,'home/Notification.html') def Query(request): allPost = QueryPost.objects.all() context = {'allPost':allPost} return render(request,'home/Query.html', context) def querySlug(request, slug): slugPost = QueryPost.objects.filter(slug=slug) slugpage = {'slugPost':slugPost } return render(request,'home/QuerySlug.html', slugpage) # APIs Page function handle def handleSignup(request): if request.method == 'POST': #get … -
extends 'base.html' doesn't work in django
my base.html code - <html> <body bgcolor="cyan"> {% block content %} {% endblock %} </body> </html> my home.html code- <% extends 'base.html' %> <% block content %> <h1>Hello {{name}}!!!</h1> <% endblock %> django server output <% extends 'base.html' %> <% block content %> Hello viraj!!! <% endblock %> home.html and base.html are in the same directory. -
Change the <input> button to a hyperlink tag <a>?
I need to change my avator image, and after pressing the Change picture button select the image and after that have a preview of new added photo. Here is my code: .html <!-- Avatar --> <div class="avatar avatar-xl mb-6"> <img class="rounded-circle account-img" id="id_image_display" src="{{ user.profile.image.url }}" alt="..."> </div> <div class=" mb-6 mt-7 ml-2"> <div class="form-group image-group" id="id_image_group"> <a href="" id="upload_avator_link"> <b>Change picture</b> </a> </div> <div class="group-input"> <input type="file" name="image" id="upload_avator" accept="pics/*" onchange="readURL(this)"> </div> </div> This is the Js function: .js document.getElementById('id_image_group').onclick = function(event){ document.getElementById('upload_avator').click(); }; function readURL(input){ var reader = new FileReader(); reader.onload = function (e) { $('#id_image_display') .attr('src', e.target.result) }; reader.readAsDataURL(input.files[0]); } and this is the .css code: #upload_avator_link{ text-decoration:none; } #upload_avator{ display:none } It should work but it doesn't! Any kind of help would be appreciated👌 -
Out of sort memory, consider increasing server sort buffer size
I am getting the following error when listing a big table, over 12k records. OperationalError at /admin/glp_legacy_db/legacy_article/ (1038, 'Out of sort memory, consider increasing server sort buffer size') Request Method: GET Request URL: http://localhost:1000/admin/glp_legacy_db/legacy_article/?p=150 Django Version: 3.0.8 Exception Type: OperationalError Exception Value: (1038, 'Out of sort memory, consider increasing server sort buffer size') Exception Location: C:\Users\elans\Documents\work\globalcitymedia\sites\python\dj_glp_v1\venv\lib\site-packages\MySQLdb\cursors.py in _get_result, line 349 ....................... -
Django Comments not creating
I was trying to create comments which are linked to posts. Everything is fine, but when I am creating my comments nothing happens. I can create my comments in the admin site and then they show up but when I try to create them as a user it doesn't work. I need help and thank you very much. view class PostDetail(LoginRequiredMixin,ModelFormMixin,generic.DetailView): model = PostModel template_name = 'post_detail.html' form_class=CommentForm def get_success_url(self): return reverse('post_detail',kwargs={'slug':self.object.slug}) def get_context_data(self, **kwargs): context = super(PostDetail,self).get_context_data(**kwargs) context ['commentmodel_list'] = CommentModel.objects.filter(post=self.object).order_by('-created_on') return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.instance.author = self.request.user form.instance.post = self.object.post return super(PostDetail,self).form_valid(form) model.py from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify # Create your models here. class PostModel(models.Model): post = models.TextField(max_length=256, unique=True) slug = models.SlugField(max_length=20, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='post_author') created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.post) super().save(*args, **kwargs) def __repr__(self): return f"{self.post}" class CommentModel(models.Model): post = models.ForeignKey('dictionary.PostModel', on_delete=models.CASCADE, related_name='post_comment') comment=models.TextField(max_length=256,unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='comment_author') created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def get_absolute_url(self): return reverse("comment_detail",kwargs={'pk':self.pk}) def __repr__(self): return f"{self.comment}" -
django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread with celery beat and dbbackup
I am writing a code to take frequent backups of our database to dropbox. The following is my tasks.py that has a test code to execute a Django management command management.call_command('dbbackup', interactive=False) every 1 minute. But I am encountering the error django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 140423029811616 and this is thread id 140422957233632.. tasks.py from __future__ import absolute_import, unicode_literals from mindspace.celery import app from celery.utils.log import get_task_logger from celery.schedules import crontab from django.core import management @app.task def db_backup_to_dropbox(): management.call_command('dbbackup', interactive=False) app.conf.beat_schedule = { 'backup-every-second': { 'task': 'core.tasks.db_backup_to_dropbox', 'schedule': crontab(minute='*/1'), 'args': (), }, } Traceback from celery.log [2020-07-25 16:24:00,050: INFO/MainProcess] Received task: core.tasks.db_backup_to_dropbox[a34653fe-a3c6-4259-a98d-7613c5f3446c] [2020-07-25 16:24:00,054: INFO/MainProcess] Backing Up Database: myproject [2020-07-25 16:24:00,213: INFO/MainProcess] Writing file to default-arc-min-prd-lon-01-2020-07-25-162400.dump [2020-07-25 16:24:00,215: INFO/MainProcess] Request to files/get_metadata [2020-07-25 16:24:00,287: ERROR/MainProcess] RecursionError: maximum recursion depth exceeded while calling a Python object File "/myproject/venv/lib/python3.8/site-packages/dbbackup/utils.py", line 118, in wrapper func(*args, **kwargs) File "/myproject/venv/lib/python3.8/site-packages/dbbackup/management/commands/dbbackup.py", line 61, in handle self._save_new_backup(database) File "/myproject/venv/lib/python3.8/site-packages/dbbackup/management/commands/dbbackup.py", line 88, in _save_new_backup self.write_to_storage(outputfile, filename) File "/myproject/venv/lib/python3.8/site-packages/dbbackup/management/commands/_base.py", line 88, in write_to_storage self.storage.write_file(file, path) File "/myproject/venv/lib/python3.8/site-packages/dbbackup/storage.py", line 82, in write_file self.storage.save(name=filename, content=filehandle) File "/myproject/venv/lib/python3.8/site-packages/django/core/files/storage.py", line 51, in save … -
GraphQL - JWT -change payload of verifyToken mutation - django
I wanna change the payload of verifyToken mutation. So instead of returning email I wanna return id schema.py import graphql_jwt class Query(AccountsQuery, ObjectType): # This class will inherit from multiple Queries # as we begin to add more apps to our project pass class Mutation( AccountsMutation, ObjectType): # This class will inherit from multiple Mutations # as we begin to add more apps to our project token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() pass schema = Schema(query=Query, mutation=Mutation) I've seen this: https://django-graphql-jwt.domake.io/en/latest/_modules/graphql_jwt/utils.html#get_user_by_natural_key But I dont know how I can implement that - if it's a correct approach Any ideas how I could do that? -
How to fetch data by id in django rest-framework
I was having a category model and subcategory model. I want that when the user click on the category it will all subcategory of it, which was releated to it in api. Here is my models.py class Category(models.Model): name = models.CharField(max_length=254, unique=True) status = models.BooleanField(default=True) def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=254, unique=True) id_parent = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) price = models.IntegerField() status = models.BooleanField(default=True) def __str__(self): return self.name Here is my serializers.py from rest_framework import serializers from accounts.models import Category, SubCategory class CategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = '__all__' class SubCategorySerializer(serializers.ModelSerializer): class Meta: model = SubCategory fields = '__all__' Here is my views.py class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all().order_by('name') serializer_class = CategorySerializer class SubCategoryViewSet(viewsets.ModelViewSet): queryset = SubCategory.objects.all().order_by('name') serializer_class = SubCategorySerializer