Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Name a file from man-to-many field on model save django
I would like to save an image with specific name depending on other model fields, specifically, many-to-many field.The problem occurs when I try to access the tags post_save(or son save()) which gives me None tags. def path_to_upload(instance, filename): ext = filename.split('.')[-1] if instance.category: upload_to = 'images/' + instance.category.category_dir filename = 'Meme-{}-{}.{}'.format(instance.category.title, uuid4().hex, ext) else: upload_to = 'images/uncategorized/' filename = 'Meme-{}-{}.{}'.format('uncategorized', uuid4().hex, ext) return os.path.join(upload_to, filename) class Meme(models.Model): title = models.CharField(max_length=1024, default='') category = models.ForeignKey(Category, null=True, on_delete=models.PROTECT) tags = TaggableManager() image = models.ImageField(upload_to=path_to_upload, default='') image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(350, 200)], format='JPEG', options={'quality': 50}) slug = models.SlugField(max_length=355, blank=True, default='') def save_meme(sender, instance, **kwargs): print(instance.tags.all()) post_save.connect(save_meme, sender=Meme) on print it gives me empty QuerySet -
Like button only works for the first post irrespective of which post is liked
I tried to build a like button where i created a model for it - PREFERENCE, now the problem I have is that I cant seem to like other post as only the first post will be like, For instance if i Like POST A, and try to like POST B, it will go back and unlike POST B. This is where i defined it in the views.py @login_required def postpreference(request, postid, userpreference): if request.method == "POST": eachpost= get_object_or_404(Post, id=postid) obj='' valueobj='' try: obj= Preference.objects.get(user= request.user, post= eachpost) valueobj= obj.value valueobj= int(valueobj) userpreference= int(userpreference) if valueobj != userpreference: obj.delete() upref= Preference() upref.user= request.user upref.post= eachpost upref.value= userpreference if userpreference == 1 and valueobj != 1: eachpost.likes += 1 eachpost.dislikes -=1 elif userpreference == 2 and valueobj != 2: eachpost.dislikes += 1 eachpost.likes -= 1 upref.save() eachpost.save() context= {'eachpost': eachpost, 'postid': postid} return redirect('blog-home') elif valueobj == userpreference: obj.delete() if userpreference == 1: eachpost.likes -= 1 elif userpreference == 2: eachpost.dislikes -= 1 eachpost.save() context= {'eachpost': eachpost, 'postid': postid} return redirect('blog-home') except Preference.DoesNotExist: upref= Preference() upref.user= request.user upref.post= eachpost upref.value= userpreference userpreference= int(userpreference) if userpreference == 1: eachpost.likes += 1 elif userpreference == 2: eachpost.dislikes +=1 upref.save() eachpost.save() context= {'post': eachpost, … -
Search static content ( HTML files ) Django 3.1.2
Django 3.1.2 provides search functionality that works great for modeled data, but I need to make it work for static content too (basically HTML files). what is the best way to do it? I want to search for any word or page title in whole website. -
Modify the appearance per site (multisite) on django-cms
Today I have an instance of Django with several sites on it. The basic template is shared between all sites. I'd like to be able to customize the look and feel per site. Example: being able to change the default font per site from the admin. Or to be able to change the appearance of the menu per site from the admin. What are the best practices for doing this? What do you recommend? -
(DJANGO) How to display a list of categories and associated products on one page in django templete?
There are two categories: class Category(models.Model): name = models.CharField(_('category Name'), max_length=64) ... class Book(models.Model): title = models.CharField(_('book Title'), max_length=256) category = models.ForeignKey(Category, related_name='category_book') ... How to make the view one request to display in the template list of categories connected with the book. For example: Fiction: book 1 book 2 Story: book 3 book 4 book 5 etc.. -
Django Cassandra index on map Entries
I have a model as follows: from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel class Event(DjangoCassandraModel): assessment_id = columns.UUID(partition_key=True) type = columns.Text(partition_key=True) fire_time = columns.DateTime(primary_key=True, default=now, clustering_order="DESC") id = columns.UUID(primary_key=True, default=uuid.uuid4, clustering_order="ASC") data = columns.Map(key_type=columns.Text, value_type=columns.Text, default=dict, index=True) I have set index=True on data column but this creates index on map values. I want to create index on map entries. -
Map Form Fields with Model Fields in Django
I am new to django and trying to create a simple form. I am using django 3.1.2 and python 3.8.3. Below is my code model class Category(models.Model): categoryid = models.AutoField(primary_key=True) name = models.CharField(max_length=50) class Meta: managed = False db_table = 'category' def __str__(self): return u'{0}'.format(self.name) class Timesheet(models.Model): timesheetid = models.AutoField(primary_key=True) categoryid = models.ForeignKey(Category, models.DO_NOTHING, db_column='categoryid') summary = models.CharField(max_length=100) description = models.CharField(max_length=1000, blank=True, null=True) logdate = models.DateField() minutes = models.IntegerField(blank=True, null=True) addeddate = models.DateTimeField(default=datetime.now()) modifieddate = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'timesheet' form class TimesheetForm(forms.ModelForm): categoryid = forms.ModelChoiceField(queryset=Category.objects.all().order_by('name'), empty_label="Select Category",required=True,label='Category',to_field_name='categoryid') class Meta: model = Timesheet fields = ['summary','description','logdate','minutes'] view def fill_timesheet(request): form = TimesheetForm() if request.method == "POST": form = TimesheetForm(request.POST) if form.is_valid(): print(form.cleaned_data['summary']) print(form.cleaned_data['description']) print(form.cleaned_data['categoryid']) form.save(commit=True) return index(request) else: print('ERROR FORM INVALID') return render(request,'app_timesheet/timesheet.html',{'timesheet_form':form}) Below is my web page I am getting below error whenever try to save data null value in column "categoryid" violates not-null constraint DETAIL: Failing row contains (32, null, test data, test description, 2020-10-13, 5, 2020-10-15 14:25:40.57836, null). also, print(form.cleaned_data['categoryid']) statement of fill_timesheet view is printing category name instead of categoryid. My question is how can I link categoryid of form with categoryid of model. I want to show drop down of … -
Q objects in filter **arguments
When I query in Django and the query depends on filters I always do something like this: if country: country_arguments = {"country": country} else: country_arguments = {} sites.filter(**country_arguments).all() Now I need a Q() in that argument. The argument should be something like this: if supplier: arguments = {Q("supplier": supplier) | Q("supplier__parent": supplier)} else: arguments = {} But python interpreter gives "Illegal argument for variable annotation" Is this possible? -
File "<input>", line 1, in <module> in django
hi i have this problem when i try to add items to my cart i have this error : ... Traceback (most recent call last): File "", line 1, in NameError: name 'OrderItem' is not defined ... ... Traceback (most recent call last): File "", line 1, in NameError: name 'Order' is not defined ... i did migrate what is problem?? views.py def details(request , slug): pr = get_object_or_404(Product , slug=slug) category = Category.objects.all() if request.method == 'POST': product = Product.objects.get(slug=slug) # Get user account information try: customer = request.user.customer except: device = request.COOKIES['device'] customer, created = Customer.objects.get_or_create(device=device) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) orderItem.quantity = request.POST['quantity'] orderItem.save() return redirect('cart') context = { 'products': pr, 'similar' : similar, 'category' : category } return render(request, "prDetails.html" , context) and my html : <form class="product-form" method="POST" action="{% url 'cart' %}"> {% csrf_token %} <div class="product-form-control"> <div class="counter-area"> <span class="counter-button minus">-</span> <input min="1" value=1 type="number" name="quantity"> <input class="btn btn-dark" type="submit" value="Add to Cart"> </div> </div> </form> -
Django PDF File View in HTML Page, how to create path/url file?
I have a pdf project: my models.py: class Dokumen(models.Model): pdf = models.FileField(upload_to='pdf/%Y/%m', blank=True, null=True, verbose_name="FILE PDF") my views.py: def detailDokumen(request, pk): dokumen = get_object_or_404(Dokumen, id=pk) form = DokumenForm(instance=dokumen) if request.method == 'POST': form = DokumenForm(request.POST or request.FILES, instance=item) if form.is_valid(): form.save() return redirect(reverse('detail_doc')) context = { 'form': form, 'instance': dokumen, } return render(request, 'doc_details.html', context) urls.py: urlpatterns = [ path('doc_detail/<int:pk>/', detailDokumen, name='doc_detail'), ] my templates: <body> <div class="page-wrapper" style="font-family: Times New Roman;"> <div class="page-breadcrumb"> <div class="row embossed"> <a class="col-md-3 col-lg-3 animated bounceInRight ml-2 mr-2 mb-2 btn badge-pill badge-info" href="{% url 'doc_list' %}" type="submit"><b><i class="mdi mdi-buffer mr-2"></i>DAFTAR DOKUMEN</b></a> </div> </div> <div class="container-fluid"> <div class="card" style="padding-right: 10px;padding-left: 10px;"> <div class="card card-header mb-1 mt-2 card-hover" style="background-color: #74cfbf;"> <h5 style="text-align: center;"><strong>DETAIL DOKUMEN</strong></h5> </div> <div class="card card-body mb-2" style="background-color: #74cfbf;text-indent: 5px;"> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="form-row" style="vertical-align: middle;"> <div class="form-group col-md-4 mb-2"> {{ form.departement|as_crispy_field }} </div> </div> <div class="form-row" style="vertical-align: middle;"> <div class="form-group col-md-4 mb-2"> {{ form.no_dokumen|as_crispy_field }} </div> <div class="form-group col-md-4 mb-2"> {{ form.title|as_crispy_field }} </div> <div class="form-group col-md-4 mb-2"> {{ form.jenis_dokumen|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-4 mb-2 input"> <div class="mb-2"><strong>TGL. PEMBUATAN: {{ instance.tgl_dibuat|date:'d-m-Y' }}</strong></div> {{ form.tgl_dibuat }} </div> <div class="form-group col-md-4 mb-2"> {{ form.status|as_crispy_field }} </div> … -
Django admin page style
im new to django, i created a superuser for the admin page and i installed bootstrap3 as well and put it in the installed app section. My admin page however has no style compared to the tutorial im using I have bootstrap3 installed and put it in settings.py section. if you need more info you can ask, im new to stack overflow as well link to the image/screenshot -
Send emails to particular users on certain time using celery
I am trying to send emails on a defined time for each event according to the model below, using celery. I have a model like this, class Events(models.Model): start = models.DateTimeField() # More Fields here class EventList(models.Model): event_id = models.ForeignKey(Events, on_delete=models.CASCADE) # And a list of users who have opted for this event Now, users can opt to receive an e-mail for certain event (mail will be sent an hour before the event). My question is that, in tasks.py how do I go about writing a function for this. Should I use a while loop for setting up the shared_task and send email whenever the time comes for particular event or there is a different approach? I know there are many answers out there but most of them are to send emails to all the users periodically, I couldn't find much for this use case. -
Django: Custom default Manager with user based queries for all views/interfaces (custom, admin, graphene, rest, ...)
In Django I'm trying to implement some kind of a "security middleware", which gives access to certain db information only, if the logged in user matches. Up to now I found two approaches: middleware or custom function in manager (Both explained here Django custom managers - how do I return only objects created by the logged-in user?). Example for cleanest solution: custom function class UserContactManager(models.Manager): def for_user(self, user): return self.get_query_set().filter(creator=user) class MyUser(models.Model): #Managers objects = UserContactManager() # then use it like this in views data = MyUser.objects.for_user(request.user) However, this solution only works, if you have control over the code which invokes this custom function (here: for_user()). But if you are using third parties apps like Django-REST, Graphene or AdminViews, they don't have the possibility to configure a specific query-func to use. My goal: Replace the default Manager Add user-based filters to query_set Use the model as normal in all app configurations Idea (pseudo code!) from django.x import current_user class UserBasedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(author=current_user.name) class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=50) objects = UserBasedManager() # The default manager. Now I could use the model Book as normal in all extension. My use case I have a project, which shall … -
how to make ' add choice in admin panel ' see description
i want add an '+ or add' inside add new record i mean when i add new record in admin panel and i have name box and i want add many names when click on + or add how to do that model.py : class Android(models.Model): name = models.CharField(max_length=50,default="") def __str__(self): return self.name i tried add many name field but it's not what i want ,, i tried something like that class Android(models.Model): name = models.CharField(max_length=50,default="") name = models.CharField(max_length=50,default="") name = models.CharField(max_length=50,default="") def __str__(self): return self.name -
Add additional amount to stripe checkout
I have working on E-commerce website using python/Django. I have integrated stripe payments where carts items are dynamically passed as line items . I added as delivery fee if the cart value is less than Rs.500. Current using the stripe session Api for checkout process. I want to add the delivery fee as extra amount to the checkout line items price. Thanks in advance @csrf_exempt def createCheckoutSession(request): if request.method=='GET': domain_url='http://localhost:8000/' stripe.api_key= settings.STRIPE_SECRET_KEY profile = UserProfile.objects.get(user__id=request.user.id) try: customer = stripe.Customer.retrieve(profile.stripe_id) print (customer) profile = UserProfile.objects.get(user__id=request.user.id) checkoutSession = stripe.checkout.Session.create( success_url =domain_url+'success?session_id={CHECKOUT_SESSION_ID}', cancel_url =domain_url+'cancelled/', payment_method_types = ['card'], mode='payment', line_items= get_line_items(request)[0], customer= profile.stripe_id, ) return JsonResponse({'sessionId':checkoutSession['id']}) except Exception as e: return JsonResponse({"error":str(e)}) -
Adding password confirmation for user authentication for api development
I have this User which UserManager extended form BaseUserManager. In admin page for this model, I have password1 and password2 in addfieldsets. Cant I use this password1 and password2 inside the field of User model in serializers?? I want to make an api, so that user can have the password confirmation field as well. In, the default dajngo admin page, If want to create a user, then I can input password and password confirmation because its in the addfieldset in the admin.py. I want same in api as well. This is my model. class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): """Creating new user and saving the user.""" if not email: raise ValueError('Admin must have a valid email') user = self.model(email=self.normalize_email(email), **kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Creates and saves a new super user""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """ Custom user model that supports using email instead of username """ email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = 'email' This is my admin page. class UsersAdmin(UserAdmin): ordering = ['id'] list_display = ['email', 'first_name', … -
How to add my own permissions to the admin?
Right, so I am working on an app and I want to limit user access based on their permissions. Issue is that the list that Django generates automatically is not that usable for me. Rather, I would prefer to have one larger permission set, that I can check to see if user has access to the section of the site. So rather than check for app.model.can_view, app.model.can_edit, etc., I would prefer to just check app.has_access_to or something similar. Or perhaps app.can_view and app.can_edit. In my admin view, there doesn't seem to be any way to add custom permission rules, and all sites I lookeu up only talked about adding permissions to a group. Is there any way to add custom permission rules in Django? -
Bootstrap scrollSpy not always work in django template
I work on a django blog using wagtail CMS. Recently I undertook to add the bootstrap scrollSpy, on blog post pages, to highlight titles in the side table of contents regarding the section on which the reader is. I follow the bootstrap tutorial trying the html data- way et the javascript way but my table of content, on some page, higlights only the first item, sometimes only the last, on some page it worked and sometime never highlight. So I search for response on different questions but no answer resolve my issue. May be my problem comes from my django/wagtail template that it looks like that: In base.html: <head> <link rel="stylesheet" href="https://bootswatch.com/4/minty/bootstrap.min.css" crossorigin="anonymous"> </head> <body class="{% block body_class %}{% endblock %}"> <div class="col-md-9"> {% block content %} {# Where blog post content is #} {% endblock %} </div> <div class="col-md-3"> <div class="position-fixed"> {% block side_widget %} {# Where table of contents is #} {% endblock side_widget%} </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> {% block extra_js %} {# Override this in templates to add extra javascript #} {% endblock %} </body> In blog_page.html that is including base.html: {% extends "base.html" %} {# Blog … -
Real-time tracking with Google assets tracking
I want add real-time tracking for our app Courier. What ready-made solutions are available for such task? Found Google assets tracking but nothing is clear from the documentation. Can i integrate google assets tracking without google maps? -
set_wakeup_fd only works in main thread Python 3.8.2. Django 3.0.6 apache v3.2.4
203/5000 Hello I have a problem with error set_wakeup_fd only works in the main thread. The application works but every now and then this error was found. I know that there are several answers to this problem, but it does not help me. Python 3.8.2. Django 3.0.6 apache v3.2.4 Windows server 2012 ValueError at /art_chem/ set_wakeup_fd only works in main thread Request Method: GET Request URL: http://localhost/art_chem/ Django Version: 3.0.6 Exception Type: ValueError Exception Value: set_wakeup_fd only works in main thread Exception Location: C:\Python38\lib\asyncio\proactor_events.py in __init__, line 632 Python Executable: C:\xampp\apache\bin\httpd.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\k.kowalski_1\\Desktop\\Magazyn', 'C:\\Python38\\python38.zip', 'C:\\Python38\\DLLs', 'C:\\Python38\\lib', 'C:\\xampp\\apache\\bin', 'C:\\Python38', 'C:\\Python38\\lib\\site-packages'] -
Django Cassandra Engine multiple primary keys
I have a model with multiple partition and clustering keys as follows: from django_cassandra_engine.models import DjangoCassandraModel from cassandra.cqlengine import columns class Event(DjangoCassandraModel): assessment_id = columns.UUID(partition_key=True) type = columns.Text(partition_key=True) fire_time = columns.DateTime(primary_key=True, default=now, clustering_order="DESC") id = columns.UUID(primary_key=True, default=uuid.uuid4, clustering_order="ASC") data = columns.Map(key_type=columns.Text, value_type=columns.Text, default=dict, index=True) on running python manage.py sync_cassandra I get the Runtime error: On Django Cassandra Models with more than one primary_key field, The model <class 'ws.models.Event'> must specify class Meta attribute 'get_pk_field'. E.g. class Meta: get_pk_field='id' So that Django knows which primary key field to use in queryies such as Model.objects.get(pk=123) -
Gunicorn : ModuleNotFoundError: No module named 'insitu.wsgi'
I'm following this tutorial to deploy a django application https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 I'm facing a problem at gunicorn step, here is the log : Oct 15 06:31:09 ubuntu-s-1vcpu-1gb-lon1-01 gunicorn[50835]: ModuleNotFoundError: No module named 'insitu.wsgi' Oct 15 06:31:09 ubuntu-s-1vcpu-1gb-lon1-01 gunicorn[50835]: [2020-10-15 06:31:09 +0000] [50835] [INFO] Worker exiting (pid: 50835) Oct 15 06:31:09 ubuntu-s-1vcpu-1gb-lon1-01 gunicorn[50833]: [2020-10-15 06:31:09 +0000] [50833] [INFO] Shutting down: Master Oct 15 06:31:09 ubuntu-s-1vcpu-1gb-lon1-01 gunicorn[50833]: [2020-10-15 06:31:09 +0000] [50833] [INFO] Reason: Worker failed to boot. Here is my gunicorn.service file : [Unit] Description=gunicorn daemon After=network.target [Service] User=djangoadmin Group=www-data WorkingDirectory=/home/djangoadmin/insitu-live ExecStart=/home/djangoadmin/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/djangoadmin/insitu-live/insitu.sock insitu.wsgi:application [Install] WantedBy=multi-user.target I don't know why the module insitu.wsgi is not found, because it exists. Can someone help me on that ? Thank you -
How to remove a permission from model?
So I had a permission in my model class like this: class Meta: permissions = (("can_send_messages", "Can send messages"),) This automatically created a migration that does this: operations = [ migrations.AlterModelOptions( name='organization', options={'permissions': (('can_send_messages', 'Can send messages'),)}, ), ] Now I removed class Meta and the permission from my model class. How do I make a migration that will undo that automatically created migration? -
How to set and print the value of json object in postgresql?
What I have done till now is : DO $do$ DECLARE namz Text; jsonObject json = '{ "Name": "Kshitiz Kala", "Education": "B.Tech", "Skills": ["J2EE", "JDBC", "Html"] }'; BEGIN SELECT jsonObject->'Name' into namz; select namz; END $do$ I am not finding any success here. actual problem is I am passing a json Object to a stored procedure which will store the data in three different table 1) user table contains user_id, user_name, user_edu. 2) skill table contain skill_id, skill_name. 3) user_skill table contain id, user_id, usr_skill_id. This is the json object I am passing from Django application {"Name": "Kshitiz Kala", "Education": "B.Tech", "Skills": ["J2EE", "JDBC", "Html"]} -
Page not found (404) is reporting
There is 'Page not found(404)' error that has been showing since yesterday but before that everything was working great. The program was running on the same URL path but now it isn't, please tell your suggestions. Thank You! urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from Platform import views urlpatterns = [ path('/admin/', admin.site.urls), path('/Home/', views.home, name='home'), path('/blog/', include('blog.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in Portfolio.urls, Django tried these URL patterns, in this order: /admin/ /Home/ [name='home'] /blog/ ^media/(?P<path>.*)$ The empty path didn't match any of these.