Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Characters like ' in Django Template. Probably unicode error
I have in Django view the following string string = "'DE', 'FR', 'IT'" which is transfered to a template: return render(request, 'template.html', {'string':string}) In the template I get this string as follows: 'DE','FR','IT' The problem is that this "'" symbol gets a strange translation; How shall I transfer this string to template? Thank you -
Where do I place the logic for validating and transforming a request to a model object in DRF?
I have a working python app that I'm trying to transform in a webapp using django and django rest. For now, I just want to do a post request containing some data: { "orderside" :"long", "symbol" : "BTCUSDT", "leverage" : "20", "entry_price" : "100", "order_cost" : "5.2", "sl_price" :"99.4", "tp_price" : "101.2" } Based on this data, I need to do some validity checks and some calculations. If the data is valid, I want to persist the results as a Trade entity in the database (no 1 to 1 mapping from request to model). This is the model for a Trade: from django.db import models class Trade(models.Model): created_datetime = models.DateTimeField(auto_now_add=True) entry_filled_datetime = models.DateTimeField() tp_sl_filled_datetime = models.DateTimeField() orderside = models.CharField(max_length=10) symbol = models.CharField(max_length=10) leverage = models.PositiveSmallIntegerField() entry_price = models.FloatField() quantity = models.FloatField() sl_price = models.FloatField() tp_price = models.FloatField() entry_id = models.CharField(max_length=25) tp_id = models.CharField(max_length=25) sl_id = models.CharField(max_length=25) state = models.PositiveSmallIntegerField() side = models.CharField(max_length=10) class Meta: ordering = ['created_datetime'] Where do I have to put the code for validation of the request data , and where do I put the calculation logic? Can I put both in the view class, like below? And where does a serializer fit in to this? class … -
Trouble with media directory/files on pythonanywhere
I seem to be having an issue serving up media content on my website. Everything works fine when run on localhost. However, when deployed to python anywhere, I receive a FileNotFoundError when I attempt to upload an image via a form. I've taken a look through overflow for some related topics however I've not found any threads which have allowed me to solve my problem. Here is the exact error received when submitting the image upload form: It seems to be an issue with the resize method in models.py (which works fine on localhost) Here are the appropriate setup files: settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... MEDIA_DIR = os.path.join(BASE_DIR, 'media') # Media MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' IMAGES_DIR = os.path.join(MEDIA_URL,"images") I believe the error is due to the images_path method not retuning the correct location (but it works on localhost). Here is the model which stores the image and defines how images are saved: models.py class Image(models.Model): # this might work? def images_path(): return os.path.join(settings.IMAGES_DIR, 'usruploads') def resize(self): im = PIL.Image.open(self.image) size=(200,200) out = im.resize(size) out.save(self.image.__str__()) def save(self, *args, **kwargs): super(Image, self).save(*args, **kwargs) self.resize() image = models.ImageField(upload_to=images_path()[1:], max_length=255) I will also throw in the media directory structure of the … -
How do I get Django to run a case-insensitive query against my MySql 5.7 db?
I'm using Django 2.0 and Python 3.7. I have this model and manager for attempting to find my model by a name, case-insentively. The backing database is MySql 5.7. class CoopManager(models.Manager): ... # Look up coops by a partial name (case insensitive) def find_by_name(self, partial_name): queryset = Coop.objects.filter(name__icontains=partial_name, enabled=True) print(queryset.query) return queryset class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() Unfortunately, when the query actually gets created, it doesn't appear Django is doing anything to account for case-insensitivity. This is an example query that results ... SELECT `maps_coop`.`id`, `maps_coop`.`name`, `maps_coop`.`type_id`, `maps_coop`.`address_id`, `maps_coop`.`enabled`, `maps_coop`.`phone`, `maps_coop`.`email`, `maps_coop`.`web_site` FROM `maps_coop` WHERE (`maps_coop`.`name` LIKE %res% AND `maps_coop`.`enabled` = True) What changes do I need to make so that Django executes the query in a case-insensitive way against my MySql database? -
Make a string with a UTC+1 date aware
Using the below code which prints 2020-05-02 15:59:00+00:00. Shouldn't it subtract 1 hour and print 2020-05-02 14:59:00+00:00? TIME_ZONE = 'UTC' and USE_TZ = True in settings.py. from datetime import datetime from django.utils.timezone import make_aware str_date = "02-05-2020 15:59" # UTC+1 dt = make_aware(datetime.strptime(str_date, '%d-%m-%Y %H:%M')) print(dt) This subtracts 1 hour from my Ubuntu machine date from django.utils import timezone now = timezone.now() print(now) -
Django DRF @permission_classes not working for IsAdminUser permission
I want to apply IsAdminUser permission on my view. I am able to do it by setting the permission_classes attribute: class UserProfileView(APIView): permission_classes = [IsAdminUser,] def get(self, request, pk=None): ... However, if I try to do the same using decorator then it seems to be ineffective and checks only for authenticated users. class UserProfileView(APIView): @permission_classes([IsAdminUser]) def get(self, request, pk=None): ... I want to understand why is it behaving so. Am I doing anything wrong? My environment configuration: Python==3.7.6, Django==2.2.10, djangorestframework==3.11.0, django-oauth-toolkit==1.2.0 -
Best Way to Handle user triggered task (like import data) in Django
I need your opinion on a challenge that I'm facing. I'm building a website that uses Django as a backend, PostgreSQL as my DB, GraphQL as my API layer and React as my frontend framework. Website is hosted on Heroku. I wrote a python script that logs me in to my gmail account and parse few emails, based on pre-defined conditions, and store the parsed data into Google Sheet. Now, I want the script to be part of my website in which user will specify what exactly need to be parsed (i.e. filters) and then display the parsed data in a table to review accuracy of the parsing task. The part that I need some help with is how to architect such workflow. Below are few ideas that I managed to come up with after some googling: generate a graphQL mutation that stores a 'task' into a task model. Once a new task entry is stored, a Django Signal will trigger the script. Not sure yet if Signal can run custom python functions, but from what i read so far, it seems doable. Use Celery to run this task asynchronously. But i'm not sure if asynchronous tasks is what i'm … -
.Net entity framework pendant for Django shell
I was used to program in Django where you have a shell. This is basically a Python interpreter where you can program in Python and can query your database. For example you open a shell from a Linux terminal with python manage.py shell Then you can query your database using Python code for example like this: print(apartment.rooms.count()) for room in apartment.rooms: print(room.square_meters) Thats really convenient because you can query your database, test some algorithms and don't have to touch your productive code. Now I am working in .Net Core and write an MVC application. But I haven't found something similar so far. Is there something similar? Or how do you add/delete/update your database during development in .Net (using entity framework)? -
Creating a photo gallery with comments in Django
I am in the process of putting together a website where people can post pictures and comment on the pictures. I have created a page where people can add pictures, and a gallery page, where pictures are displayed. I have also created a comments model (with a ManyToMany image field) and comments form for users to add comments. I am not clear on how I put a comment form beneath each of the images, and to make it so that any comments posted are associated with the relevant image (and appear beneath it). I have done a bit of googling, and can't find any guides that show me how to do this. What advice would you give me, please? Thank you. Jeff -
How can I resolve role errors in postgres? "ERROR: createdb: error: could not connect to database template1: FATAL: role 'John' does not exist"
So I'm going through a Django course using postgres, and I've been stuck on the same error for a few hours. I'm on Windows, and know that postgres likes to default to the name on the OS (in this case, it's John) when trying to log in or creating a database. So I did a few things: created a username named "john" with CreateDB privileges, changed the pg_hba.conf "md5" setting to "trust", then looked at all the roles with the psql \du command: Role name | Attributes john | Create DB demo | Superuser, Cannot login postgres | Superuser, Create role, Create DB, Replication, Bypass RLS But the problem is still the same. Whenever I try to createdb, just to test things, I get this error: createdb: error: could not connect to database template1: FATAL: role "John" does not exist I noticed that "John" is capitalized. I made sure to capitalize "John" when creating the role, but it just defaults to "john" automatically in the role name, so the "John" must still be referring to the OS name. How is this error solved? I assume it must be common, since I see tons of references to it, but none of … -
Why this intermediate Django page won't get back to the former action?
This is Django 1.11.29 and I'm trying to write a simple Django admin action with an intermediate page. I've seen something like this has been asked here but even following the response advice I can't manage to solve it. In my ModelAdmin I have this: from django.contrib.admin import helpers from django.shortcuts import render class MyModelAdmin(admin.ModelAdmin): ... actions = ['send_email'] ... So I implemented my send_email action like this: def send_email(self, request, queryset): print(request.POST) print(queryset) if 'apply' in request.POST: # Do some stuff else: return render(request, 'admin/confirm_email.html', { 'mymodels': queryset, 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME }) This is pretty standard according to the Django documentation. The admin/confirm_email.html looks like this: {% extends "admin/base_site.html" %} {% block content %} <p>You're about to send a lot of mails!</p> <form action="" method="post"> {% csrf_token %} {% for mymodel in mymodels %} <input type="hidden" name="{{ action_checkbox_name }}" value="{{ mymodel.pk }}" /> {% endfor %} <br /> <input type="button" value="Cancel" onClick="history.go(-1); return true;" /> <input type="submit" name="apply" value="Confirm" /> </form> {% endblock %} The problem is that when the admin action is invoked, it enters the intermediate page, but when hit Confirm in the intermediate page, it won't call the admin action back, so I cannot process the answer. … -
Django redirecting to a wrong url
when i click submit on my form it goes to ../register/register/ where as my expectation is that it should go to ../register This is my main project urls.py urlpatterns = [ path('participants/', include('participants.urls')), path('admin/', admin.site.urls), ] This is my application urls.py urlpatterns = [ path('register/', views.register, name="register") ] This is my views function def register(request): if request.method == "POST": username = request.POST['username'] # email = request.POST['email'] password = request.POST['pass'] print(username, password) user = User.objects.create_user(username=username, password=password) user.save() return redirect('register') else: return render(request, 'register.html') -
Django template for loop is empty
I am trying to build a detail view in django, but nothing is displayed in the template. views.py class MyDetailView(DetailView): model = Article template_name = 'detail.html' detail.html {% extends 'base.html' %} {% load i18n %} {% endblock %} {% block content %} {% for item in itemlist %} {{item.pk}} {{item.title}} {% empty %} There are no items in this list {% endfor %} {% endblock %} Why is nothing displayed in the template here? -
KeyError at / "https://pbs.twimg.com/media/EUDjMHoWsAERZ83.jpg'"
I want to access the number of retweets and number of likes on a tweet that I get using twitterAPI. I have written the following code with some help from other sources. I am not able to understand the reason for this error. The error is in line 88 of the code. Please help me out. I am attaching the image for the error. views.py: from django.shortcuts import render from TwitterAPI import TwitterAPI from Post.models import Album import calendar from django.contrib.auth.models import User import requests import http.client,urllib.request,urllib.parse,urllib.error,base64,sys import simplejson as json consumer_key='RNBUUEtazKVJemcMedGHWgMCV' consumer_secret='zILQDS386Dd4WRr8810gD5WAGbfkeVRDT3BYWs7RKChY1U7duM' access_token_key='893345180958564352-UT4mqHeDQyYllebzbsIPItOCyjHs8eP' access_token_secret='Gv2pbj6eeKvKPWjbePfO71la7xOeib2T5lV4SaL86UUdj' api = TwitterAPI(consumer_key,consumer_secret,access_token_key,access_token_secret) me = User.objects.get(username='vedant') def newsfeed(request): hashtag_string = '#Swachh_Bharat' hashtag_string = hashtag_string.lower() if(request.GET.get('mybtn')): hashtag_string = str(request.GET.get('hashtag')) print("HashtagString :: ",hashtag_string) if hashtag_string == '#vedant': url_list = [] retweet_count_list = [] url_retweet_dict = {} url_favourite_dict = {} favourite_count_list = [] url_list_in_database = Album.objects.all().filter(user = me).values('image_url') temp = Album.objects.all().filter(user = me).values('image_url','date','retweet_count','like_count') url_list = {} for entry in temp: dt = str(entry['date'])[0:10] dt = calender.month_name[int(dt[5:7])]+" "+ dt[8:10]+"," + dt[0:4] url_list[str(entry['image_url'])] = (dt, str(entry['retweet_count']),str(entry['like_count'])) return render(request, 'Post/newsfeed.html', {'url_list': url_list}) #get the images of particular hashtag else: url_list = [] retweet_count_list = [] url_retweet_dict = {} url_favourite_dict = {} favourite_count_list = [] r = api.request('search/tweets',{'q':hashtag_string,'filter':'images','count':1000}) url_dict = {} for … -
Django with react depkoyment on google cloud
Im trying to build server for my project where frontend is react and backend is django. I did it locally works just fine, but how I should deploy it on google cloud platform, i want to make it live through external ip of my virtual machine. I tried everything what i found on google, but usually all guides are for localhost. -
How to redirect user to login page while adding items to cart?
I am newbie to django. I am creating simple order system. I want only logged in user to add items in cart. If user is not looged in, redirect user to login page and after logged in again redirect user to previous page. This is my views.py @require_POST @login_required def cart_add(request, dish_id): cart = Cart(request) dish = get_object_or_404(Dish, id=dish_id) form = CartAddDishForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(dish=dish, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') -
how to filter user created by another superuserso that it can send notice
in my forms.py class NoticeFormWarden(forms.ModelForm): class Meta: model = Noticee fields = ('name','description','users','file',) def save(self,user): owner = user issue_date = datetime.datetime.now().strftime("%Y-%m-%d") name = self.cleaned_data['name'] description = self.cleaned_data['description'] users = self.cleaned_data['users'] file = self.cleaned_data['file'] Noticee.objects.create(name=name, description=description, users=users, file=file, owner=owner, issue_date=issue_date) def __init__(self, users, *args, **kwargs): super(NoticeFormWarden, self).__init__(*args, **kwargs) self.fields['users'].queryset = User.objects.filter(is_hostelstaff=True) self.fields['name'].widget.attrs['placeholder'] = ' Subject' self.fields['file'].widget.attrs['placeholder'] = ' Subject' self.fields['description'].widget.attrs['placeholder'] = 'write your msg here . . .' self.helper = FormHelper() self.helper.form_show_labels = False in views.py def WardenCreateNotice(request): form = NoticeFormWarden(request.user, request.POST or None) if request.method == 'POST': if form.is_valid(): print('Saved notice') form.save(request.user) form = NoticeFormWarden(request.user) return redirect("warden_view:notice-warden2") context = { 'form': form, 'user': request.user, } return render(request, 'warden_view/notice.html',context) i have four type of user. admin,warden,staff,student admin create warden warden create staff and staff create student . now i want send notice so that admin send notice to warden and warden send notice to their created staff note that one warden has many staff and it can send notice to its only staff so how can i filter specific warden created staff -
Avoid duplicate entries for the same field
I have a model choice in django. which has foreign key relationship with user model and items model. Each user can choose as many items as he wants from items model, the choice model will keep track of how many users have chosen what items. a particular user could be able to choose an item only once, but my problem is that when user1 select any item no other user can choose that one again. this is my code for choice fill. Views.py def choice_fill(request, cid): item_list = item.objects.all() title = "Choice Filling" page = "Choice Filling" if request.method == "POST": usr = user.objects.get(id=request.session['id']) # return render(request, 'success.html',{'stud':stud}) if usr.isactive != 1: messages.error(request, "Your registration process is incomplete.") else: if not choice.objects.filter(item_id_id=cid, isactive=1).exists(): userid = usr.id c = choice(user_id_id=studid, item_id_id=cid, isactive=1) c.save() else: return HttpResponse('multiple Entry for same college') models.py class user(models.Model): fullname = models.CharField(max_length=50) password = models.CharField(max_length=10) email = models.EmailField(unique=True) class item(models.Model): name = models.CharField(max_length=50) password = models.CharField(max_length=10) institute_code = models.IntegerField(unique=True) class choice(models.Model): user_id = models.ForeignKey(user, on_delete=models.CASCADE) item_id = models.ForeignKey(item, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.datetime.now()) updated_at = models.DateTimeField(default=timezone.datetime.now()) isactive = models.BooleanField() -
Is it possible to wrap Django code to ensure all database access for the ORM has "using" set by default?
I have a Django project that handles connections with multiple databases. I have a Database Router that handles the logic of which objects to store in a specific database which I easily use in my views, so no issue there at all. For example: class ClientDatabaseRouterMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, args, kwargs): if 'client_url' in kwargs: # kwargs = {key: value.lower() for key, value in kwargs.items()} thread_local.client_url = kwargs['client_url'].lower() else: if hasattr(thread_local, 'client_url'): del thread_local.client_url class ClientDatabaseRouter: def _default_db(self): from django.conf import settings if hasattr(thread_local, 'client_url'): db = thread_local.client_url if db in settings.DATABASES: return db else: if settings.DEBUG: if hasattr(settings, 'DEBUG_CLIENT_DB'): return settings.DEBUG_CLIENT_DB return None def db_for_read(self, model, **hints): instance = hints.pop('instance', None) if instance: if instance._state.db is not None: return instance._state.db if model._meta.app_label == 'client': return 'clients' if model._meta.app_label == 'django_celery_beat': return 'default' return self._default_db() db_for_write = db_for_read def allow_relation(self, obj1, obj2, **hints): return obj1._state.db == obj2._state.db def allow_migrate(self, db, app_label, model_name=None, **hints): if db == 'default': return app_label == 'django_celery_beat' if not app_label == 'client': if db == 'clients': return False else: return db == 'clients' return None However, I also use Celery and … -
How can I retrieve form data from Django CreateView?
I have a Django blog where the users can set the status of each post (active, inactive) when creating them. I am using Django's generic class-based views and would like to redirect the user to their created post only when the status is set to "active", otherwise they should be redirected to the homepage. How can I retrieve this submitted info from the form to create an if statement? For example: if status == "a"... views.py from .models import Listing from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.views.generic import CreateView class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Post fields = ['title', 'status', 'content'] template_name = 'blog/post-form.html' success_message = 'Your post has been created.' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) -
How can I reference a user globally in Django for all Exceptions?
I have two questions that correlate. 1) Does django-rest-framework have a way to reference a user globally? 2) Does django / python allow me to change the generic exception class to include this user ID as meta every time it throws? I know I can create custom exception classes and raise them in code, but what about an exception I don’t correctly handle? For example, let’s say a divide by zero exception is thrown but I didn’t correctly handle it, right now my logs just say “Divide by zero exception”. Is there a way to update this globally so if a user is logged in it says “Divide by zero exception for user_id {id}“? class SomeExternalApiHelper: @staticmethod def do_api_call(): url = 'https://example.com' # do api request try: home_value = 100 / 0 except Exception as e: # Exception occurs here, I want to be able to reference user_id, without having # to pass the user_object all the way down into this call raise Exception("Something went wrong for user ID {0}".format(user_id)) class AddNewHouse(APIView): def post(self, request, format=None): # I can call request.user here and access the user object SomeExternalApiHelper.do_api_call() -
Django: Using current user as a foreign key to projects model
I am building a web-app where people can write projects. The projects are stored in a model and I want to use the user as the foreign key so I can show the user their projects on a webpage. Instances are entered through a form. The code always assigns the default value (1) and and not the user. Can any of you see what's causing this bug? Here is the code for the creation of the model in models.py: class PersonalProject(models.Model): user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() code = models.TextField() def __str__(self): return self.title Heres the code for the form view to create the project in views.py: def newproject(request): if User is None: messages.error(request, "Must be signed in") return redirect('main:dashboard') if request.method == "POST": form = NewProjectForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('main:dashboard') else: messages.error(request, "Error") else: form = NewProjectForm() return render(request, "main/newproject.html", {"form":form}) Heres the code for the homepage view in views.py: def dashboard(request): messages.info(request, request.user.username) return render(request=request, template_name="main/dashboard.html", context={"structuredprojects": StructuredProject.objects.all(), "personalprojects": PersonalProject.objects.filter(user__username=request.user.username)}) I really hope you can help - I've been stuck on this for a while -
no python application found for uwsgi setting
I am setting with djano and uwsgi $uwsgi --ini uwsgi.ini My Django root is here /var/www/html/myapp/current It must be quite simple setting however I am not sure the yet. I have these two files /var/www/html/myapp/current/myapp/settings.py /var/www/html/myapp/current/myapp/wsgi.py [uwsgi] chdir=/var/www/html/myapp/current module=myapp.wsgi:application env DJANGO_SETTINGS_MODULE=myapp.settings http-socket = 0.0.0.0:8008 processes = 1 threasds = 1 master = 1 max-requests = 100000 The error is below, but I can't dig the detailed logs. spawned uWSGI worker 1 (pid: 27353, cores: 1) --- no python application found, check your startup logs for errors --- [pid: 27353|app: -1|req: -1/1] 172.17.1.143 () {28 vars in 334 bytes} [Thu Mar 26 17:37:01 2020] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) -
Business logic in django manager outside of query interaction
This will be a spin-off about the infinite dispute on where to put your business logic in Django. After reading tons of related question on Stack Overflow and the django docs, I'm still undecided whether to put business logic in a separate module (e.g. service.py) or encapsulate it inside a model.Manager. What cause me esitating on using manager in this case is its intro in the django doc: A Manager is the interface through which database query operations are provided to Django models Indeed, I need to create a function which autonomously analyses data from a model and passes them to a view that will forward them to the front-end. This is not actually a query the front-end performs on the db. Rather, it's the back-end notifying the user if a particular data has been found. So, according to the django doc, this is not exactly the case for relying on manager. -
Reverse for 'remove' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['remove\\/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)\\/\\$$']
I want the remove obj function to be triggered when the user click on it but its throwing error I have tried searching but cannot find solution I want to display a list ob objects and as soon as a user clicks on the object it gets deleted patients.html <body> {% include 'pages/nav.html' %} <div class="container"> <p>patients <a class="btn btn-primary btn-lg" role ="button" href="/patientadd">Add Patients</a> </p> <div class="list-group"> <br> <br> {% for i in names %} <a href="{% url 'remove' pk=i.pk %}" class="list-group-item">{{i}}</a> {% endfor %} </div> </div> </body> views.py not the whole view def removeObj(request, pk): object = get_object_or_404(request,pk) object.delete() model.py from django.db import models from django.contrib.auth.models import User class Patient(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) age = models.IntegerField() numvisit = models.IntegerField() detail = models.TextField(max_length=300) # url pattern urlpatterns = [ path('admin/', admin.site.urls), path('register/',register,name="register"), path('patients/',patients,name="patients"), path('patientadd/',patientAdd,name="patientadd"), path('login/',login,name="login"), path(r"remove/(?P<pk>\d+)/$",removeObj,name="remove"), path('register/logout/',logout,name="logout"), path('',home), ]