Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to display the information that related to a specific user
i have this Model class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) address = models.CharField(max_length=200, null=False) city = models.CharField(max_length=200, null=False) state = models.CharField(max_length=200, null=False) zipcode = models.CharField(max_length=200, null=False) date_added = models.DateTimeField(auto_now_add=True) and this view def view_profile(request): data = cartData(request) cartItems = data['cartItems'] shippingAddress = ShippingAddress.objects.all() args = {'user': request.user, 'cartItems': cartItems, 'shippingAddress': shippingAddress} return render(request, 'store/profile.html', args) template {% for sa in shippingAddress %} <p>address: {{ sa.address }}</p> <p>city: {{ sa.city }}</p> <p>state: {{ sa.state }}</p> <p>zipcode: {{ sa.zipcode }}</p> {% endfor %}`enter code here` the problem is the template display all the Shipping Addresses in the DB and i want it just to display the Shipping Address that related to the signed in user Thanks -
Translating a pluralized string in Django
When working with a translated string that needs a pluralized word, is it best to just pass in the pluralized word or use ngettext and have a singular/plural sentence? Example 1 (passing in the pluralized word): ugettext("You have {count} {apple_pluralized}").format( count=apple_count, apple_pluralized=ngettext("apple", "apples", apple_count) )` Example 2: ngettext("You have {count} apple", "You have {count} apples", apple_count).format(count=apple_count) My understanding is the second approach is always recommended because it's not always as simple as swapping in a word. For example, even in English, there is 1 object vs there are 2 objects. Is this correct? And if so, are there any situations where the first approach might be preferred? -
not able to access any course materiel in open edx
I have installed open edx and now want to set up ios app but I can not see my courses content I get this error ( your action could not be completed) -
Django admin: created users have plain text password and can't login
I want to have a custom tab for staff users so in admin.py I do: class StaffUser(User): class Meta: proxy = True @admin.register(StaffUser) class AdminUserAdmin(admin.ModelAdmin): pass But on the admin site, whenever I add a new user with this interface I can't log in with it since for some reason it sets it's password as plain text instead of hashing it. I've read this post BUT if I do that and change StaffUser to inherint from AdminUserI get this other error AttributeError: type object 'StaffUser' has no attribute '_meta' -
How to print all model fields ignoring reverse related and relates fields
I am trying to print all model fields and their values as follows def pretty_print_model_fields(m: Model): if not m: data = None else: data = {} for f in m._meta.fields(): data[f.name] = getattr(m, f.name) return data The issue is some of reverse_related does not exist -> error RelatedObjectDoesNotExist How can I ignore reverse_related and related fields all together -
When deploying Django application on cpanel, application does not connect to static files
I am trying to deploy django application from cpanel. I have managed to deploy the site and everything works apart from the static files part, because my website loads without any styling. My settings.py part looks like this : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'assets'), ] STATIC_ROOT= os.path.join(BASE_DIR,'static') When I run command on cpanel terminal command "python manage.py collectstatic", It runs fine and copies over the files however website loads without styling. Also my base html looks something like this (in case I need to change something there however on local server everything was running fine): {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>About</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Work+Sans:100,200,300,400,700,800" rel="stylesheet"> <!-- {% static 'website/css/owl.carousel.min.cs' %} --> <link rel="stylesheet" href="{% static 'website/css/open-iconic-bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'website/css/animate.css' %}"> -
Trying to write a unit test for django-rest-passwordreset, but the password seemingly will not change in the test?
I have the standard installation of django-rest-passwordreset. I am trying to test the password reset process. Here is my unit test: def test__password_reset_resets_password_success(self): testing_password = "Testing12345" # Generate a user and trigger the password reset user = self.login_basic_user() user.set_password(wrong_password) body = {"email": user.email} self.make_request("POST", url=self.password_reset_url, data=body) # Go and get the password reset email and token self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0] url, token = self.get_url_and_token(message.body) # Resetting the password body = {"password": testing_password, "token": token} resp = self.make_request("POST", url=self.password_change_password_url, data=body) self.assertEqual(resp["status"], "OK") self.assertTrue(user.check_password(testing_password)) However, for some reason the check_password at the end does not return True with the new password. It only returns true with the old password. It seems that for some reason the POST is not causing the new password to be saved to the database. Why might this be? I have tested the urls manually with the DRF interface, so I know the password resets successfully that way. -
Django: MultipleChoiceFilter on Model TextChoices
I have a Model which holds models.TextChoices. class Visit(BaseModel): class VisitStatus(models.TextChoices): INQUIRED = 'INQ', _('Inquired') OPTIONAL = 'OPT', _('Optional') CONFIRMED = 'CON', _('Confirmed') ACTIVE = 'ACT', _('Active') INACTIVE = 'INA', _('Inactive') CANCELLED = 'CXL', _('Cancelled') I am trying to use the MultipleChoiceFilter from django-filter as follows: class VisitFilter(django_filters.FilterSet): status = django_filters.filters.ChoiceFilter(choices=models.Visit.VisitStatus, empty_label=None) class Meta: model = models.Visit fields = ['status'] I keep getting the following TypeError Exception Type: TypeError Exception Value: __call__() missing 1 required positional argument: 'value' Any suggestions? -
Manually rendered form fields do not save data
I really wanted to figure this out myself and I spent over 4 hours on the subject but I give up now. I have a form that is supposed to save data, and if I lay out the form with the {{ form }} tag everything works great. If I put in to form with individual tags like {{ form.client_email }}, the form data is not saved to the database. I need to render these fields manually for front end purposes but I just couldn't figure out how to do it. I appreciate your help a lot. Here is my code. views.py def client_list_view(request): if request.method == 'POST': form = ClientModelForm(request.POST) if form.is_valid(): client_title = form.cleaned_data["client_title"] client_email = form.cleaned_data["client_email"] client_turkishid_no = form.cleaned_data["client_turkishid_no"] client_tax_no = form.cleaned_data["client_tax_no"] client_tax_office = form.cleaned_data["client_tax_office"] client_contactperson = form.cleaned_data["client_contactperson"] client_phone_number = form.cleaned_data["client_phone_number"] Client.objects.create( client_title=client_title, client_email=client_email, client_turkishid_no=client_turkishid_no, client_tax_no=client_tax_no, client_tax_office=client_tax_office, client_contactperson=client_contactperson, client_phone_number=client_phone_number ).save() return redirect("books:client-list") else: form = ClientModelForm() client_list = Client.objects.all().order_by("client_title") context = {'client_list' : client_list, "form": ClientModelForm} return render(request, 'clients/client_list.html', context=context) Working template <div id="clientModal" class="modal bottom-sheet"> <div class="modal-content"> <form method="POST"> {% csrf_token %} {{form}} <button class="btn">Ekle</button> </form> </div> </div> Not Working Template <div id="clientModal" class="modal bottom-sheet"> <div class="modal-content"> <div class="row"> <div class="col s12"> <ul class="tabs"> <li class="tab … -
Django - getting the selected results return from data in template inside a for- loop
I having some issues in getting the selected to show on my res summary. I was able to get data from an api and load inside a Django template. On the Django template, this data is in a for loop, . it only works when I selected the first data inside that for loop which I am able to display on the res summary and insert into the database but for the rest of the data I cannot. -
Django + nginx security in production
I recently found a big security breach in a project I did with django. The application was deployed in production and worked properlly using Nginx, I also use python decouple to separate my sensitive information. Here is the permissions on the project files: -rw-r--r-- 1 rouizi rouizi 151 Oct 8 21:30 .env -rw-rw-r-- 1 rouizi rouizi 65 Jul 9 07:50 .env.example drwxrwxr-x 8 rouizi rouizi 4096 Sep 23 15:50 .git -rw-rw-r-- 1 rouizi rouizi 244 Jul 14 09:18 .gitignore drwxrwxr-x 5 rouizi rouizi 4096 Sep 22 16:17 core -rwxrwxr-x 1 rouizi rouizi 624 Jun 25 13:58 manage.py drwxrwxr-x 3 rouizi rouizi 4096 Oct 8 21:27 prof -rw-rw-r-- 1 rouizi rouizi 599 Jul 14 09:18 requirements.txt drwxrwxr-x 4 rouizi rouizi 4096 Jun 25 13:58 static drwxrwxr-x 5 rouizi rouizi 4096 Jun 25 14:02 staticfiles drwxrwxr-x 3 rouizi rouizi 4096 Oct 6 09:11 templates drwxrwxr-x 4 rouizi rouizi 4096 Jun 25 14:02 users drwxrwxr-x 6 rouizi rouizi 4096 Jun 25 13:59 venv let say my domain name is exemple.com. What I didn't know is if I try to access exemple.com/.env I can see the content of the .env file. This is really bad because this file contains the secret key and other … -
Delete db item in Django Python via Javascript button
I have written a small application in which want to build in a function which provides the possibility to delete database items (stored earlier) via a html button and Jinja (dynamic link building). Models.py Forms.py Views.py Etc. Have all been updated correctly. However the problem in building the link to delete a certain item gets triggered by the fact that i can't seem to succes in passing the db item (item.id) to the dynamic link because i have decided to put a javascript pop-up in between that asks for a confirmation before deleting the item. All attempts have failed until now. After endless searching for a solution i hope anyone can help me with this... First i generated a for loop that displays all the items in the db to which i have added a button "delete". This buttons triggers a javascript pop-up which works fine asking if the item must be deleted or the command should be cancelled. i don't seem to succeed in putting the dynamic link behind the last confirmation button. Python > Django > HTML > HTML Jinja > Javascript > HTML Jina For the moment the link has been build (lacking any better solution) as … -
Django not able to submit form using ModelForm
The form is always sending a Get request instead of a Post which has been explicitly added using method = "POST". So, not able to persist the data to db. I have just started with Django so, any help will be appreciated. Below are the code snippets: create_order.html <form method="POST" action="{% url 'home' %}"> {% csrf_token %} {{form}} <input class="btn btn-primary btn-sm" type="submit" name="Submit"> </form> urls.py urlpatterns = [ path('', views.dashboard, name='home'), path('products/', views.product, name='products'), path('customer/<str:cust_id>/', views.customer, name='customer'), path('create_order/', views.create_order, name='create_order'), ] views.py def create_order(request): form = OrderForm() if request.method == 'POST': print("In Post", request.method) form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: print("In else", request.method) print(form.is_valid()) if form.is_valid(): form.save() return redirect('/') context = {'form' : form} return render(request, 'accounts/create_order.html', context) terminal output In else GET False -
Django merge querysets in one page
In django rest framework i am using pagination of 20 on a model. Now i want to make a queryset which takes 5 items which has the featured field as true. The other 15 should be items which has the featured field as false. Does anyone have an idea how to make this work? -
Django url without pk or slug (One to Many Relationship)
Please can anyone help me ou with this, I am totally lost.I am new and trying to learn django. I am trying to update my model formset using update views without using the model primary key on the url (eg: update-pet-health/<int:pet_id>/<pk>) I want it to be just update-pet-health/<int:pet_id> scenario: A pet in a vet clinic might have multiple health concerns. Model: class PetHealth(models.Model): pet_health_id = models.BigAutoField(primary_key=True, null=False) pet = models.ForeignKey('Pet', null=False, on_delete=models.PROTECT) symptom_type = models.CharField(null=True, blank=True) date_of_symptom = models.DateTimeField(null=False, auto_now_add=True) symptom_observed_by = models.CharField(null=True, blank=True) date_of_cure = models.DateTimeField(null=False, auto_now_add=True) cured_by = models.CharField(null=True, blank=True) give_medication = models.BooleanField('Propose Medication', null=False) date_medication_proposed = models.DateField('Date Medication Proposed', null=True, blank=True) Medication_given_by = models.CharField(null=True, blank=True) comments = models.TextField('Comments', null=True, blank=True) This is the form I used for...it is the same as the createview cbv Form: class PetHealthForm(forms.ModelForm): class Meta: model = PetHealth fields = [ 'symptom_type ', 'symptom_observed_by', 'cured_by ', 'give_medication', ] PetHealthFormset = modelformset_factory(PetHealth, form=PetHealthForm, extra=3) I'm trying to update the form using update view and here is my cbv for update View: @method_decorator(login_required, name='dispatch') class UpdatePetHealth(UpdateView): base = ... template_name = base + '/update_pet_observation.html' model = PetHealth form_class = PetHealthForm def get(self, request, *args, **kwargs): pet_id = self.kwargs.get('pet_id', None) formset = PetHealthFormset(queryset=PetHealth.objects.filter(pet_id=pet_id)) context = {'pethealthissues': … -
Django Foreign key relation views.py and template html
I have 3 tables related for listing a product with features, i want to list FeatureItem values with for loop in template html file. I ve tried to write a view class but i couldn't succeed. Any Suggestion which approach for views.py and template.html file would be best solution? Thanks. class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() slug = models.SlugField() category = models.ForeignKey(Category, on_delete=models.CASCADE) feature = models.ForeignKey(Feature, on_delete=models.CASCADE) class FeatureItem(models.Model): feature_title = models.CharField(max_length=100) feature_description = models.CharField(max_length=100) feature_id = models.ForeignKey(Feature, on_delete=models.CASCADE) class Feature(models.Model): title = models.CharField(max_length=100) description = models.TextField() -
How can I filter the queryset I use in my ModelChoiceField field?
I have looked at several answers on SO but I haven't found one that address my particular case. I have this ModelForm which I am using in Django admin panel. class AssignInventoryForm(ModelForm): class Meta: model = Driver fields = [] template = forms.ModelChoiceField(queryset=ItemTemplate.objects.all(), empty_label="(Select Template)") template.label = 'Template' def save(self, driver): driver = self.form_action(driver) return driver I would like to be able to filter ItemTemplate like so: ItemTemplate.objects.filter(id=driver.item.id) But obviously driver is not defined at that point of the code. -
How would you write an `is_pdf(path_to_file)` function in Python?
I have a Django project that creates PDFs using Java as a background task. Sometimes the process can take awhile, so the client uses polling like this: The first request starts the build process and returns None. Each subsequent request checks to see if the PDF has been built. If it has been, it returns the PDF. If it hasn't, it returns None again and the client schedules another request to check again in n seconds. The problem I have is that I don't know how to check if the PDF is finished building. The Java process creates the file in stages. If I just check if the PDF exists, then the PDF that gets returned is often invalid, because it is still being built. So, what I need is an is_pdf(path_to_file) function that returns True if the file is a valid PDF and False otherwise. I'd like to do this without a library if possible, but will use a library if necessary. I'm on Linux. -
Upload multiple images with Django Rest Framework
I am trying to upload multiple images from a Vue app to a Django Rest Framework api. Works fine for one image and thanks to this post I made it work for multiple images. But it feels like I missed something and I was wondering how I could improve this code. It feels like hacky code because: the serializer only returns one serialized object (and although it works the serialized object seems odd) I now need to create another serializer for simple get requests with one single image Should I split the images at view level a call a simple serializer with many=True? In create method or perform_create method? Tried a couple of things but without success Thanks for any help you may provide! models.py class Photo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='photos') owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='photos') image = models.ImageField(upload_to=upload_path) view.py class PhotoViewSet(viewsets.ModelViewSet): serializer_class = PhotoSerializer permission_classes = (IsOwner,) parser_classes = (MultiPartParser, FormParser,) def perform_create(self, serializer): serializer.save(owner=self.request.user) def get_queryset(self): user = self.request.user project = self.request.query_params.get('project') if user.is_authenticated: return Photo.objects.filter(owner=user, project=project) raise PermissionDenied() serializers.py class PhotoSerializer(serializers.ModelSerializer): image = serializers.ListField( child=serializers.ImageField(allow_empty_file=False) ) class Meta: model = Photo fields = ['id', 'image', 'project'] def create(self, validated_data): images = validated_data.pop('image') for image in images: … -
Django 2.2 and Rest Framework 3.11 - partial updating model "owner" field (ForeignKey) with owner's username string instead of pk
Django 2.2 and Rest Framework 3.11 I have an Alarm model. Every alarm instance can optionally have an owner (the standard django User model). I want to be able to partially update (PATCH) an alarm by setting its owner just using his/her username (string) instead of the pk. Right now, I can update an alarm's owner only by using his/her pk. I tried various things, like: override the update() method in the AlarmSerializer class but whenever I use the owner's username string instead of the pk in the PATCH call, I get back: { "owner": [ "Incorrect type. Expected pk value, received str." ] } play with nested serializers and lookup_field but no luck so far. The api call (PATCH) should look like this: url: /api/alarms/{alarm_id}/ Payload: { "owner": "owner_username" } How can I do that? Thanks models.py from django.db import models from django.conf import settings class Alarm(models.Model): """ this class is meant to represent a network alarm (a.k.a. event or ticket) coming from some monitoring system (Zabbix, Nagios, etc.) """ customer = models.CharField(max_length=50) owner = models.ForeignKey( settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=True, ) managed = models.BooleanField(default=False, blank=False, verbose_name="Managed ?") device_type = models.CharField(max_length=150) ... serializers.py from django.contrib.auth.models import User from rest_framework import … -
Django permission not working when variable in Axios request
I ran into a really strange error today while setting up restrictions on some of my Vue pages. I'm attempting to make this GET request: try { let actors = await $axios.$get(`/api/v1/users/${loggedInUser.id}/`); return { actors }; } catch (e) { return { actors: [] }; } }, I get back an empty actors [] object, but if I swap out ${loggedInUser.id} with just 1: try { let actors = await $axios.$get(`/api/v1/users/1/`); return { actors }; } catch (e) { return { actors: [] }; } }, I get back the actors: [] object I want. ({{loggedInUser.id}} returns 1 in the template). In Django I have the permission for this user's group set to myapp|user|Can View user Is there some reason that the variable in the Axios call is messing with the perms? I've tried already something like : const id = loggedInUser.id and await $axios.$get(`/api/v1/users/id/`) -
How can I solve my connection error in mysql
I've tried to connect my db. All db settings in settings.py is checked and they are correct. When I run the server, I face an error which is shown below. I searched at internet and I find solutions but all them is working for lower python version. I am using the newest python version. My error is that: System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 197, in connect self.init_connection_state() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 231, in init_connection_state if self.features.is_sql_auto_is_null_enabled: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res … -
Check if a string has a capital letter in Django?
If I have a string "Hello", how do I check if the string has at least one capital letter and one lowercase letter in Django? -
Django pagination request page given context
Is there a clever way to request a specific page from Django pagination if I know the content I want. e.g. article = Article.objects.get(pk=10) articles = Article.objects.all() paginator = Paginator(articles, 10) paginator.get_page_containing(article) Note. get_page_containing doesn't exist but illustrates what I'd like to do. -
Using primary keys in Django and connecting multiple CBVs in database
I am incredibly new to Django and I'm struggling to get something to work in my project even after extensive research (I've been trying this over and over for about 2 days straight now and I'm sure I'm not finding the right answer because I'm probably not looking for the right question). When I try and add a class based model (Artifacts) to another model in my database (Exhibit), it successfully adds the artifact data to the database but does not show up in the front end as I expect. The Exhibit view is already connected to another view (Case) and that all seems to work fine. model.py: class Artifact(models.Model): exh_ref = models.ForeignKey(Exhibit, on_delete=models.CASCADE, null=True) art_type = models.CharField(max_length=50) description = models.CharField(max_length=100) source = models.TextField(max_length=500) notes = models.TextField(max_length=1000) def get_absolute_url(self): return reverse('exhibit_detail', kwargs={'pk': self.pk}) def __str__(self): return self.art_type + " - " + self.description and class Exhibit(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE) exh_ref = models.CharField(max_length=20) exh_pic = models.ImageField(upload_to='exhibit_pics', blank=True, null=True) exh_type = models.CharField(max_length=50) exh_make = models.CharField(max_length=50) exh_model = models.CharField(max_length=50) exh_PIN = models.IntegerField() exh_periph = models.TextField() exh_condtn = models.TextField() special_cat = models.BooleanField(default=False) def get_absolute_url(self): return reverse('case_list') def __str__(self): return self.exh_ref + " Make: " + self.exh_make + " Model: " + self.exh_model Views.py: …