Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a share button in Django to share a post
I am relatively new to Django, I have a blog that I have been working on. However, I am having problem implementing a sharing button to share my posts on social media, with the title and thumbnail,specifically Facebook and WhatsApp.I have researched and googled all the possible solutions, but neither of them tends to solve my problem. Not many tutorials out here have covered this issue. I have used the social_share,django_addthis, and social_share_widgets but none of them seem to help. Here are my models and templates {% extends 'base.html' %} {% load static %} {% load social_share %} {% load blog_tags %} {% block content %} <p>{{post.content| safe}}</p> <div class="social-contact"> <a href="#" id="shown" style="background-color: red;"><i class="fa fa-share"></i> Share</a> <a id="hidden" href="https://facebook.com/share?url=http://devbrian.com{{ request.get_full_path|urlencode }}" class="facebook-link"><i class="fa fa-facebook"></i> Facebook</a> <a id="hidden" href="https://www.twitter.com/share?url=http://devbrian.com{{ request.get_full_path|urlencode }}" class="twitter-link"><i class="fa fa-twitter"></i> Twitter</a> <a id="hidden" href="https://www.instagram.com/share?url=http://devbrian.com{{ request.get_full_path|urlencode }}" class="instagram-link"><i class="fa fa-instagram"></i> Instagram</a> <a style="background-color: green;" href="https://api.whatsapp.com/send?+254799043853=+*YOURNUMBER*&text=%20*{{ request.get_full_path|urlencode }}&title=<your title>&summary=<your desc>&source=http://devbrian.com*" class="youtube-link"><i class="fa fa-whatsapp"></i> Whatsapp</a> </div> {% endblock content %} class Post(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200,blank=True,unique=True) thumbnail = models.ImageField() def get_absolute_url(self): return reverse('details', kwargs={'slug': self.slug}) I will appreciate your help -
Django-differnt models for specific group model choices Django
Could someone help me how to solve my question, What is an efficient and good way to write group model choices, I want multiple Django model values depends on choice field values! (Django rest framework)enter image description here For jobs it's giving different field and if you choose another option it displaying other options like below picture This is for cars..I would like to write code for this similar one -
HOW TO EDIT A RECORD BY USE DJANGO FORM INTO A TEMPLATE
I have two models that have relationship to each other which are a child and academy model which means that a child can have academic details,and then i pass a child ID into the template to edit academic details of child here is academy model #ACADEMY MODEL from child.models import Child_detail class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Average_grade = models.CharField(max_length = 10) Overall_position = models.IntegerField() Total_number_in_class = models.IntegerField() def __str__(self): return str(self.Student_name) here is child model #CHILD MODEL from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) Tribe = models.CharField(max_length = 50) Current_Address = models.CharField(max_length = 50) def __str__(self): return self.Firstname I come to the scenario that i want to edit academic details of a child by use django form to the template that i pass child ID def edit(request,pk): child=get_object_or_404(Child_detail,pk=pk) form=AcademicForm(request.POST or None,instance=child) if form.is_valid(): form.instance.Student_name=child form.save() return redirect('more',pk=pk) context={ 'form':form } return render(request,'functionality/more/academy/edit.html',context) And here is my form.py file class AcademicForm(forms.ModelForm): class Meta: model=Academic fields='Class','Date','Average_grade','Overall_position','Total_number_in_class' labels={ 'Average_grade':'Average Grade', 'Overall_position':'Overall Position', 'Total_number_in_class':'Total Number In Class' } Date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) And also this is my template that pass child id <form action="" method="post" autocomplete="on"> {% csrf_token %} … -
meke tests with django inside innerHTML method
I am new in django and I faced a problem in my project.The problem is I want to put some tests inside innerHTML method like this: var level = document.getElementById('level'); selectElementM.innerHTML = ` <option value="">--select--</option> {% for module in modules %} {% ifequal module.level|lower ${level} %} <option value="{{ module.name}}">{{ module.name}}</option> {% endifequal %} {% endfor %} // here are other tests... `; I know it's not possible for doing it like this so I need another proper way -
Django username is empty in a GET request
In my views.py, I have a function which uses GET method as shown below. def status_codes(request): try: url = request.GET.get('url') urls = linksextraction(url) url_codes.objects.filter().delete() print(request.user.username) # prints empty string # do something return JsonResponse(url_final_data) except Exception: return JsonResponse({"message": "Invalid url"}) When i try to print the current logged in user, it prints an empty string. I have used the same in other functions which uses POST and it works fine there. Can someone please help me getting the username in such scenarios where it involves GET method? -
Django self referance filter for version
I have created different version of Template model using self reference field with one parent Template when user update any template i will create new version of previous template. Model class AppTemplate(models.Model): app = models.ForeignKey( Application, on_delete=models.CASCADE, related_name="apps" ) name = models.CharField(max_length=100, null=False) description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) version_ref = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL) version = models.FloatField(default=1.0) Now i want to filter template for specific app if one template have multiple version display only latest template. I have done this using looping. templates = AppTemplate.objects.filter(app=app_id, version_ref__isnull=True) queryset = [] for template in templates: child_template = AppTemplate.objects.filter(version_ref=template).order_by('-created_at') if len(child_template) > 0: queryset.append(child_template.first()) else: queryset.append(template) How can i improve my queryset Filter ? -
is there any way to request for client zone base data retrieval from angular app to django?
while interacting from angular 8 app to django back end i want to retrieve data based on user timezone without doing any manual conversion between the timezone . Date being saved is in UTC format on backend. in which format date should be sent so that it automatically retrieve correct data for that zone. -
Convert postgres raw query to Django ORM query and group by
I have a raw Postgresql query which needs to be converted to Django ORM query. I was able to execute the query in Postgres and see the expected result. I'm getting 5 records for the raw query on postgres DB. But when I execute the Django ORM query, it's not giving the expected output. I'm getting 78 results for the ORM query in postgres. Please let me know where am I making mistake in Django ORM query. Raw postgres query: select customer_id, program_id, project_id, store_id, count(store_id) from public.alerts_alert where (customer_id=2 and program_id=134 and project_id=1364) group by customer_id, program_id, project_id, store_id Django ORM query: queryset = Alert.objects.filter(**filter_params).defer( 'unregistered_timestamp' ).annotate( customer_name=F('customer__name'), program_name=F('program__name'), project_name=F('project__name'), store_count=Count('store') ) **filter_params is where I'll be providing actual values as mentioned in raw queryset. -
Cannot get cookie value
I have a script that calls a prompt when I push a button and gets a number from the user. The number is stored in a cookie. Then that script loads a view that gets the number from the cookie and passes it to a form. Currently I have the cookie being saved; I can see it in the browser debugger. But when I try to get the cookie in my view it always returns null. Please I need help figuring out what the problem is. JavaScript $(document).ready(function() { $(document).off('click', '.order_button').on('click', '.order_button', function() { // $(".on_button").click(function() { var amount = prompt("Please enter amount of orders" ,"0") if (parseInt(amount) <= 0 /* || amount === null */) { alert("Please enter integer greater than 0") } else if (parseInt(amount) > 0) { document.cookie = "amount=" + amount; //+ ";max-age=60"; console.log(document.cookie) var link = $(this).find('a'); console.log(link.attr('href')); window.location.href=link.attr('href'); console.log("OK"); } return false; }); }); View def add_order(request, meal_slug, meal_restaurant): print("OK") amount = get_server_side_cookie(request, 'amount', '1') print(amount) # clear_amount_cookie(request) if amount is not None: meal = Meal.objects.get( slug=meal_slug, restaurant_slug=meal_restaurant) user = UserProfile.objects.get(user=request.user) order = Order.objects.create( meal=meal, customer=user, amount=amount, date=datetime.now()) order.save() # clear_amount_cookie(request) return redirect('food_cloud:index') Get cookie function def get_server_side_cookie(request, cookie, default_val=None): val = request.COOKIES.get(cookie) print(val) … -
How to create booking/reservation in Django
I created this Library website in Django, where I created 2 groups - Librarians and Library Members. Librarians are able to play with books and catalogs in library and it all works perfect, but I dont know how to make Library Members being able to book a book or catalog. Please any example of solution ? I am despred to figure out. Thanks. -
it is correct to use csrf token to protect django rest framework API? - I need protect to API (without user account authentication) from spammers
I know that django rest framework has an authentication system based in SessionAuthentication, TokenAuthentication, BasicAuthentication and others, and Third party packages: JSON Web Token Authentication, etc. But all are based in user account authentication and I need use my API with ajax from django template and only want that my application use the API without expose to spammers. That's what I've done: 1 - Custom authentication based to csrf token permission.py from django.middleware.csrf import get_token, _unsalt_cipher_token, _compare_salted_tokens from rest_framework.permissions import BasePermission class HasCsrfTokenValid(BasePermission): def has_permission(self, request, view): try: csrf_token = request.headers.get("api-csrftoken") # get token from ajax request csrf_cookie = request.META.get("CSRF_COOKIE")# get token from cookie token_valid = _compare_salted_tokens(csrf_token, csrf_cookie) # compare if is valid token except TypeError: token_valid = False return token_valid or bool(request.user and request.user.is_staff)#return True or False``` 2- protect view view.py from . permissions import HasCsrfTokenValid class SomeAPI(generics.RetrieveAPIView): queryset = Model.objects.all() serializer_class = SomeSerializer permission_classes = [HasCsrfTokenValid] authentication_classes = [SessionAuthentication, ] 3- Ajax Request index.html <script> $.ajax({ url:'http://localhost:8000/api', headers:{'api-csrftoken':'{{csrf_token}}'}, success:function(data){ console.log(data) }, error:function(error){ console.log(error) } }); </script> Note: Django REST Framework API Key is a powerful library to use authentication without user account but this key it would be expose in ajax request in frontend. Is it ok what … -
How to solve No Reverse Match error in django
I am getting this error and I could not solve it, "Reverse for 'post_task' with arguments '('',)' not found. 1 pattern(s) tried: ['post/ajax/task/(?P[0-9]+)$'] " I have a script on my main page, and when I am on the template page everything is ok. but when I go to any other page including the main page, I get this error. can you assist me? main.html <script> if ($('#task-form').length > 0) { // Exists. $("#task-form").submit(function (e) { // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the form data. var serializedData = $(this).serialize(); // make POST ajax call $.ajax({ type: 'POST', url: "{% url 'post_task' order.id %}", data: serializedData, success: function (response) { // on successfull creating object // 1. clear the form. $("#task-form").trigger('reset'); // 2. focus to nickname input $("#task").focus(); // display the newly friend to table. var instance = JSON.parse(response["instance"]); var fields = instance[0]["fields"]; $("#my_tasks tbody").prepend( `<tr> <td >${fields["task"] || ""}</td> </tr>` ) }, error: function (response) { // alert the error if any error occured alert(response["responseJSON"]["error"]); } }) }) } $("#service-form").submit(function (e) { // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the form data. var serializedData … -
How to add suggested post
how do I add a Suggested post after my first two post. For example, Post Post... Suggested post... Post Post. def home(request): all_images = Image objects.filter(imageuploader_profile=request.user, active=True) context={'all_images':all_images} #my post here {% for post in all_images %} {{ post.username }} {% if post.profile_pic %} <img src = "{{....}}"> {% endif %} {% endfor %} -
Add user to a group at signup in Django
New to Django here. There are three types of users: Bronze, Silver and Gold with different permissions. All users start out as Bronze when they sign up and then move upwards when they fulfill certain conditions. Therefore I tried to customize the User model using Django's tutorial. So far I have been able to create the users correctly. However, I want to now add these users to the Bronze group as soon as they sign up and am not sure where do I put that code. Here is my code. Its fairly straightforward. models.py # models.py from django.contrib.auth.models import AbstractUser, Group from django.db import models class CustomUser(AbstractUser): pass # add additional fields in here def __str__(self): return self.username forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email') views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic.edit import CreateView from .forms import CustomUserCreationForm # Create your views here. class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' admin.py from django.contrib import admin # Register your models here. from django.contrib.auth import … -
Using Google Firestore with Django
Hi so i was wondering if its possible to use Google Firestore with Django. I don see why i couldn't but i cant find anywhere explain how to integrate it. I know in the Django Settings it gives a database option and it starts out using SQLite3. Is this where i change it or do i write specific code where i have to add every entry manually like i saw in one video. If anyone has any sample videos that wold be greatly appericated. Im reading the google firestore Doc and its just showing me how to manually enter the data. -
How can i get the pk from a cloned model instance i in form_valid to use in get_success_url in an UpdateView? https://bpaste.net/F76Q
class DomainRegistrationItemUpdateView(UpdateView): model = DomainRegistrationItem form_class = DomainAddYearsForm template_name = "add_years.html" def get_context_data(self, *args, **kwargs): context = super(DomainRegistrationItemUpdateView, self).get_context_data(**kwargs) # tld_ppy Top Level Domain Price Per Year context['tld_ppy'] = TLD.objects.get( name='.%s' % (self.kwargs['domain_name'].split('.')[1])).yearly_price return context def get_object(self, queryset=None): return DomainRegistrationItem.objects.get(domain=self.kwargs['domain_name'], purchased=True) def get_success_url(self): split_dn = self.kwargs['domain_name'].split('.') namespace = split_dn[0] sld = split_dn[1] return reverse("domain_registraiton_item_detail", kwargs={ "pk": self.kwargs['pk'], 'namespace': namespace, 'second_level_domain': sld}) def form_valid(self, form): f = form.save(commit=False) working_dri = DomainRegistrationItem.objects.get(domain=self.kwargs['domain_name']) working_dri.pk = None working_dri.save() working_dri.purchased = False working_dri.years = f.years f.save() return super(DomainRegistrationItemCreateView, self).form_valid(form) The working_dri code is code that clones a DomainRegistrationItem under consideration by the view. I want to get the pk from working_dri to usee in get_success_url. How can I do this? Thanks in advance for any and all help. -
I have a Django-MySQL back end, which web-server provider can handle this?
The day has finally come where I have finished the front end of my mobile app. I completed the back end, a Django-API connected to MySQL, prior to beginning the front end. Now I need to push my backend onto a server so that I can publish my app. Which server provider can handle MySQL/Django? Thank you. -
Maintain AJAX received data in the browser's back
How do I maintain the ajax received data when the user navigates back/forward in the browser? I have Python, Django app, Jquery for ajax. When I receive data from ajax I populate that in a div. When I move to another page and return 'back' on chrome browser the data is lost and I have to make the ajax call again. -
Django: How to use custom url name instead of 'password_reset_done' for password reset route in urls.py?
I am creating my first Django project and implementing password-reset functionality. So I know that I have to configure the URLs with the following name and use inbuilt views. password_reset password_reset_done password_reset_confirm password_reset_complete But I have created a seaparate application accounts to handle the authentication part and I am following a convention of prepending application name for naming application-specific URLs. So all the URLs in the accounts app have accounts- prepended to them. path('signup/', views.signup, name='accounts-signup'), path('logout/', auth_views.LogoutView.as_view(), name='accounts-logout'), PROBLEM: But while creating password reset URLs, I have to use predefined names as mentioned above. Is there a way to use a custom name in place of these predefined names, or any way to override these in settings.py I checked docs for settings.py but could not find anything. EXPECTATION: I want to be able to assign custom names like accounts-password_reset and accounts-password_reset_done. The app works fine with predefined names, but what If I want to create another app in the same project with a separate authentication system and separate routes. Wouldn't the same name for reset password route can cause namespace collisions in other apps? -
Can I add a Color Picker to Django Forms
I tried using the django-colorfield module which works great for the admin page but I cannot get it to render the widget in the actual forms. Below is what I have tried so far and all I get on the form is a CharField with the default value as text. I am open to every and any suggestions but I do not want to use the RGB color picker that html5 has if possible. This is in my forms.py from django import forms from .models import Automation from colorfield.fields import ColorWidget def get_automation_form(content, data=None, files=None): songs = content[2].split(', ') music_choices = [] for song in songs: song = song.replace(' ', '-') song_filename = f'Music/{song}.wav' music_choices.append((song_filename, song)) class AutomationForm(forms.ModelForm): music_selection = forms.CharField(widget=forms.Select(choices=music_choices)) class Meta: model = Automation fields = content[0] labels = content[1] widgets = { 'color1': forms.CharField(widget=ColorWidget()), 'color2': forms.CharField(widget=ColorWidget()), 'color3': forms.CharField(widget=ColorWidget()), 'color4': forms.CharField(widget=ColorWidget()), 'color5': forms.CharField(widget=ColorWidget()), } def __init__(self, *args, **kwargs): super(AutomationForm, self).__init__(data=data, files=files,*args, **kwargs) return AutomationForm() This is in my models.py from django.db import models from django.contrib.auth.models import User from colorfield.fields import ColorField class Automation(models.Model): timestamp = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default="", blank=True) text_field01 = models.CharField(max_length=50, default="") text_field02 = models.CharField(max_length=50, default="") text_field03 = models.CharField(max_length=50, default="") text_field04 = models.CharField(max_length=50, default="") … -
Using a Wagtail "ChoiceBlock" with dynamic choices rather than a hardcoded list
We have a setup with a Blog model that has a manytomany relation for BlogPageCategory, and we have a "recent blog posts" streamfield block that lets you specify whether to show cards for X latest blog posts, or X latest blog posts from a specific category. As such, we started with the following code: from wagtail.core import blocks class RecentBlogEntries(blocks.StructBlock): title = blocks.CharBlock( required=True, ) category_filter = blocks.ChoiceBlock( label='Filter by Category', required=False, choices=[ ('all', 'All'), ('First Category', 'First Category'), ('...',. '...'), ], ) ... But hardcoding the categories is kind of silly, and being able to pick them from "what the list is, right now, based on the CMS data for BlogPageCategory" would be far more convenient. However, the following code (of course) turns into an equally hardcoded migration: from wagtail.core import blocks from ... import BlogPageCategory class RecentBlogEntries(blocks.StructBlock): title = blocks.CharBlock( required=True, ) choices = [ (cat.name, cat.name) for cat in BlogPageCategory.objects.all()] choices.sort() choices.insert(0, ('all', 'All')) category_filter = blocks.ChoiceBlock( label='Filter by Category', required=False, choices=choices, ) ... Is there any way to make this a dynamic value instead of a list that is fixed by makemigrations? -
How to use post_save signal with custom user model extended with AbstractBaseUser
There are two apps in my ecommerce website and i have been following a particular tutorial on youtube. In the course, the guy used django-allauth package for login purposes. I followed the course along but I created custom user model exending AbstracBaseUser class in account app. I created another app called product where I handled all the ecommerce logics. Here's the code: models.py (account) class MyAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, gstin_no, phone_no, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have a username") if not first_name: raise ValueError("Users must have First Name") if not last_name: raise ValueError("Users must have Last Name") if not gstin_no: raise ValueError("Users must have a valid GSTIN Number") if not phone_no: raise ValueError("Users must have a valid Phone Number") user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, gstin_no=gstin_no, phone_no=phone_no, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, gstin_no, phone_no, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, first_name=first_name, last_name=last_name, gstin_no=gstin_no, phone_no=phone_no, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', … -
Template tags not rendering in HTML
I am building a skeleton django website, but can't manage to get the template tags to render for what I thought would be a simple test. Currently, the template tags just appear as text (i.e. it just says '{{ test }} and end' when I look at the website. I am sure the problem is obvious, but I am not very experienced with django. I am not running into any errors though, so if there is any debugging advice that would be helpful. Please let me know if I have missed any key information. views.py from django.shortcuts import render from .models import Forms def home(request): return render(request, 'kb/home.html', {'test': 'begining'}) home.html <html> <head> <title>Kinbank</title> </head> <body> <p>Hi there!</p> <p>{{ test }} and end </p> </body> </html> urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.home, name='home'), ] -
Python django.How can I enter the text selected by the user with a drop-down element in the name_znat field
There is an html form with dropdown elements: <form method = "POST" action = "{% url 'create_group_handler'%}"> <select name = "select"> <! - Add an identifier here instead of using 'name' -> <option value = "value1"> Value 1 </ option> <option value = "value2" selected> Value 2 </ option> <option value = "value3"> Value 3 </ option> </ select> </ form> And there is a Python django model: Znat Class (models.Model): name_znat = models.CharField ('Name znat', max_length = 200) Suppose that the user selects a drop-down element with the text "Value 2". How can I enter the text selected by the user with a drop-down element in the name_znat field -
Django channels freezes
I'm trying to create a Django Channels consumer which receives some data in real time from a RabbitMQ queue and then sends this data to a frontend, in order to let users have real-time data. Here is my basic consumer: class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='Test') def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume( queue='Test', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') await self.send({ "type": "websocket.accept" }) await channel.start_consuming() async def websocket_receive(self, event): print("received", event) # Echo the same received payload async def websocket_disconnect(self, event): print("disconnected", event) And here is my Javascript code: <script> // websocket scripts var loc = window.location var wsStart = 'ws://' + window.location.host + window.location.pathname var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) if (loc.protocol == 'https:'){ wsStart = 'wss://' } socket.onmessage = function(e){ console.log("message", e) } socket.onopen = function(e){ console.log("message", e) } socket.onerror = function(e){ console.log("message", e) } socket.onclose = function(e){ console.log("message", e) } </script> The problem with this code is that, altough in my console i will see the queue waiting for data, on my HTML page i won't see any …