Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Filter count data
Does anybody know how can I use count based on selected value using django_filters Error 'UserFilter' object has no attribute 'count' My Reference link views.py def search(request): user_list = Person.objects.all() user_filter = UserFilter(request.GET, queryset=user_list) count = user_filter.count() #this will return an error print(count) return render(request, 'user_list.html', {'filter': user_filter}) filters.py from django.contrib.auth.models import User from .models import Person import django_filters class UserFilter(django_filters.FilterSet): class Meta: model = Person fields = ['category', 'firstname', 'lastname' ] user_list.html {% extends 'base.html' %} {% block content %} <form method="get"> {{filter.form.as_p}} <button type="submit" >Search</button> </form> <table class="table table-bordered"> <thead> <tr> <th>Firstname</th> <th> Lastname</th> <th>Caegory</th> </tr> </thead> <tbody> {% for user in filter.qs %} <tr> <td>{{ user.firstname }}</td> <td>{{ user.lastname }}</td> <td>{{ user.category }}</td> </tr> {% empty %} <tr> <td colspan="5">No data</td> </tr> {% endfor %} </tbody> </table> {% endblock %} I want to count all the list base from data I filtered -
Find django object by .id only (unknown Model)
I have two separate django (version >=2.2) apps: campus and equipment. campus Building Room equipment Camera Display Switcher Source etc. There's a lot of foreign key nesting going on, ex. source -> switcher -> room -> building, and all that works fine. I'm able to do things like source_list = Source.objects.filter(switcher__room_id=room_id) with no issues. I'm creating an API for equipment that will be using raw UDP strings, so I'm a little bit limited in how fancy it can be. My question is, can I somehow figure out what specific object is being referenced by the .id alone? I can narrow the query to the equipment app since I can figure out Building/Room based on the host IP address. In other words, my plan is to send a string from the external device with something like 1356|True|hdmi1|whatever|123|abc|stuff| with 1356 being the .id, and then in django efficiently figure out what equipment object 1356 is referring to. I'm good on the whole transport portion of getting the string into a django view, I just need to identify what 1356 is. Doing something (pseudo code) like this can't be the best way: try: Display.objects.get(id=1356) except: not a display... try: Switcher.objects.get(id=1356) except: not a … -
how to encrypt a file before uploading in django
Im building a project secure file sharing.which encrypts a file before uploading into local computer and decrypts while downloading if the user has the decryption key.I was stuck how to encrypt a file before uploading into my pc I'm following this approach which is mentioned below. https://ruddra.com/documentation-of-django-encrypt-file/#basic-usage but i dont't know how to link with my code. can anyone help me views.py def upload(request): context={} if request.method == 'POST': upload_file= request.FILES["document"] fs=FileSystemStorage() name=fs.save(upload_file.name, upload_file) context['url'] = fs.url(name) return render(request, 'accounts/upload.html',context) upload.html {% include 'accounts/main.html'%} <pre> Upload your files for sharing </pre> {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="document"> <button type="submit">Upload</button> </form> {% if url %} <p> Uploaded file:<a href="{{ url }}">{{ url }}</a></p> {% endif %} {% endblock %} settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL= '/media/' -
Django django.urls.exceptions.NoReverseMatch: Reverse for ' new_topic' not found. ' new_topic' is not a valid view function or pattern name
I'm trying to build a topics section, in where you can create a new topic. This exercise is from the python crash course book. The error I see is the next one: django.urls.exceptions.NoReverseMatch: Reverse for ' new_topic' not found. ' new_topic' is not a valid view function or pattern name. views.py from django.shortcuts import render from .models import Topic, Entry from .forms import TopicForm, EntryForm from django.http import HttpResponseRedirect from django.urls import reverse # Create your views here. def index(request): return render(request, 'learning_logs/index.html') def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render (request, 'learning_logs/topics.html', context) def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) topics = Topic.objects.order_by('date_added') entries = topic.entry_set.order_by('date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topics.html', context) def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} return render(request, 'learning_logs/new_topic.html', context) def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) proj/urls.py from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [path('', views.index, … -
How to call method from tasks.py in Django?
In my cars/models.py I have the following code: from django.contrib.auth import get_user_model from django.utils.timezone import now from django.db import models class Car(models.Model): # Fields # methods In my cars/signals.py I have the following code: from django.dispatch import receiver from django.db.models.signals import post_save from .models import Car from tasks import create_car @receiver(post_save, sender=Car, dispatch_uid="queue_car_create_job") def queue_car_request(sender, instance, created, **kwargs): if not created: return status = create_car.delay(instance.pk) In my cars/apps.py file I have: from django.apps import AppConfig class CarConfig(AppConfig): name = 'provisioners' def ready(self): print("at ready") import cars.signals In my tasks.py I have: from celery import Celery import subprocess import django django.setup() from django.conf import settings from cars.models import Car app = Celery('management', broker=settings.CELERY_BROKER) @app.task(bind=True) def create_car(self, car_pk): if car_pk is None or not isinstance(car_pk,int): return False car_obj = Car.objects.get(pk=car_pk) return True When running Django (without Celery), I get the following error: RuntimeError: populate() isn't reentrant All I want to do is as following: Signal for creating a car. Celery runs an async job to create a car. Previously I had queue_car_request in cars/models.py but I need to import cars/models.py in tasks.py and import tasks.py in cars/models.py which makes a circle (and python does not like it). So I moved it to … -
Django - How can I edit an existing note? (Views)
I'm working on an application which allows users to create, edit, and delete notes for artists and their shows at venues. Currently I have a method for creating new notes and deleting as example, how could I create a method of allowing the user to edit an existing note? Here is what I currently have, I also thrown in repository links as reference to help explain how my application works. Any idea how I can do this? https://github.com/claraj/lmn/blob/master/lmn/urls.py #Note related path('notes/latest/', views_notes.latest_notes, name='latest_notes'), path('notes/detail/<int:note_pk>/', views_notes.note_detail, name='note_detail'), path('notes/for_show/<int:show_pk>/', views_notes.notes_for_show, name='notes_for_show'), path('notes/add/<int:show_pk>/', views_notes.new_note, name='new_note'), path('notes/detail/<int:note_pk>/delete', views_notes.delete_note, name='delete_note'), https://github.com/claraj/lmn/blob/master/lmn/views/views_notes.py @login_required def new_note(request, show_pk): show = get_object_or_404(Show, pk=show_pk) if request.method == 'POST' : form = NewNoteForm(request.POST) if form.is_valid(): note = form.save(commit=False) note.user = request.user note.show = show note.save() return redirect('note_detail', note_pk=note.pk) else : form = NewNoteForm() return render(request, 'lmn/notes/new_note.html' , { 'form': form , 'show': show }) @login_required def delete_note(request, note_pk): # Notes for show note = get_object_or_404(Note, pk=note_pk) if note.user == request.user: note.delete() return redirect('latest_notes') else: return HttpResponseForbidden https://github.com/claraj/lmn/blob/master/lmn/templates/lmn/notes/note_list.html <form action="{% url 'delete_note' note.pk %}" method="POST"> {% csrf_token %} <button type="submit" class="delete">Delete</button> </form> -
Celery or Schedule for django?
So I am working on a project. And it has a small module where when the user is not authenticated he can try to reset the password and I am implementing an OTP based verification for this, where the key for the otp will be stored in the database and when the user tries to reset the password a random number will be created which will be sent to the user through a email and the user can change the password. Now the problem is that I need the random number stored in the database will be changed to null after 10 min of its creation so now do I use the schedule or do use Celery for this project. -
Unable to login because Django saving passwords in plain text but
class UserManager(BaseUserManager): def create_user(self, username, email, password=None): if username is None: raise TypeError('User should have a username') if email is None: raise TypeError('User should have an email') user = self.model( username=username, email=self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None): if password is None: raise TypeError('Password should not be none') user = self.create_user(username, email, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField( max_length = 255, unique = True, db_index = True ) email = models.EmailField( max_length = 255, unique = True, db_index = True ) is_verified = models.BooleanField(default = False) is_staff = models.BooleanField(default = True) is_active = models.BooleanField(default = True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def tokens(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length = 255, min_length = 6, write_only = True ) class Meta: model = User fields = ['email', 'username', 'password'] extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} def validate(self, attrs): email = attrs.get('email', '') username = attrs.get('username', '') if not username.isalnum(): raise serializers.ValidationError( "Username should contain only alphanumeric characters" ) return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) class RegisterView(generics.GenericAPIView): permission_classes … -
Is update_or_create safe within atomic transaction?
The title is pretty explicit : can you use an update_or_create command inside an atomic transaction in django ? I don't find the answer in the doc. There is something about race condition, but atomic transaction is about rollback more than race ? -
How to create editable password policy using Flask?
I want to create a Editable password policy using Flask. Admin can tick the any password policy in the menu (Please see admin menu page image). admin menu page Based on the selection password policy need to be updated. How can I Implement it?? -
django one request.is_ajax() check and multiple forms
so i have this code that checks if there is an ajax request and then handle the form stuff if there is, but my problem is it's kind of repetitive to check each time like you will see in the code that i will add, what i want is to check only once and then say if form_1 do some stuff, if form_2 do some stuff here is the code: if request.is_ajax(): Form1 = form_1(request.POST) if form_1.is_valid(): # do some stuff else: # do some stuff) if request.is_ajax(): Form2 = form_2(request.POST) if form_2.is_valid(): # do some stuff else: # do some stuff what i want to do is something like this or an alternative to the following: if request.is_ajax(): if it's form1: # do form1 stuff elif it's form2: # do form2 stuff -
How to add item in django relation table created with manyToMany relation
Is possible to interact with a table created automatically by Django using manyToMany relation? I have a table that contains an user_id and an article_id, and i want to add a new article using a web form. This table has been created without using a User model (i used the ones provided by Django, so i've not created a new ones). The problem is that i don't want to create a new table for User nor for the relation. Is it possible? -
I'm not being able to access app front-end/login page
I'm a student learning Web app development. I have designed an app using Python-Django framework. Very simple, it is supposed to be a bookings/event management platform for a university, and staff and student should be able to login to their accounts and have specific permissions. Everything is OK, except I can access the admin page and login as staff, but I am unable to find the login page for a student. As in, the only page I am being able to access when I runserver, is Django Administration. I guess I need to add views/url but im not being able to figure out where/what to add. Sounds pretty simple for you pros out here. Here's what my directory looks like - [1]: [https://i.stack.imgur.com/E6hGZ.jpg][1] Here's the urls.py code - from django.contrib import admin from django.conf.urls import include, url __author__ = 'rs' urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('NDEvents_api.urls', namespace='api')) ] -
How to Modify user input using Class Based Views in Django
I'm currently using generic class based views. Basically, I am trying to learn how to modify the user input, for instance make the user's input a negative number so I would think something like, fields = ['tname', 'recipient', 'amount'*(-1), 'date'] to modify the amount, or in the future I would like to be able to do amount*2.735 That doesn't work but regardless I'm not sure exactly which type of feature to utilize in Django or the best way to go about this. Here is my current class based view class TranCreateView(LoginRequiredMixin, CreateView): model = transactions success_url = '/users/tactionslist' fields = ['tname', 'recipient', 'amount', 'date'] def form_valid(self, form): form.instance.user_id = self.request.user return super().form_valid(form) The 'amount' is a DecimalField in the models. -
How to access a logged in user from a class based view?
How do I access a current logged in user from a class based view?. In a function view we can pass a request parameter but I can't pass a request parameter from a class view. I have seen ways to do it in the internet but I can't understand it. my models.py file class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return (self.name) def get_absolute_url(self): return reverse("home") class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(max_length=3500) category = models.CharField(max_length=255, default="uncategorized") views.py class HomeView(ListView, LoginRequiredMixin): model = Post template_name = "home.html" Thank you. -
trying to import a module in pycharm wouldnt work
from django.contrib import admin from generator import views when i import it gives me a Module not found error but the module file is in the same file. enter image description here -
Remove a part of string by Regex
I wanna Remove 'amp;' by Regex from this url https://pps.whatsapp.net/v/t61.24694-24/85536857_551478115508757_7310509839538811257_n.jpg?oh=e4b2c87c9691a84ee08e39dc674ea0c4&**amp;**oe=5FBBA259 Can You help me? -
Email body is showing html code in place of template in django
I am sending email using smtp in django but its showing its HTML code. Here is my django view and template view.py current_site = get_current_site(request) mail_subject = 'Activate Your Account' mail_message = render_to_string('mail_body.html', { 'user' : user, 'domain' : current_site.domain, 'uid' : urlsafe_base64_encode(force_bytes(user.pk)), 'token' : default_token_generator.make_token(user) }) mail_to = email, email = EmailMessage( mail_subject, mail_message, to = mail_to ) email.send() mail_body.html <div> {% autoescape off %} <b class="text-center">Hello {{ user.username }}</b><br> Please click on the link below to verify your email address and complete your registration. <a class="btn btn-primary btn-block" href="http://{{ domain }}{% url 'auth' uidb64=uid token=token %}" role="button" target="_blank">Verify</a> <hr /> <br /> If you think, it's not you, then just ignore this email. {% endautoescape %} </div> -
Django how to automatically generate username when registering user via email?
Currently in my Django application users register and login with their email. When a user registers, they don't specify a username in addition to registering their email. Since I want to make profile pages, I figured the best way to do this was to automatically generate a string of numbers to represent a "username" that would link to the individual's profile page during the create_user() method. Here is my models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager import random class AccountManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email address") user = self.model( email=self.normalize_email(email), username=str(random.randint(1,9999)) + str(random.randint(1,9999))) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, ) 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=63, unique=True) username = models.CharField(verbose_name="username", max_length=15, unique=True, blank=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(verbose_name="first name", max_length=31, blank=True) last_name = models.CharField(verbose_name="last name", max_length=31, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username',] objects = AccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): … -
Django issue playing audio files
I am using Javascript in a Django project to make an audio player/visualiser but I am having the problem that when the link is clicked it is showing a 404 error, and that the current path is not in the project .urls. I have tried to add a path but not been able to get it to work, and below is the JS I have used to create the audio player. I am new to Django so any help would be brilliant, thanks. export default class AudioPlayer { constructor(selector = '.audioPlayer', audio = []) { this.playerElement = document.querySelector(selector); this.audio = audio; this.currentAudio = null; this.createPlayerElements(); this.audioContext = null; } createVisualiser() { this.audioContext = new AudioContext(); const src = this.audioContext.createMediaElementSource(this.audioElement); const analyser = this.audioContext.createAnalyser(); const canvas = this.visualiserElement; const ctx = canvas.getContext('2d'); src.connect(analyser); analyser.connect(this.audioContext.destination); analyser.fftSize = 128; const bufferLength = analyser.frequencyBinCount; const dataArray = new Uint8Array(bufferLength); const barWidth = (canvas.width / bufferLength) * 2.5; let barHeight; let bar; function renderFrame() { requestAnimationFrame(renderFrame); bar = 0; analyser.getByteFrequencyData(dataArray); ctx.fillStyle = '#000'; ctx.fillRect(0, 0, canvas.width, canvas.height); for (let i = 0; i < bufferLength; i++) { barHeight = dataArray[i] - 100; const r = barHeight + (50 * (i / bufferLength)); ctx.fillStyle = `rgb(${r}, … -
create a list of nested dictionnaries in python
I want to create a list of parent, children object. My object is like that in my model: class Group(models.Model): group_id = models.AutoField(primary_key=True) groupParent_id = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) group_name = models.CharField(max_length=100, null=False, blank=False, unique=True) My code is : # Logic for tree view with child and grandchild treeList = [] groups = Group.objects.order_by('groupParent_id') print (groups.query) for item in groups: # there is no parent. item is on 1st level of tree e = dict() e['key']=item.pk e['value']=item.group_name if item.groupParent_id is None: treeList.append(e) else: parent = item.groupParent_id.pk testParent = find_in_list_of_list(treeList,parent) treeList[testParent].append(e) I've a function but not sure it will works well when I will have to digg in more than one level of parent... def find_in_list_of_list(mylist, char): return next((i for i, item in enumerate(mylist) if item["key"] == char), None) at the end I would like a list like that: treeList = [ {'key':1,'value':rdtd}, [ {'key':32,'value':sdr}, [{'key':34,'value':fds}, {'key':45,'value':gtq}, {'key':4,'value':non}], {'key':12,'value':fgr}, [{'key':3,'value':dfr}, {'key':52,'value':ghvc}], {'key':100,'value':vte}, [{'key':46,'value':err}, {'key':76,'value':test}, {'key':200,'value':non}] ], {'key':265,'value':patate}, [{'key':456,'value':choux}, {'key':67,'value':bluet}, '{'key':9,'value':non23}] ] There is a undefined level of nested dict. At the end i will a tree view of multi level. thanks -
Is this good practice to save children object in "save" method of parent object?
If have two models called Company and Implantation. Obviously, a company can have multiple implantations , hence a ForeignKey field in Implantation class. There is a french API which will help gathering fields for companies. So I define a clean method for Company which is querying the API. This same call will also return information about the company's implantations. I'm thinking "why not create (and save) implantation's while saving the company ?". I may be able to achieve this using an atomic transaction within the save method of Company. So far, I've managed something like this (not entirely tested though...) : from django.db import models, transaction import requests class Company(models.Model): #this is the french "official" key of any company : siren = models.CharField("Numéro SIREN", max_length=9, blank=True, unique=True) #this is a field which can be found on the french API denomination = models.CharField("Dénomination", max_length=150, blank=True) def clean(self): if self.siren: #call to the french API s = requests.Session() r = s.get("https://entreprise.data.gouv.fr/api/sirene/v3/unites_legales/"+self.siren) if r.status_code: #'unite_legale' translates (here) to 'company' self.denomination = r.json()['unite_legale']['denomination'] #'unite_legale' translates (here) to 'implantation' self.implantations = r.json()['unite_legale']['etablissements'] def save(self, *args, **kwargs): self.clean() with transaction.atomic(): super().save(*args, **kwargs) for implantation in self.implantations: implantation = Implantation(etab['siret']) implantation.save() class Implantation(models.Model): #this is the french … -
why this is showing undefined variable request
from django.shortcuts import render,redirect from F_UI import models def blocks(): if request.method=="GET": return render(request,"blocks.html") -
How do I use a django url inside of an option tag in a dropdown menu?
I have a select tag with two options. I want the url to change based on the option selected. I want the url defined in URLPATTERNS in django to be linked to these options. My html: <select name="rec-type" id="rec-type"> <!-- <a href="{% url 'transactions' rec_type='expense' %}"> --> <option value="expense">Expense</option> <!-- </a> --> <!-- <a href="{% url 'transactions' rec_type='expense' %}"> --> <option value="income">Income</option> <!-- </a> --> </select> My url for transactions is : path('transactions/<str:rec_type>', views.transactions, name='transactions'), -
Perform database query in Django channels
I'm trying to create a very simple system where an user, in order to use a consumer, needs to input a key in the WS url, like : ws://127.0.0.1:8000/main?key=KEY. Once the consumer is called, Django Channels needs to perform a very simple DB query to check if the key exists: class TestConsumer(AsyncJsonWebsocketConsumer): async def websocket_connect(self, event): ... key_query = await database_sync_to_async(keys.objects.get(key=key)) ... But the problem with this code is that it will give the following error: You cannot call this from an async context - use a thread or sync_to_async. Is there any way to accomplish this? Any advice is appreciated!