Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multiple boolean fields on ForeignKey model in form as checkboxes
I have a Django app that has the following models: class ProductNotification(models.Model): question_asked = models.BooleanField(default=False, help_text='Receive messages when a question is added') question_delete = models.BooleanField(default=False, help_text='Receive messages when question is deleted') # There are more boolean fields in here class Product(models.Model): name = models.CharField(max_length=255, unique=True) #... product_notification = models.ForeignKey(ProductNotification, on_delete=models.CASCADE, default=True) Each Product should have its own notification setting. My forms: class ProductNotificationForm(forms.ModelForm): question_added = forms.BooleanField(help_text='Receive messages when question is added.', required=False) question_delete = forms.BooleanField(help_text='Receive messages when question is deleted.', required=False) # same fields to come as in the model class Meta: model = ProductNotification fields = ['question_added', 'question_delete', ...] class ProductForm(forms.ModelForm): name = forms.CharField(max_length=50, required=True) # ... product_notification = forms.ModelChoiceField(queryset=ProductNotification.objects.all(), required=False) The problem is: The form adds the new "sub form" product notifications, but instead of a bunch if checkboxes for all the boolean fields, there is only one drop-down menu. I have tried ModelMultipleChoiceField too, without success. Can someone help me to get all the checkboxes displayed instead of one drop-down menu? Thanks a lot :) -
Django - how to order queryset for varying query?
I have this issue where I want to order my queryset according to a compute value based on a query in descending order. Query: ?fruit=Apple&?fruit=Pear In this case: Num. Apples + Num. Pears + (Num. Apples * Num. Pears) models.py class Costumer(BaseModel): name = models.CharField('name'), max_length=255, blank=True fruits = models.JsonField('fruit'), null=True, blank=True, default=dict) My Costumer.fruits looks something like this: fruits = {name: Apple, count: 10}, {name: Pear, count:4}, {name: Cherry, count: 1}, {name: Avocado, count: 2} views.py def get_queryset(self): fruits = dict(self.request.GET).get('fruit', []) queryset = Costumers.objects.all() if fruits: queryset = sorted(queryset, reverse = True, key=lambda costumer: self.calculate_order(costumer, fruits)) return queryset def calculate_order(self, costumer, fruits): value_list = [fruit['count'] for fruit in costumer.fruits if fruit['name'] in fruits] return sum(value_list) + (reduce((lambda x, y: x*y), value_list)) if value_list else 0 This seems to be ordering the data correctly from what I have tested so far, however doesn't seem like the best way to do it. Is there a better way using Django Queryset API for ordering this data? Since the way it's ordering now is a bit time consuming since I have to iterate on all the records on the database. -
django - on model save method, determine if field value is set explicitly, or a default value is being used
With following model; class MyModel(models.Model): my_field = models.CharField(max_length=32, default='default_value') def __init__(self, *args, **kwargs): self.my_field is not None # True def save(self, *args, **kwargs): self.my_field is not None # True MyModel.objects.save(a=1, b=2) # Not setting my_field here Here, in the two methods above (or somewhere else), is there a way to determine of my_field value was set expliclitly, or the model is using the default value here? Checks return True when I don't set a value explicitly for the model field, and has 'default_value' value. -
How to override existing Permission model __str__ method() in django?
By default Permission model str method returns objects as '%s | %s' % (self.content_type, self.name).I want to display only self.name.Is there any way to do this? I tried this but it is not working. from django.contrib.auth.models import Permission class Permission(Permission): def __str__(self): return '%s' % (self.name) -
Exception in django: Query set have no attribute user
Here i am simply using User model from django.contrib.auth.models import User and I have a custom userprofile model where user foreign key in that django built in User model , well i have created an email_address field which can manually update by a user, and there is an other email field which is built in inside django User model , I want to update that email field as userprofile email_address field update. I am simply getting user object which username and try to get email of that user object but getting an error : 'QuerySet' object has no attribute 'email' models.py def save(self,*args, **kwargs): user_obj = User.objects.filter(username=self.user.username) print(user_obj,'user object') print(user_obj.email,'email have a user') email = self.email_address user_obj.email = self.email_address print(user_obj.email,'email have a user') user_obj.save(user_obj.email) super(UserProfile,self).save(*args, **kwargs) -
How to update a list of objects with checkboxes in Django
I have a page that displays a list of messages that each have a checkbox. I want to be able to select one or more of them and toggle their unread status. I have a Message model: class Message(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) sender = models.ForeignKey(Profile, on_delete=models.CASCADE) message = models.TextField(blank=True) unread = models.BooleanField(default=True) And my messages.html looks like this: <ul> <li><a href="{% url 'users:read_message' %}">Mark as read</a></li> <li><a href="{% url 'users:unread_message' %}">Mark as unread</a></li> </ul> {% for msg in messages %} <input type="checkbox" name="message" value="{{ msg.id }}"> <p>{{ msg.message }}</p> {% endfor %} Here are my urls: path('read-message/', MessageRead.as_view(), name='read_message'), path('unread-message/', MessageUnRead.as_view(), name='unread_message'), What I am struggling with is how to pass the selected messages to the view. Here is what I have attempted so far: class MessageRead(UpdateView): model = Message template_name = 'users/messages.html' success_url = 'users/messages.html' def get_queryset(self): message = self.request.GET.getlist('message').values_list('pk', flat=True) message.update(unread=False) return message class MessageUnRead(UpdateView): model = Message template_name = 'users/messages.html' success_url = 'users/messages.html' def get_queryset(self): message = self.request.GET.getlist('message').values_list('pk', flat=True) message.update(unread=True) return message This brings up an AttributeError 'list' object has no attribute 'values_list' Can someone please explain what I'm doing wrong? -
Ho can I post an object data into Django test Client post request?
I'm writing a test to see if form data is validating on post request trying to create a Post object. Here is the code: def setUp(self): user = User.objects.create_user(email='test@gmail.com', password='test', name='test') Post.objects.create(user=user, body='hi') self.post = Post.objects.get(body='hi') self.user = User.objects.get(email='test@gmail.com') self.client.login(email=user.email, password=user.password) @tag('fast') def test_index(self): client = Client() response = client.get('/home/', {}, True) r = client.post(reverse('index'), data={'user': self.user, 'body': 'Test'}, follow=True) print(r, self.user) self.assertTrue(Post.objects.filter(body='Test').exists()) self.assertEqual(response.status_code, 200) but the test fails implying that the object with body "Test" was not created. I already tried encoding data with urlencode but it did not help. Here is what print statement shows: <TemplateResponse status_code=200, "text/html; charset=utf-8"> test -
Prevent unauthorized user from accessing PDF file
I have a web application that allows users to download PDF files. The users are supposed to login or register (if not already registered) and after verification of credentials are allowed to view or download PDFs. Hence, only authorized users are able to access the PDFs. My question is, is there a way in which I can prevent the authorized users from sharing the PDFs with other unauthorized users? I have read about password encryption, digital certificates and Digital Rights Management. I also know that we can hide the toolbar in the browser using embed tag and prevent users from downloading the files. I have also read so many posts saying that preventing users from sharing the PDFs after it has been downloaded is simply not possible. But I just wanna know if it is possible to somehow embed a key with the PDF when it is being downloaded and invoke a script (preferably Python) to verify the user, when the user tries to open the PDF? Any help will be appreciated. Thanks. -
Cannot update a module with pip due to file not found, and cannot delete said module with pip due to file not found
I have taken over a django website, and I need to update the django-fobi module. I cd into the main folder of the project I activate the venv with source ~/Projets/XYZ/venv-dfs/bin/activate I attempt an update with pip install django-fobi --upgrade I get the error : ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/home/me/Projets/XYZ/venv-dfs/lib/python3.8/site-packages/django_fobi-0.12.3.dist-info/RECORD So, instead of updating, I try to delete first, to then do a clean re-install, using pip uninstall django-fobi I get FileNotFoundError: [Errno 2] No such file or directory: '/home/me/Projets/XYZ/venv-dfs/lib/python3.8/site-packages/django_fobi-0.12.3.dist-info/RECORD' This is my first time working with venv and pip, is there a workaround for this? -
Django QuerySet API check if is unique for this id
This is how my model looks like: class Catalog(models.Model): global_id = models.IntegerField(unique=True) name = models.CharField(max_length=30) short_name = models.CharField(max_length=10) description = models.CharField(max_length=200, blank=True) version = models.CharField(max_length=10) class Meta: constraints = [ models.CheckConstraint( check=models.Q( // CHECK IF VERSION IS UNIQUE FOR THIS PARTICULAR GLOBAL_ID // ), name="%(app_label)s_%(class)s_unique_version", ) ] As you can see, I need to make sure that version models are unique for a particular global_id, I just don't know how. Help. -
I can't activate my virtual environment in pycharm
I just made a virtual environment but trying to open it with mypython\Scripts\activate Can anybody tell me why this is not working? The execution of the command -
django-import-export how to skip import some rows based on current user login?
Actually started using django-import-export latest version. Wanted to know where exactly we can override to skip certain rows of the csv from being imported based on current user or the domains from a list of domains he can import data from the csv. How exactly to customize which of the methods to override and how? In my ModelResource, I have created the list of domains for the current user, and which method of the import-export do I check this and skip the rows from being imported? class MailboxResource(resources.ModelResource): mdomain_list = [] def before_import(self, *args, **kwargs): # make changes to csv super(MailboxResource, self).before_import(*args, **kwargs) muser_id = kwargs['user'].id muser = kwargs['user'] # import for all domains if muser.is_superuser: pass # import for domains belonging to the hierarchy elif muser is not None: exist = muser.groups.filter(name='customers').exists() self.mdomain_list.append(Domain.objects.filter( customer__in=Customer.objects.filter( email=muser))) Hence customer should be able to import data from the CSV only for domains that belong to him and skip all other rows from the CSV, which don't exist in the list. CSV: id,name,email,domain, 1,ABC pvt.ltd,abc@zinn.com,zinn.com, 2,XTD,xtd@ggg.com,ggg.co.in, 3,RTG,tiger@goa.com,goa.com If customer doesn't own ggg.com domain, only 1st and 3rd row should get added to the table via import. How can this be achieved? Using python … -
Why the Data of Patient and Doctor are not registred in the database?
when I register the patient or the doctor on the registration platform (sign up),I don't know why the data of the Doctor and Patient are not registred in the database (MySQL)?, I need your helpe please. I have the following code in bas_app\views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.db import IntegrityError from django.contrib.auth import login, authenticate from .forms import MedForm, PatForm, ContactForm from .models import Patient, Médecin, User def accueil(request): return render(request, 'base_app/accueil.html') def inscription(request): if request.method == 'GET': dict_inscription_form = {'form': UserCreationForm()} return render(request, 'base_app/inscription.html', dict_inscription_form) else: # Creer un nouveau compte if request.POST['password1'] == request.POST['password2']: try: # Enregistrer ses données user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() # Se Connecter directement login(request, user) return render(request, 'base_app/apres-inscription.html') except IntegrityError: dict_form_error = {'form': UserCreationForm(), 'error': "Ce nom d'utilisateur existe déjà"} return render(request, 'base_app/inscription.html', dict_form_error) else: # Probléme dans le mot de passe dict_form_error = {'form': UserCreationForm(), 'error': 'Le mot de passe ne correspond pas'} return render(request, 'base_app/inscription.html', dict_form_error) # apres Connection page def apres_inscription(request): return render(request, 'base_app/apres-inscription.html') def apres_connection_medecin(request): return render(request, 'base_app/apres_connection_medecin') # se connecter def se_connecter(request): if request.method == 'GET': return render(request, 'base_app/connection.html', {'form': AuthenticationForm()}) else: user = authenticate(request, username=request.POST['username'],first_name=request.POST['nom'],last_name=request.POST['prénom'],password=request.POST['password']) if … -
Setup Unity mobile app login using Django OAuth2
I built the backend for a Django REST API on mydomain.com and have set up email authorisation and OAuth2 for google and facebook. I am a newbie to Unity (and Django before setting it up). I have a Unity mobile app for iOS and Android(that I obv did not develop myself) that I need to connect to Django for authentication to create users on the app. I've seen this post, but being completely new to JSON and Unity I wouldn't know how to begin implementing anything mentioned. Are there any tutorials with guided steps? Could you provide me with some basic information? The documentation dives straight into the deep end but is still not informative enough for me to use it for oauth. Closest youtube video I've found is for a fitbit and I don't know how to apply anything form there to my case. Literally any help would be greatly appreciated! (please :(( ) -
Upload many images django rest framework
I try to upload many images to one post. I try to achive this: When I post data i get this: What is wrong with my code ? -
Django app does not work after Deploy when I used Pandas
I have a project and it works well when I run the project in pycharm But when I deploy this project on the server, it has a problem The problem is using pandas toolkits It works well when I remove "import pandas as pd" from the files on the server, but when I use this toolkit, the project does not work It should be noted that after Deploy, when this package is used in one of the files, the whole project does not work I use Apache The version of packages on the server and local is the same Pandas version is 1.1.2 -
Error while configuring postgressql for django
I have implemented full text search in my django app using postgresql. But, when I press the search button, I get an error: ProgrammingError at /blog/search/ function similarity(character varying, unknown) does not exist LINE 1: SELECT COUNT(*) FROM (SELECT SIMILARITY("blog_post"."title",... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I don't know where the error is, so if you need any files, I will edit this question. Please help me -
How to embed a filter in the other side of a foreign key relationship in django
I have the following structure: class Room(models.Model): doors: BaseManager class Door(models.Model): deleted = models.BooleanField(default=False) room = models.ForeignKey(to=Room, related_name='doors' ) Now after I've saved a room and saved some doors which reference that room I can load a room and get all the doors in the room... However, when I do a room.doors.all() I actually want to receive only those doors that are not deleted (that have deleted as false). How would you do this with django? -
How to pass value from one method to another and edit value in a model?
I am trying to do OTP-based authentication in Django during user signup but I am not getting how to pass email from signup page to otp page and edit value in model. The signup method is working fine but I am not getting how to update user_status to 'v' i.e. verified for a particular email who is signing up after otp verification. views.py def signup(request): if request.method == 'GET': return render(request,'registration/signup.html') else: postData = request.POST first_name = postData.get('firstname') last_name = postData.get('lastname') email = postData.get('email') username = postData.get('username') phone = postData.get('phone') password = postData.get('password') #validation value = {'first_name':first_name,'last_name':last_name,'email':email,'username':username,'phone':phone} error_message = None if(not first_name): error_message="First Name Required" elif(not last_name): error_message="Last Name Required" elif(not email): error_message="Email is Required" elif(not username): error_message="Username is Required" elif(not phone): error_message="Phone Number is Required" elif len(phone) is not 10: error_message="Mobile Number is Invalid" elif(not password): error_message="Password is Required" elif len(password) < 6: error_message = 'Password must be 6 char long' #saving if not error_message: print(first_name,last_name,email,username,phone,password) customer = Customer(first_name=first_name,last_name=last_name,email=email,username=username,password=password,phone=phone) customer.register() return render(request,'index.html') else: data = { 'error' : error_message, 'values' : value } return render(request,'registration/signup.html',data) def otp(request): if request.method == 'GET': return render(request,'registration/otp.html') else: otp_gen = None postData = request.POST otp_enter = postData.get(otp_enter) otp_gen = random.randint(10000,99999) print(otp_gen) otp_message = … -
Django admin page loads nothing
I am working on a Django project where I ran makemigrations and migrate. seemed to work fine its been a few days since I did that and now my admin page doesn't render anything it shows blank All the other pages work fine when I go to localhost:8000/admin it just shows nothing and the terminal shows this [06/Nov/2020 09:19:26] "GET /admin/ HTTP/1.1" 302 0 [06/Nov/2020 09:19:26] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 0 -
Django: Cache needs to de deleted to see new design changes
I have a Django applciation running in kubernetes environment behind an nginx ingress controller. Often when I redeploy the app with new design changes, the browser history/cache needs to be deleted in order to see the changes. How to automate this process so the user does not need to delete the browser cache to see the latest changes? -
how to fix video displaying error in Django?
So basically I was following a tutorial (https://www.youtube.com/watch?v=aR_JzBGdGvM) on how to upload videos to django but I'm having trouble at the html because the video tag won't play the video, it'll only play the sound. Here is my code <div class="container"> {% for vid in videos %} <h3 class="text-center mt-2 mb-2">{{ vid.caption }}</h3> <video class="embed-responsive embed-responsive-4by3" controls="controls"> <source class="embed-responsive-item" src="{{ vid.video.url }}" type="video/mp4" /> </video> {% endfor %} </div> The for loop and everything is working its just that the video itself won't play. The audio will play but the video won't. I am on a mac if that makes any difference because the video file is a .MOV but even when I try bootstrap's way <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="{{ vid.video.url }}" allowfullscreen></iframe> </div> the video doesn't play it just downloads it. How can I fix this? Please Help! Thank You! -
DJANGO: how to use "core" URL in template
I'm trying to use a "core" url in my template but I don't know what is happening, It won't let me. My url is declared here: url.py: (the djangorestframework is the important one) urlpatterns = [ path('admin/', admin.site.urls), path('consumos/', include('consumptions.urls', namespace='consumptions')), path('registros/', include('logs.urls', namespace='logs')), path('reglas/', include('rules.urls', namespace='rules')), path('djangorestframework/', include(router.urls), name="drf"), path("", include("authentication.urls")), path("", include("dashboard.urls")), ] But when I'm trying to use it in my sidebar I have to sidebar.html: <li class="mt-3 nav-item"> <!-- FIXME: Esta url tiene que haber otra manera de llamarla --> <a target="_blank" class="nav-link" href="/djangorestframework"> <i class="fas fa-cloud"></i> <p> API </p> </a> </li> because it won't let me use it like this: <li class="mt-3 nav-item"> <!-- FIXME: Esta url tiene que haber otra manera de llamarla --> <a target="_blank" class="nav-link" href="{% url 'drf' %}"> <i class="fas fa-user-cog"></i> <p> API </p> </a> </li> It says: Reverse for 'drf' not found. 'drf' is not a valid view function or pattern name. Why I can not use the name of my url? why do I have to use a relative path? Thank you! -
Error "Unknown field(s) (student_id) specified for User" for django-registration two step account activation with custom user
I'm using the two step account activation in django-registration and I get this error when I run the server. I'm also using a custom user created from AbstractBaseUser. The user model automatically sets the email field by student_id. forms.py from django_registration.forms import RegistrationForm from .models import StudentUser class StudentUserRegisterForm(RegistrationForm): class Meta(RegistrationForm.Meta): model = StudentUser in models.py class StudentUserManager(BaseUserManager): def create_user(self, student_id, name, password): user = self.model(student_id=student_id, name=name, email=f'{student_id}@ksa.hs.kr') user.set_password(password) user.save() return user def create_superuser(self, student_id, name, password): user = self.create_user(student_id, name, password) user.is_active = True user.is_superuser = True user.is_staff = True user.save() return user class StudentUser(AbstractBaseUser, PermissionsMixin): object = StudentUserManager() student_id = models.CharField(max_length=10, verbose_name='학번', help_text='00-000', unique=True) name = models.CharField(max_length=100, verbose_name='이름') email = models.EmailField(default=f'{student_id}@ksa.hs.kr') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'student_id' REQUIRED_FIELDS = ['name'] part of urlpatterns in urls.py path('accounts/register/', RegistrationView.as_view(form_class=StudentUserRegisterForm), name='django_registration_register'), path('accounts/', include('django_registration.backends.activation.urls')), in setting.py INSTALLED_APPS = [ 'ksa_books_app', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_registration', ] AUTH_USER_MODEL = 'ksa_books_app.StudentUser' -
Change label of ManyToMany Field django?
class PermissionForm(forms.ModelForm): class Meta: model = Group fields = ['permissions'] widgets = { 'permissions': forms.CheckboxSelectMultiple, } If I render the above form I get the output as: I need to show only the marked area(red color) as label.And one more for example,in the below image there is a accordion,I want to show permission of Group model under role tab and permission of organization model under organization tab.I don't have any idea how to start with