Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django button GET request with ajax
Its my button : <form action="{% url 'panel:lights' %}" method='GET'> {% csrf_token %} <button class="btn" type='submit' onclick=mybtn() >ON</button> </form> its my urls.py : app_name = 'panel' urlpatterns = [ path('panel', views.panel_views , name = 'panel'), path('light', views.light_views , name = 'lights'), its my views.py : def light_views(request): print ("finally worked") Device.objects.all() device = Device.objects.get(id=1) device.status = not device.status device.save() return redirect(request , 'panel/panel.html') and the error i get when i click button is : Reverse for '<WSGIRequest: GET '/panel/lightcsrfmiddlewaretoken=eIQ9rKiLaTvmOqMtXAoi9J1YcuOgEEtuaAlkV67hMk8iYZsXlEahyd7E62g5eXWu'>' not found. '<WSGIRequest: GET '/panel/light?csrfmiddlewaretoken=eIQ9rKiLaTvmOqMtXAoi9J1YcuOgEEtuaAlkV67hMk8iYZsXlEahyd7E62g5eXWu'>' is not a valid view function or pattern name. and the ajax code i used and it seems its wrong is : <script> function mybtn() { var xhttp; if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET","{% url 'panel:light' %}", true); xhttp.send(); }; </script> -
JSON from Django render() to React.js
I'm writing a simple Django + React Application in which I want to pass some JSON from Django render() to React.js. I first render an HTML page with Django, providing the JSON. Although I'm unaware of the format, the data is coming through, as I can show it using Django's template language. However, in the React code, which is called by the HTML page, I get the JSON as a string, and only the first 10 chars. I'm wondering whether there is a way to get this through properly, instead of having to write an http post every time. My Django views script, which renders the html: @login_required(login_url="/login/") def index(request): data = { 'key': [0, 1, 2, 3], 'key2': 'abcd', } context = { 'data': json.dumps(data), 'navItem': 0, } return render(request, "index.html", context) My index.html: <!DOCTYPE html> <html lang="en"> <body> {{data}} <div class="reactitem" data-json={{data}}></div> <script src="http://127.0.0.1:8080/index.js" charset="utf-8"></script> </body> </html> And lastly my index.js (locally hosted): document.querySelectorAll('#reactitem').forEach((domContainer) => { console.log(domContainer.dataset.json); console.log(typeof(domContainer.dataset.json)); console.log(domContainer.dataset.json.length); }) When I load the page, I see the full data json on screen while getting the following output in the console: {"key": string 7 -
The build_absolute_uri function always generates url with the http protocol
The build_absolute_uri function of the request object generates a url with the http protocol, although the url with the https protocol is obviously. Is it possible to somehow force the generation of a security protocol? -
Plugin caching_sha2_password could not be loaded: /mariadb19/plugin/caching_sha2_password.so: cannot open shared object file
I am trying to dockerise my Django app. docker-compose.yml version: "3.8" services: db: image: mysql:8 command: --default-authentication-plugin=mysql_native_password # this is not working restart: always environment: MYSQL_ROOT_PASSWORD: rootmypass ports: - '3306:3306' cache: image: redis environment: REDIS_HOST: localhost REDIS_PORT: 6379 ports: - '6379:6379' web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db - cache When I run docker-compose -up, I get the following error. django.db.utils.OperationalError: (1156, 'Plugin caching_sha2_password could not be loaded: /usr/lib/x86_64-linux-gnu/mariadb19/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory') Upon searching, I found the solution was to use command: --default-authentication-plugin=mysql_native_password or downgrade mysql. Tried the first command but it's not working. I don't want to downgrade as well. How do I get it to work? -
React-input-range dosen't displayed after build
I have seek bar component witch based on React-input-range <> <CurrentTimeWrapper> <CurrentTime/> </CurrentTimeWrapper> <SeekBarInput> <InputRange step={0.1} maxValue={duration} minValue={0} value={currentTime} onMouseDown={this._handleMouseDown} onMouseUp={this._handleMouseUp} onChange={this._handleChange} classNames={ DEFAULT_CLASS_NAMES } /> </SeekBarInput> </> After I build react app and add it in django code like: <script src="{% static "vsh25-biopro/static/js/2.ab2cb7d8.chunk.js" %}"></script> <script src="{% static "vsh25-biopro/static/js/main.27fe58ec.chunk.js" %}"></script> But when I check in Django, Seek bar dosen`t displayed. And I dosen't know any reason why it hapend. -
How to store and print array value from json object in postgresql?
Here i need to extract only skill and store in 'skill_s' variable for further processing. How can i achieve this? DO $do$ DECLARE skill_s Text[]; jsonObject json = // Json object '{ "Name": "bala Kala", "Education": "B.Tech", "Skills": ["enim", "aliquip", "qui"] }'; BEGIN SELECT jsonObject::TEXT[]->'Skills' into skill_s; raise info 'JSON value Name is %', skill_s; END $do$ I want to print the output enim, aliquip, qui -
Is there a way to have "parallel" for loop in Django template tags?
So I have two models : Question and Answer, like below: class Question(models.Model): number = models.IntegerField(primary_key=True) question = models.CharField(max_length = 100, blank=False, default="") class Answer(models.Model): authuser = models.ForeignKey(User, on_delete=models.CASCADE, null=True) number = models.ForeignKey(Question, on_delete=models.CASCADE, null=True) answer = models.CharField(max_length = 100, blank = False, default="") And what I want to do is display all questions and each corresponding answers. Like this: Q1. This is the first question A1. This is this user's first answer. Q2. This is the second question A2. This is this user's second answer. And so on.. So I have my view like this: def questionsAndAnswers(request): thisUser = User.objects.get(authuser_id=request.user.id) answers = Answer.objects.filter(authuser_id=request.user.id) questions = Question.objects.filter(authuser_id=request.user.id) context = { 'thisUser' : thisUser, 'answers': answers, 'questions' : questions, } return render(request, 'main.html', context) AND NOW I'M STUCK. Apparently, I cannot have two nested for loops, like below (simplifed): ... {% for q in questions %} {% for a in answers %} <div>Question : {{q.question}}</div> <div>Answer : {{a.answer}}</div> {% endfor %} {% endfor %} So I was wondering if there's a way to have "parallel" for loops in the template. How do I do this? I very much appreciate your help in advance. :) -
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 …