Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get context_type from request
I am looking for build-in solution in django or DRF for getting a context_type from request. I know that django createst a context_type records for each model in the project. Is there a solution that could helps me get context_type on a request basis? I need this for one purpose: I would like to check if the user from request has permisions on this context_type (I had my own role-based permission access) -
Django save multiple foreign keys to database with multiple upload
I am a newbie in Django and I am looking for the best workaround on how to deal with this problem. I have these 3 Models: class Rigs(models.Model): name = models.CharField(max_length=30) featured_img = models.ImageField(upload_to='images/') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Gallery(models.Model): rigs = models.ForeignKey(Rigs, on_delete=models.CASCADE, related_name='galleries') file = models.ImageField(upload_to='images/') def __str__(self): return self.name class Specs(models.Model): cpu = models.CharField(max_length=50) motherboard = models.CharField(max_length=50) rigs = models.ForeignKey(Rigs, on_delete=models.CASCADE) def __str__(self): return self.cpu I am using this library for the multi-uploading of images (https://github.com/Chive/django-multiupload), so basically I structured my Forms similar to what the document states: class SpecsForm(forms.ModelForm): class Meta: model = Specs fields = ('rigs', 'motherboard') class RigForm(forms.ModelForm): class Meta: model = Rigs fields = ('name','featured_img') gallery_image = MultiMediaField( min_num=1, max_num=3, max_file_size=1024*1024*5, media_type='image' ) def save(self, commit=True): instance = super(RigForm, self).save(commit) for each in self.cleaned_data['gallery_image']: Gallery.objects.create(file=each, rigs=instance) return instance As well as my Views: class newrig(CreateView): model = Rigs form_class = RigForm template_name = 'flexrigapp/newrig.html' success_url = '?success' My problem is that I couldn't figure out how to include the SpecsForm on my HTML Form as well as save it on my database with the correct Foreign Key. I have already tried transferring this one on my views with some changes … -
How to pass parameter to get_queryset in Django
I have Django API built in and I have endpoint the return all object. I want the user to provide me with keyword to filter this queryset. What is the best way to do it. and how to do it plz ? is it in get_queryset? if yes can you help me !? -
Is there a way to capture some text in a Django template as a template variable?
Here's a non-working example which illustrates what I'm trying to do. I've imagined some tags that don't really exist: {% capture variable=my_url %}http://baz.bar.foo/bof?a=b{% endcapture %} {{ my_url | urlencode }} If this were a working example, I would want it to produce a URLendcoded version of whatever text was in the "capture" tag, which in this case is a URL. -
python object does not initialize
I have the following python class: class GaugeHighChart(object): def __init__(self): print('in gauge object high cchart') self.credits: { 'enabled': False } I am trying to the initialize this object and then get the value of its attributes like this: def closures_gauge_view(request): highchart = GaugeHighChart() print(highchart.credits) I get the following error: AttributeError: 'GaugeHighChart' object has no attribute 'credits' -
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})