Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Try/except/else implementation of a 'unique_together' django constraint
I recently realized while writing tests that the unique_together constraint I added in my models did not work with foreign keys accepting null values (Cf this discussion). Since I already had to override the models .save() method, I though about coding this constraint in it. Goal: make sure that no category could have the same name and parent I firstly tried an if else using exists() on a filtered query set but it did not seem to work. @abstractmethod def save(self, *args, **kwargs): self.path = str(self) if type(self).objects.filter(name = self.name, parent = self.parent).exists(): raise ValidationError("A category with same name and parent already exists") else: super(Category, self).save(*args, **kwargs) I then switched to a get approach. Query to check whether the object exists. If it does not exists, get raises a ObjectDoesNotExist and the normal save() should occur. class Category(models.Model): class Meta: abstract = True parent = models.ForeignKey('self', null=True, blank=True, related_name='nested_category', on_delete=models.SET_NULL) name = models.CharField(max_length=50) path = models.CharField(default = "", max_length=50, editable=False) count = models.PositiveSmallIntegerField(default=0, editable=False) @abstractmethod def save(self, *args, **kwargs): # HERE !!!!!! self.path = str(self) try: type(self).objects.get(name = self.name, parent = self.parent) except ObjectDoesNotExist: super(Category, self).save(*args, **kwargs) else: raise ValidationError("A category with same name and parent already exists") class Article_category(Category): … -
Django 2.1 Form Wizard for Model Forms with foreign Key
i have two models parent and child model, the parent model holds the value of the startup_name while the child model have a foreign key referanced to it and it is dynamic multi fields to create team members, the foreign key fields 'startup' in child model must be set automaticaly to the value of startup name field. how can i achieve that in Wizard form. from django.db import models class Startup ( models.Model ) : startup_name = models.CharField ( 'Startup Name' , max_length = 100 ) def __str__(self) : return self.startup_name class Team ( models.Model ) : name = models.CharField ( 'Name' , max_length = 100 ) position = models.CharField ( 'Position' , max_length = 100 ) startup = models.ForeignKey ( Startup , on_delete = models.CASCADE ) def __str__(self) : return self.startup -
redis Error condition on socket for SYNC: Connection refused
I have a server running with celery and redis. After maybe 1 day of working processing more than 200k messages, redis shutdowns. I tried to search for the error but as I am not an expert in redis, found no relative clue: redis_1 | | `-._ `._ / _.-' | PID: 1 redis_1 | `-._ `-._ `-./ _.-' _.-' redis_1 | |`-._`-._ `-.__.-' _.-'_.-'| redis_1 | | `-._`-._ _.-'_.-' | http://redis.io redis_1 | `-._ `-._`-.__.-'_.-' _.-' redis_1 | |`-._`-._ `-.__.-' _.-'_.-'| redis_1 | | `-._`-._ _.-'_.-' | redis_1 | `-._ `-._`-.__.-'_.-' _.-' redis_1 | `-._ `-.__.-' _.-' redis_1 | `-._ _.-' redis_1 | `-.__.-' redis_1 | redis_1 | 1:M 23 Aug 2019 17:16:37.063 # Server initialized redis_1 | 1:M 23 Aug 2019 17:16:37.063 * Ready to accept connections redis_1 | 1:S 24 Aug 2019 15:22:59.018 * Before turning into a replica, using my master parameters to synthesize a cached master: I may be able to synchronize with the new master with just a partial transfer. redis_1 | 1:S 24 Aug 2019 15:22:59.018 * REPLICAOF 192.3.70.16:20012 enabled (user request from 'id=26 addr=192.3.70.16:54498 fd=21 name= age=0 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=46 qbuf-free=32722 obl=0 oll=0 omem=0 events=r cmd=slaveof') redis_1 | 1:S … -
self variable declare inside class method
want to declare instance variable inside a @classmethod a=20 def __init__(self): self.a=10 self.b=20 def m1(self): self.a=30 self.c=50 @staticmethod def m2(x,y): x=90 y=120 @classmethod def m3(cls): self.a=90 #its showing error here in self keyword cls.z=200 print('class method') class c(p): pass c=c() print(c.a) print(c.b) c.m1() c.m2() c.m3() I have used a self keyword inside the class method. I know there is only one way to declare the instance keyword in a class by using self keyword only @classmethod def m3(cls): self.a=90 #its showing error here in self keyword cls.z=200 print('class method') -
Security in Django API
I have created the sign up Api in Django Rest FrameWork without authentication or any permissions and i want to use is it in mobile app. my question is this api secure??? any person or Robots that access to the SignUp Api Url can create Account nonstop. -
current user be admin
I have a djanog project, my problem is in the first time the current user is the logged one but if I refresh the browser, in the request.user I found the admin , how can the overcame this issue ? this is my view : def countries_rate(request): auth_user = request.user if request.user.is_authenticated: auth_user = request.user if (user_rate.objects.filter(user_id=auth_user).delete()): print(auth_user,' OK deleted ----------------.................') formset = countriesFormset(request.POST or None) if request.method == 'POST': if 'Add_More' in request.POST: #print('--- add more in post -----') cp = request.POST.copy() cp['form-TOTAL_FORMS'] = int(cp['form-TOTAL_FORMS'])+ 1 formset = countriesFormset(cp,prefix='form') total = cp['form-TOTAL_FORMS'] #print('total forms {}---------------------',format(total)) return render(request,'thesis_app/countries_rate.html', context={ 'formset':formset, 'total':total }) elif 'submit' in request.POST: if formset.is_valid(): for inst in formset: rate = user_rate() if inst.is_valid(): #answer2 =inst.save(commit = False) #answer2.user_id = auth_user countries_name_id = inst.cleaned_data.get('countries_name_id') country_rating = inst.cleaned_data.get('country_rating') rate.user_id = auth_user rate.countries_name_id = countries_name_id rate.country_rating = country_rating #print(auth_user,"................") rate.save() return redirect('thesis_app:result') else: return redirect('thesis_app:login') user = request.user formset = countriesFormset(request.POST or None) return render(request,'thesis_app/countries_rate.html', context={ 'user':user, 'formset':formset } ) -
Restrict items shown by django-filter
How can I limit items shown by django-filter? I mean restrict them and show part of it for each user. -
Images not being shown in sent emails
I am developing a site using django, and I plan on sending notifications via email. In the emails, I have a a few images such as logo etc. For emails, I am using smtp with sendgrid. In the email template, I have the full image src: <img src="https:www.mysite.com/static/images/logo.png" alt="Logo" title="Logo"> when I copy and paste the src in the browser, I see the image. However, in both gmail and outlook, the image is not there. It looks like they are caching it, and using their own version of the image, but it's not there. -
images arent displaying from db in django 2.2 even if i get my uurl correct and include static and media root in settings and url
my image isnt displaying . I have tried putting all the urls and roots for static and media but it isnt working for 2.2 version. #in settings.py STATIC_URL = '/static/' STATIC_ROOT=os.path.join(BASE_DIR,'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #in main urls.py + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) #in app urls .py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
celery 4.3.0 : get variable from inside current task
I have this task which is designed to bulk insert or delete objects in database : views.py from .tasks import run_task_with def index(): # some code to retrieve obj_list run_task_with(insert_obj, obj_list).delay() return HttpResponseRedirect('/app_root/') tasks.py @shared_task def run_task_with(func, queryset): cache.add('current_task_id', run_task_with.request.id) obj_numb = len(queryset) r = map(func, queryset) for i, obj in enumerate(r): sleep(0.1) progress_percent = int(round(float(i) / float(obj_numb) * 100)) current_task.update_state( state='PROGRESS', meta={'progress_percent': progress_percent} ) But run_task_with.request.id keeps returning None even while object insertions runs smoothly. Could anyone explain to me why ? Thanks -
Django grabing before the BASE_DIR path
I am trying to set my static file before the base_dir file like, My root dir is Desktop/afolder/projectdir/settings.py and my current static file in Desktop/afolder/static/blabla.js And grab it like with STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Above those works great, but now i am changing my static file dir, it will be now before the base dir like: Desktop/static/blabla.js In this case, i am in trouble to configure my setting so that it get my static files. coz, it is before the base dir, my base dir is afolder like Desktop/afolder/projectdir/settings.py Can anyone help me to recognize the static file of this dir Desktop/static/blabla.js ? -
ModuleNotFoundError at /login/ No module named 'accounts'? Django deployement
I'm using heroku to deploy my django blog web-app. But when I login it gives me no module name 'accounts' error in production even though I don't have any accounts app or related name in my project Anyone know how to fix it. I'm using AWS S3 as my database. -
Using dictionary inside jinja
I am trying to access the 'title' key of a dictionary {% for article in articles %} {{ article['title'] }} {% endfor %} I am getting this error: Could not parse the remainder: '['title']' from 'article['title']' -
Providing the functionality for users to give answers
I am creating a front-end page, where the admins will be posting the questions and the users will be answering to those questions, facing a problem on how to give the space for users to post their answers and and provide functionality like bold,italic, and post images their , or this functionality can only be done through the backend portion,any plugin or anything. Any easy and simple method and elaborated explanations please. -
CSS not working in Django admin: The resource from [css file url] was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff
Django admin is displaying without CSS because of the error: The resource from “my-website-address/static/admin/css/responsive.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). The CSS url I can open in my browser and it looks fine. What can I do to fix CSS displaying for standard Django admin interface? -
Unable to display two forms in a view - Django
I have two related models (Sim and Payment - A Sim can have many Payment). On searching of Sim (by ID ) i want its detail to be populated in a form (which i am able to). But using the same form i want to save the details of Payment model as well and at the same time want to update the Sim model as well. I am able to populate only Sim form using the id but the AddPaymentForm is not populating. def updatePayment(request, id): sim = get_object_or_404(Sim, pk=id) payment = AddPaymentForm() sim_form = UpdatePayment(request.POST, instance=sim) if request.method == "POST": # sim_form = UpdatePayment(request.POST, instance=payment) payment_form = AddPaymentForm() try: if payment_form.is_valid(): payment_form.save() sim_form.save() messages.success(request, ("Payment has been updated")) else: messages.warning(request, ("Data in fields is incorrect, please try again")) except Exception as e: messages.warning(request, ("Error: {}".format(e))) else: form = UpdatePayment(instance=sim) payment = AddPaymentForm() context = {'payment': payment, 'form': form,} return render(request, 'payment/updatePayment.html', context) -
Restirct items shown by django-filter package
I have a book model in my Django app and each book has an author. My models are #models.py class book(models.Model): title = models.CharField() author = models.ForeignKey(User, on_delete=models.CASCADE) class comment(models.Model): book = models.ForeignKey(book) in my app each user can comment on a book and each author can login and see the comments. I wanted to filter comment by the book for the author and each author could only see its own books in the filter items. How could I achieve this? -
How to post an external url in your website
I am now to django and web programming. I'm trying to make a practice site that shows the search result of another website. I use $requests$ to get the page and $Httpresponse$ to show the page result but the result page does not display the table an the images. when I open the html with my browser there are I don't want to use iframe because there is a button on the page that I do not like to appear in my page def index(request): ... if request.method == 'POST': # If the form has been submitted... html=requests.get(url).text return HttpResponse(html) Failed to load resource: the server responded with a status of 404 (Not Found) info-small.png:1 Failed to load resource: the server responded with a status of 404 (Not Found) (index):63 Uncaught ReferenceError: $ is not defined at (index):63 warning-32.png:1 Failed to load resource: the server responded with a status of 404 (Not Found) (index):2134 Uncaught ReferenceError: $ is not defined at (index):2134 info-small.png:1 Failed to load resource: the server responded with a status of 404 (Not Found) -
django reservation system for trains(booking tickets)
i already made a django reservation system for trains(booking tickets)but only for 1 person at a time, now i fell like this is not enough and i need to make the user able to choose how many tickets he want to book(list from 1 to 9) then be able to book those multiple tickets in the same form at the end after choosing the trip im stuck Urls.py from django.urls import path, include, re_path from . import views urlpatterns = [ path('tickets/<int:ticket_id>/',views.tickets_page, name='tickets'), path('trips/<int:trip_id>/',views.trips_page, name='trips'), re_path(r'^from/(?P<start_station>[0-9]{1,50})/$', views.details_page, name='details_page'), path('', views.details_page, name='booking'), ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.core.exceptions import ValidationError from .models import Ticket, Trip from django.http import Http404 from django.shortcuts import get_object_or_404 import logging # Get an instance of a logger logger = logging.getLogger(__name__) # Create your views here. def details_page(request): if request.method == 'GET': end_station_id = request.GET.get('station') elif request.method == 'POST': end_station_id = request.POST.get('to_station') #print(request.GET.get('to_station')) trips = Trip.objects.filter(end_station_id=end_station_id) context = {'trips' : trips} return render(request, 'details/details.html', context) def trips_page(request, trip_id): trip = get_object_or_404( Trip,pk=trip_id) error = None ticket = None if request.method == 'POST': first_name = request.POST.get('first_name') middle_name = request.POST.get('middle_name') last_name = request.POST.get('last_name') email = request.POST.get('email') gender = request.POST.get('gender') ticket = Ticket(trip=trip,first_name=first_name, … -
form not saving email in django admin
django forms doesn't save email in the database.i try all sort of things but still it is the only thing that is not saving .I need help forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegistrationForm(UserCreationForm): email=forms.EmailField() class meta: model=User fields= ['username', 'email_address', 'password1','password2'] views.py code register(request): if request.method=='POST': form=UserRegistrationForm(request.POST) if form.is_valid(): form.save(commit=False) username=form.cleaned_data['username'] password1=form.cleaned_data['password1'] password2=form.cleaned_data['password2'] email_address=form.cleaned_data['email'] form.save() return redirect('/') else: form=UserRegistrationForm() return render(request, 'blog/register.html',{'form':form}) -
Filter those rows that have most rows in in a related table, while also doing a distinct query
I have a Media model that has a many-to-many relationship to Artist (one Media can have many artists and one Artist can belong to many media). Also each user can rate each Media through a relational table named UserMedia, one Media can have multiple UserMedia. I want to do a query where I order by most ratings (UserMedia), while also filter the queryset for distinct Artist, such that each artist appears only once in the queryset and that Media is returned with the most UserMedia related rows (or counts). I can do the two things separately, order by most counts or do a distinct artists filter. Here's the query that I have right now: distinct_artists = models.Media.objects.distinct("artists__id") queryset = ( models.Media.objects.annotate( count_ratings=Count("usermedia"), ).filter( count_ratings__gte=F("count_ratings") ) .order_by("-count_ratings") .filter( id__in=distinct_artists ) ) The resultset returns distinct Artist, but not the Media with the most counts of UserMedia for this artist. -
Django group by and order by
I have comment table with following fields. Here, first row means, 3rd comment in the database belongs to post 1. Second and third row means, 3rd and 4th comments belongs to post 1 and they are also replies to the 2nd comment and so on. id post_id comment_id date 2 1 ... 3 1 2 ... 4 1 2 ... 5 1 ... 6 1 5 ... I would like to do a django group by query so such that, to get all the comments of post 1 and group them by the replies to a comment. So I would expect groups like this group1: comment2: comment3,4 group2: comment5: comment6 The group query should also be ordered by date field. How can I do this? -
Add a new item to a related fields within a form
I want a user to be able to select from an existing list of options. If the option is not within the ones already in the database, though, they need to be able to add a new item, while remaining on the main form, because after having added the new item they need to be able to save the main form I was using the JQuery library select2, which allows a tags:True option, thanks to which users can add a new item to a list if not present. Nevertheless, Django validates that field and if it finds an item which is not in the database is raises an error. My initial plan was that of capturing the new value in the view and then (saving first the form with commit=False), if it was not in the database, save it. But this is not doable without forcing Django not to validate the field, which I haven't managed to do. Another option, which I'm currently investigating, is that of adding a modal pop-up containing the sub-form. Of course I'd like to avoid opening the sub-form in another page, which would work but would be quite non-user-friendly. models.py: class Venue(models.Model): venue_name = models.CharField(max_length=30) … -
Authentication view doesn't recognize html template
I'm using authentication views in my project https://docs.djangoproject.com/en/2.2/topics/auth/default/#module-django.contrib.auth.views path('accounts/', include('django.contrib.auth.urls')), in my urls My issue is when it comes to the PasswordChangeView the accounts/password_change url shows the django adminstration page instead of the template I have under posts\templates\registration\password_change_form.html -
How to use CLASS BASED VIEWS and tags + slug in urls with DJANGO 2,.1
I am not sure why but i am unable to access the ProductListView page. The terminal just throw the error below. django.urls.exceptions.NoReverseMatch: Reverse for 'products' with no arguments not found. 1 pattern(s) tried: ['products/(?P<tag>[-a-zA-Z0-9_]+)/$'] Full traceback below: Internal Server Error: / Traceback (most recent call last): File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/macadmin/Documents/Django_fun4/practical_django/practical_django/core/views.py", line 18, in home return render(request, 'core/home.html') File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/defaulttags.py", line 442, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/urls/base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, …