Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using multiple custom event as triggers in HTMX, can I identify which of the triggers is being used?
I am using HTMX in my Django project to change elements in a form depending on previous selections. At some point I use a custom event and listen for it as indicated in solution 3 here: https://htmx.org/examples/update-other-content/ Everything works as expected, also when using two triggers separated by a comma. However, I would like to pass a header, the value of which depends on the event being used as trigger. Trigger foo -> header A, trigger bar -> header B. Below is some code that should help understand. <div hx-get="{% url 'someurl' %}" hx-trigger="foo from:body, bar from:body" hx-target="#sometarget" hx-swap="outerHTML" hx-headers='{"someheader":"foo_value"}' OR '{"someheader":"bar_value"}'> So far, I have tried: putting target.value as header value (you can use it as trigger filter, so I thought it might work in hx-headers too) Passing headers or context variables in the view that causes the trigger to go off, so that then I can use Django's {% if %} in the template. But they don't get here because that view renders a different part of the template, and this is just being triggered because it listens for the event on the body due to event bubbling Any suggestions? -
save an object with django createview from a form and additional fields
I'm confused about how to add additional fields in my_model that are excluded from my HTML form defined in forms.py while saving with createview! models.py: class My_model(models.Model): # attrs in the form that are saved already with now problem ... #attrs excluded in forms.py but I want to save them along with the form attr_1=models.CharField(max_length=30) attr_2_type=[('a','A'),('b','B')] attr_2=models.Charfield(max_length=8,choices=attr_2_type) ... def get_absolute_url(self): return reverse("application:redirectin_pattern_name", kwargs={"pk":self.pk}) views.py: class StagesInitCreateView(CreateView): model= My_model form_class = MyModelForm template_name = "satges/mymodel.html" mymodel.html <div class="row "> <div class="col-md-3"></div> <div class="col-md-6"> {% block form %} <form method="post" action="{% url 'application:pattern_name' %}"> {% endblock form %} {% csrf_token %} {{ form.as_p }} <input class="form-control btn-primary" type="submit" name="save" value="send your demand" /> </form> </div> </div> here everything is working fine the form is showing and I can submit data and save it to the database then I get automatically redirected to the details page of the object I saved and all the details are correct I even checked passing ids of another object to see if it changes and show the details of each object called and it works too. now I just want to save the remaining attributes of the model at the same time when I'm saving the form … -
Django ORM where in two columns with subquery
Imagine I have two tables. One lists licenses customers have, each with a specific version and type. The other table has general shared info about the licenses (eg name, price, duration), also listed by type and version. I need to query the information table for any rows pertaining to licenses a given customer has. In pure SQL, that can be accomplished with this subquery: select * from version_details where (version, type) in (select version, type from licenses where company_id = '6f65e5cc-cd1f-4888-a236-38295bae393a'); Is there a way to accomplish this with Django ORM? I know how to use a subquery but I can't figure out how to do a wherein with two columns. -
Django Admin Page, Part addition
OperationalError at /admin/parts/part/add/ no such table: parts_part It keeps showing this error no matter how many times I have edited the models.py and admin.py code, whenever I try to add a part as a superuser it is showing the same error -
Make form with dynamical amount of inputs in django template
The crux of the problem is this: I have a Schema that will later be converted to a .csv file. However, I need to populate this schema with data. To do this, I need columns that will have fields (Name, data type, order, etc.) But I don't know how many columns the Schema will have Therefore, the wording sounds like this: Create a form with a dynamic number of columns. While I was writing the question, I had an idea to create a "Scheme" table in the database and bind a table - "Column" to it Thus, when you click "add column", a new instance will appear that will already be bound to this Schema. Am I thinking in the right direction or do you have another idea? The picture below will allow you to convey the essence of the problem more accurately. Thank you in advance -
Unable to push on heroku
I'm trying to push my code on heroku but keep getting this error below Things I've tried Make new branch and add and commit to it and push using git push heroku newbranch:master Change requirements.txt encoding to UTF-8 and ANSI -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app -----> Python app detected -----> Using Python version specified in runtime.txt Traceback (most recent call last): File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> r = f.read().strip() File "/usr/lib/python3.8/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input ! Requested runtime (��python-3.10.2 ! Aborting. More info: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed -
Division, district, upzilla, pourosova/Union, ward, zip code implement in django
I want to implement Bangladeshi Division, district, upzilla, pourosova/Union, ward,zip code in django website..how i can implement it using django ? Can anyone help me or give me some suggestions .. -
How to update model object when testing UpdateView Django
I'm having some issues when I test an update view in my code.Here's the view: class PatientUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): permission_required = 'main.change_patient' model = Patient template_name = 'patient/edit_patient.html' form_class = PatientUpdateForm And this is the patient model: class Patient(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) middle_name = models.CharField(max_length=50, blank=True, default='') hospital_number = models.IntegerField(unique=True, default=0) age = models.IntegerField(blank=False) sex = models.CharField(max_length=6, choices=gender_choices, default='female') weight = models.CharField(max_length=10, choices=gender_choices, default='female') def __str__(self): return f' {self.hospital_number} --> {self.first_name} {self.last_name}' def get_absolute_url(self): return reverse('patient_detail', args=[str(self.id)]) Here's the form: class PatientUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PatientUpdateForm, self).__init__(*args, **kwargs) gender_choices = [ ('male', 'Male'), ('female', 'Female') ] marriage_choices = [ ('married', 'Married'), ('single', 'Single') ] self.fields['gender'] = forms.ChoiceField(choices=gender_choices) self.fields['marriage_status'] = forms.ChoiceField(choices=marriage_choices) class Meta: model = Patient fields = [ 'first_name', 'last_name', 'hospital_number', 'age', 'sex', 'weight' ] And the test case: class PatientsTest(TestCase): def setUp(self): self.superuser = get_user_model().objects.create_user( email='genuis@gmail.com', username='supergenius', password='password', is_superuser = True ) def test_patient_update_view(self): data = { 'first_name':'Joe', 'sex' :'female', } new_patient = Patient.objects.create( first_name='John', last_name = 'doe', hospital_number = 2, age=24, sex = 'male', weight='79 Kg', ) self.client.login(username=self.superuser.username, password='password') response = self.client.post(reverse('patient_edit', kwargs={'pk': new_patient.id}), data) self.assertEqual(response.status_code, 302) # should go through for superusers, response code … -
How to add a new foreign key field in model django without migration error?
I have two models A, B, they contain a lot of data(int database). Suddenly I decided to add a foreign key in model B to A. But Django can't migrate it because existing rows in table B haven't value for this FK. What should I do in such a situation? -
how to correct text orientation for scanned pdf file
I am trying to correct the orientation of the scanned pdf file to correct alignment. I have been attempting with image format using Deskew packagebelow I have uploaded image but I need to correct orientation for the pdf file but I need to update the orientation of the pdf file. Please suggest any resources or code or documentation. -
JavaScript Redirect to Django view with parameters
These lines of code produce an error, my question is, how can I pass the IDS and MESSAGES parameters to windows.location.href in Django view. $(function () { console.log("HOME"); let ids = 1; let messages = "My personal Message"; let myurl = "{% url 'message-page' ids messages %}"; //ERROR HERE: IDS and MESSAGES are variables return window.location.href = myurl }); -
Problem with handling nested dictionary on Django Rest Framework
Testing Django Rest Framework. I receive the following JSON as a result of the POST request for entry (it is important here that the keys of the dictionary, the rest are trifles): { "title": "Test title10", "description": "Test description10", "client": { "name": "Egor10", "surname": "Egor11", "phone": "1645342534532", "adress": "st. Egor9, 53453" }, "products": ["Karamel", "Shokolad", "Limon", "Banan"], "delivery_adress": "st. Egor44", "delivery_date": "2022-23-09:44:00", "delivery_code": "4562gdgll" } I have two models: from django.db import models class Client(models.Model): name = models.CharField(max_length=100, blank=True) surname = models.CharField(max_length=100, blank=True) phone = models.CharField(max_length=100, blank=True) adress = models.CharField(max_length=150, blank=True) class Order(models.Model): title = models.CharField(max_length=100, blank=True) description = models.CharField(max_length=255, blank=True) delivery_code = models.CharField(max_length=50, blank=True) delivery_adress = models.CharField(max_length=150, blank=True) client = models.ForeignKey('Client', on_delete=models.CASCADE, null=True, related_name='orders') Next, I want to make a serializer and look towards SlugRelatedField or Nested relationships to process the nested dictionary relationship: "client": { "name": "Egor10", "surname": "Egor11", "phone": "1645342534532", "adress": "st. Egor9, 53453" } For SlugRelatedField I tried this story in the serializer: class OrderSerializer(serializers.ModelSerializer): orders = serializers.SlugRelatedField( read_only=True, slug_field='phone' ) class Meta: model = Order fields = ['title', 'description', 'delivery_code', 'delivery_adress', 'orders'] In views.py I do the standard processing: def post(self, request): serializer = OrderSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() And this whole story does not work … -
ModuleNotFoundError: No module named 'api.company'
I'm doing a Django project and the only thing I've seen today is this error: File "/home/user/Work/ud_pytest_2/api/company/admin.py", line 4, in <module> from api.company.models import Company ModuleNotFoundError: No module named 'api.company' 1)I set up a virtual environment with pipenv, and it's activated and has all the packages installed. 2)I can easily import packages I installed like django, pytest 3)When I'm trying to import packages from the ACTUAL project, let's say, the class Company from the models section, VSCode doesn't give me any error and actually recognizes the file exists... 4)But when I runserver, it says the module wasn't found. I think it's some kind of path issue but I can't figure out what 5) Already selected the correct interpreter 6) Already trying the Python Path https://i.ibb.co/4KfHhRr/Project.png From the image, I'm showing my project tree. Whenever I try to import what's marked as yellow (I marked it yellow), I get that error, even though VSCode doesn't warn me and even sugest that actual import. Can't figure why the interpreter isn't recognizing the import. I think it's something related to the virtual environment and the Paths but i'm not sure Thanks in advance -
AttributeError at <URL> During Email Verification Python Django
I'm developing the backend of my React-Native application on Python Django. I'm trying to implement registration + email verification. First, the user sends their information for registration in a request. The is_active field is set to False by default. A verification_token is created for each user, stored in a separate table in the DB. The user receives an email which has a link appended with the created verification_token. The VerifyPatient class handles the email verification by checking if the token is equal to the token in the db. I receive the email just fine but get an AttributeError when I click the link, so the user doesn't get registered. My models.py file: from django.db import models from django.contrib.auth.models import User class VerificatonToken(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='token') verification_token = models.CharField( max_length=256, blank=True, null=True) My serializers.py file: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework_jwt.settings import api_settings from .models import VerificatonToken class TokenSerializer(serializers.ModelSerializer): class Meta: model = VerificatonToken fields = ('user', 'verification_token',) class PatientSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( required=True, max_length=32, validators=[UniqueValidator(queryset=User.objects.all())] ) first_name = serializers.CharField( required=True, max_length=32 ) last_name = serializers.CharField( required=True, max_length=32 ) # DOB … -
Increment Django database value every day
let's assume I've created a Django model with an integer field of count, with initial value for every record equal to 0. How do I increment this value, for every record of the db, once every day? -
Cache.get returns None when using Memcache
Would like to use Memcache to store and retrieve a list of all online users. I am using my console to test if my cache and memcache work but not getting the correct output/ So example when I run this $ python manage.py shell >>> from django.core.cache import cache >>> cache.set("foo", "bar") >>> cache.get("foo") I do not receive any output after running cache.get("foo"). I would be expecting to receive the output bar This is what I have in my settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } USER_ONLINE_TIMEOUT = 300 USER_LASTSEEN_TIMEOUT = 60 * 60 * 24 * 7 my middleware: import datetime from django.core.cache import cache from django.conf import settings class ActiveUserMiddleware: def process_request(self, request): current_user = request.user if request.user.is_authenticated(): now = datetime.datetime.now() cache.set('seen_%s' % (current_user.username), now, settings.USER_LASTSEEN_TIMEOUT) and models.py: from signup import settings ... class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... def last_seen(self): return cache.get('seen_%s' % self.user.username) def online(self): if self.last_seen(): now = datetime.datetime.now() if now > self.last_seen() + datetime.timedelta( seconds=settings.USER_ONLINE_TIMEOUT): return False else: return True else: return False -
Django - Print Dictionary of List of Lists in a Table in HTML
I have a Dictionary of List of Lists. I want to print this as a structured way preferably a table. For each hostname, i want its specified rows in the table with three columns (Address Interface State ID ) with apprpriate entries printed out. It seems a very complicated nested loop if possible. Here is the dictionary ospfdictkey being passed to the template {'hostname': [['R1-ISP'], ['R2-ISP']], 'ospfneighboraddress': [['192.168.5.2', '192.168.5.13', '192.168.5.25'], ['192.168.5.1', '192.168.5.6', '192.168.5.32']], 'ospfneighborinterface': [['ae1.0', 'ae4.0', 'ae7.0'], ['ae1.0', 'ae2.0', 'ae9.0']], 'ospfneighborstate': [['Full', 'Full', 'Full'], ['Full', 'Full', 'Full']], 'ospfneighborID': [['172.0.0.2', '172.0.0.4', '172.0.0.5'], ['172.0.0.1', '172.0.0.3', '172.0.0.6']]} HTML Code {% for ip in listip %} {% for ospfadd in ospfdictkey.ospfneighboraddress %} {% for a in ospfadd %} <tr> <td>{{ a }}</td> </tr> {% endfor %} {% endfor %} {% endfor %} Here is the end result im getting but its repeating keys data and how do i iterate over other keys to print next as table data ? -
django.security.SuspiciousOperation.response_for_exception:99- Attempted access to '/mediafiles/some' denied
The following line raw_file = fileUpload.objects.get(fileName=str(raw_file_fetch)) path_temp = fileUploadSerializer(raw_file).data["local"] The path_temp returns the error django.security.SuspiciousOperation.response_for_exception:99- Attempted access to '/mediafiles/some' denied. Any ideas how to fix this? -
Django graphene accept any mutation input
In mutation, I just need to save the event name and its payload that might differ and I do not need any validation for it. How can I say graphene that I just need to accept an object? class SendEvent(MutationMixin, relay.ClientIDMutation): class Input: event = graphene.String(required=True) payload = # any object -
Improve Django application logs to only display custom log from Logging settings
I am trying to improve the logging of my Django application to have it in a standardized way for querying it with Loki and for each log that I create, 3 log entries are recorded. For example, any request (sucess or failed) to this endpoint below will generate three log entries. views.py class ModelViewSet(models.ModelViewSet): def retrieve(self, request, *args, **kwargs): try: # do something logger.info(f"{request.path} {request.method} 200: user {request.user.id} - success!") return Response(serializer.data) except Exception as exc: logger.warning(f"{request.path} {request.method} {exc.status_code}: user {request.user.id} - {exc.detail}") return Response(exc.detail, status=exc.status_code) settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'timestamp': { 'format': '{asctime} {levelname} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'timestamp' }, }, 'loggers': { 'django': { 'handlers': ['console', ], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } Output in console 2022-06-02 10:26:09,714 WARNING /api/v1/<path/ GET 403: user 71 - You do not have permission to perform this action. 2022-06-02 10:26:09,814 WARNING Forbidden: /api/v1/<path/ 2022-06-02 10:26:09,815 WARNING "GET /api/v1/<path/ HTTP/1.1" 403 12495 Any suggestion on how to optimize and have only one entry, preferably my custom logging entry and get rid of the other two? This will also help reduce drastically the size of the logs stored. -
React and django cache issue
I have a react and django app which is being served behind nginx. The /admin route and /api routes both point to uwsgi. However when loading these routes the react app is served unless a hard refresh of the page is peformed. It seems like react is serving all routes instead of just the index. Is there a way to exclude routes in react so it will only display if the path is "/" or is there something in nginx/django config I can change to overcome this issue. This is a snippet from my nginx conf: location / { try_files $uri $uri/ =404; } location /api/ { uwsgi_pass uwsgi; include /etc/nginx/uwsgi_params; } location /admin/ { uwsgi_pass uwsgi; include /etc/nginx/uwsgi_params; } and my django urls config: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include(routers.urls)) ] Any ideas on how I could proceed would be appreciated -
Django development static 404 not found: new files only
Curious issue on Django development server. Static files which are in existing use work just fine. When I add new files (of any sort) I get 404 not found. settings.py DEBUG = True INSTALLED_APPS = [ 'django.contrib.staticfiles', ] STATIC_ROOT = os.path.join(BASE_DIR, '') STATIC_URL = '/static/' template <img src="{% static 'media/cypress.jpg' %}"/> <!-- old file works --> <img src="{% static 'media/butterfly.jpg' %}"/> <!-- new file returns 404 --> Jquery files which were in use are found, those which were sat in the same folder unused before aren't. I assume therefore it's an indexing issue of some sort. I've tried python manage.py collectstatic but no joy. Any guidance much appreciated. -
I need to redirect users to a previously typed link after authentication. (I am using Django)
In my App, being authenticated is a must to access the content. Let's say someone shared a link such as http://website.com/form/ioxPwhRtV8zeW2Lj9njZjs4065Ml6u/viewform. If not authenticated, it redirects the user to the main login page. I need to figure out how once authenticated I redirect the same user back to the previously typed link http://website.com/form/ioxPwhRtV8zeW2Lj9njZjs4065Ml6u/viewform. I am using Django version 4.4 for my app. For a reference, here is my code: def login_view(request): """ Display the login form and handle the login action. """ form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) now = datetime.datetime.now() current_time = now.strftime("%I:%M %p, %B %d") msg = f'Success - Logged in at {current_time}' messages.success(request, msg) # Look over here. It redirects not to the location typed, but the home page. I want it to redirect any authenticated user to the previously typed URL. return redirect("/") else: msg = 'Invalid credentials' messages.error(request, 'Error validating the form') else: msg = 'Error validating the form' messages.error(request, 'Error validating the form') return render(request, "accounts/login.html", {"form": form, "msg": msg}) Mates, I need help fast. -
django models hierarchy question: related attributes of a ManyToManyField
As a fresh coder, I seriously have problems to build my models relations. Please check these two cases, How can I set current_reading_pages on my Scenario2? from django.db import models # Scenario1: Users can record their reading progress of a book. class Book(models.Model): name = models.CharField(max_length=128) class User(models.Model): current_reading_book = models.ForeignKey('Book', on_delete=models.CASCADE) current_reading_page = models.IntegerField() Result1: No problems about database, but Users can records their progress of only one book. Other scenario, which I want to build: from django.db import models # Scenario2: Users can record their reading progress of multiple books. class Book(models.Model): name = models.CharField(max_length=128) class User(models.Model): current_reading_books = models.ManyToManyField('Book') # current_reading_pages = ??? I want to save all progress of current books, for example, User A is reading 3 books, book1 till page 100, book2 till page 10, book3 till page 0. -
Adding a comment through page instead of /admin - django
I am able to add comments to a page through the /admin panel and I would like to be able to do so through a buttom.. I've created an HTML page and added a some functionality for it forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('commenter_name', 'comment_body') widgets = { 'commenter_name': forms.TextInput(attrs={'class': 'form-control'}), 'comment_body': forms.Textarea(attrs={'class': 'form-control'}), } views.py @login_required(login_url='/accounts/login') def add_comment(request, slug): movie = Movie.objects.get(slug=slug) form = CommentForm() context = {'form': form} return render(request, 'add_comment.html', context) add_comment.html <form action="add_comment.html" method="post"> <textarea name="comment" id="comment" rows="10" tabindex="4" required="required"></textarea> <a href="{% url 'movies:add_comment' movie.slug %}" class="myButton">Submit</a> urls.py path('<slug:slug>', MovieDetail.as_view(), name='movie_detail'), path('<slug:slug>/add-comment/', views.add_comment, name='add_comment'), models.py class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = models.ImageField(upload_to='movies') banner = models.ImageField(upload_to='movies_banner', blank=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=10) status = models.CharField(choices=STATUS_CHOICES, max_length=2) cast = models.CharField(max_length=100) year_of_production = models.DateField() views_count = models.IntegerField(default=0) movie_trailer = models.URLField() created = models.DateTimeField(blank=True, default=timezone.now) slug = models.SlugField(blank=True, null=True) class Comment(models.Model): movie = models.ForeignKey(Movie, related_name="comments", on_delete=models.CASCADE) commenter_name = models.ForeignKey(User, default=None, on_delete=models.CASCADE) comment_body = models.TextField() date_added = models.DateTimeField(auto_now=True) def __str__(self): return '%s - %s' % (self.movie.title, self.commenter_name) I've confirmed the URL works and the html webpage add_comment is shown.. my goal is to allow the user to comment - …