Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is always returning 404 while testing. "The requested resource was not found on this server."
I have an Django API that I build quickly, and now I want to add some tests to ensure is stable. The problem is that Django simply refuses to let me access any resource on the server. It can't find any URL. I have some models, but this test is with the User model. # auth/urls.py urlpatters = [ ... path( "user/<str:email>/", views.UserView.as_view(), name="public staff user", ), ... ] # auth/tests/tests.py (Folder workign as a submodule, tests.py is a temporary name) from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient, APITestCase from authentication.models import User import os # Create your tests here. class TestTestCase(APITestCase): def setUp(self): self.staff_user = User.objects.create( email="test@account.me", is_staff=True, is_active=True ) self.staff_user_password = "staff_password" self.staff_user.set_password(self.staff_user_password) def test_testing(self): print(User.objects.all()) url = reverse("public staff user", kwargs={"email": self.staff_user.email}) print(url) response = self.client.get( url, ) print(response.content) I have a few unused imports, but those don't matter. I create a User instance, and change it's password. Then, in the test, I try to retrieve it's data. I can confirm the user exists (the shell returns <QuerySet [<User: Employee#000>]>) and the url works (/api/user/test@account.me/ works with another email in the dev database). However, response.content returns the following: # Escaped for ease … -
How can I use a value in a models.Model?
I wondering to know how it is possible to pass a value into a model. For example, I'm tryng to get the supplier_id : class Question(models.Model): q = models.CharField(max_length=250, blank=True, null=True) def get_audited(self, *arg, **kwargs): bar_param = kwargs.get('pk') **bar_param** = 11 <-- supplier_id ? return AuditSupplier.objects.filter(question_id=self, supplier_id=**bar_param**) def __str__(self): return self.q -
Generating an encrypted file on a webpage daily
I have a python program that reads an encrypted file to extract the required settings and time. The encrypted file should be updated per each minute and should be accessed remotely by multiple users. Is there a way to generate that encrypted file on a webpage (with a fixed hyperlink; say www.website-name.com/log.txt) and replaces the older file at a specific time frame (for example, per minute, hourly, daily, etc). Then, I can access that file from its url. Is there a way to do that? -
Unable to solve thisReverse for 'read_post' with arguments '('',)' not found. 1 pattern(s) tried: ['read_post/(?P<id>[0-9]+)$']
I have a navbar in my template in which i am trying to add active class however whenever i do that get this error:NoReverseMatch at / Reverse for 'read_post' with arguments '('',)' not found. 1 pattern(s) tried: ['read_post/(?P[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'read_post' with arguments '('',)' not found. 1 pattern(s) tried: ['read_post/(?P[0-9]+)$'] Exception Location: C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.2 Python Path: ['C:\Users\Abdullah\Desktop\Blog\my_blog', 'C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Abdullah\AppData\Local\Programs\Python\Python39', 'C:\Users\Abdullah\AppData\Roaming\Python\Python39\site-packages', 'C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Wed, 21 Apr 2021 09:38:37 +0000 my base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <link rel="stylesheet" href="{% static 'css/posts.css' %}"> {% url 'posts' as posts %} <nav> <ul> <li><a class="nav_a {% if request.path == posts %} active {% endif %}" href="{% url 'posts' %}">Blogs</a></li> {% if request.user.is_authenticated %} <li><a class="nav_a" href="{% url 'myposts' %}">Welcome {{ request.user }}</a></li> <li><a class="nav_a" href="{% url 'post' %}">Post</a></li> <li><a class="nav_a" href="{% url 'myposts' %}">My Posts</a></li> <li><a class="nav_a" href="{% url 'logout' %}">Logout</a></li> {% else %} <li><a class="nav_a" href="{% url 'signup' %}">Signup</a></li> <li><a class="nav_a" href="{% url 'login' %}">Login</a></li> {% … -
Disable prefers-color-scheme: dark in django admin
I have dark mode enabled on Mac but it's looks awkward in django admin panel with ckeditor. Is it any option to disable it in Chrome or Django admin? I've already tried themes and extensions - no success. -
Come posso impostare il valore del radio button in modo dinamico e salvarlo nel database?
Ciao a tutti, sto lavorando a un progetto Django e ho problemi a salvare i dati di un record scelto da una tabella json, nel mio database. in views.py --> creo la tabella json def upload_csv(request): df = pd.read_csv(os.path.join(settings.BASE_DIR,'Cooling-S1.csv')) # parsing the DataFrame in json format. json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'d': data} return render(request, 'upload.html', context) in upload.html --> mostro la tabella e aggiungo un radio buttom in ogni riga {%include 'base.html' %} {% load static %} {% block content %} <form method="POST" name="form" action="{% url 'upload_servizio' %}"> {% csrf_token %} <h2 class="text-center"><u>Cooling S1</u></h2><br> <table class="table table-dark table-striped"> <thead> <tr> <th>Level</th> <th>Name</th> </tr> </thead> <tbody> <!-- jinja2 Technique --> {% if d %} {% for i in d %} <tr> <td>{{i.Level}}</td> <td>{{i.Name}}</td> <td> <input id= "risposta" name="risposta" type="radio" value= "{{i}}" > </td> </tr> {% endfor %} {% endif %} </tbody> </table> <button type="submit" class="btn btn-success">Save</button> </form> <p><a href="{% url 'home' %}">Return to home</a></p> {% endblock %} Ho inserito un radio buttom in ogni riga, ma non riesco a capire come passare i valori della riga scelta al mio modello per salvarli. il mio modello: class Upload(models.Model): level = models.CharField(max_length=40, help_text='Inserisci il nome … -
jquery function not registering changes
I have a jquery script in my django project that reads checkboxes and then submits them to a function when clicked. My problem is that this only works when I reload my page. is it possible to have the jquery script "listening" allt the time to the checkboxes? <script> $(document).ready(function() { var vals=[]; $.each($("input[name='checkb']:checked"), function() { vals.push($(this).attr('id')); }); console.log('calling function:',vals) $('.print').click(function() { console.log('print:',vals) $.get('eprint/ticked/',{marked: vals}) }) $('.delete').click(function() { console.log('delete:',vals) $.get('edelete/ticked/',{marked: vals}) }); }); </script> {% for l in object_list %} <tr> <td> <form> <label><input type="checkbox" id={{l.pk}} name="checkb"></label> <form> -
Sections in admin.py django became inline
Display, filter, and search fields float to the left. @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'post', 'created', 'active') list_filter = ('active', 'created', 'updated') search_fields = ('name', 'email', 'body') -
method_descriptor object has no attribute 'now' - while returning in function encoded with strings [closed]
while running the below snippet the error is thrown on datetime.time.now() Error msg : method_descriptor object has no attribute 'now' from datetime import datetime def fileprocces(file_path, max_width=0, width=0, height=0): file_dir = _get_file_dir(file_path) file_name = _get_file_name(file_path) return f" {file_dir}/thumbnails/{max_width}/pro_pic{datetime.time.now()}.jpg" -
How do I include an oninvalid attribute while using django widget tweaks?
{% render_field form.field_1 class="form-control mb-2" type="text" onkeyup="empty_select_check(this)" oninvalid="this.setCustomValidity(' ')" %} I am currently using django widget tweaks to render my fields. However, on some fields that are required, if users do not fill up those fields, the default "Please field in this field" or "Please select a list" will appear. I have tried using the invalid attribute which was recommended by stackoverflow on another question. This attribute works fine when I use it on an input element but when I insert it into widget tweaks, I get the following error: Template Syntax Error: Could not parse the remainder: '"this.setCustomValidity('' from '"this.setCustomValidity('' I am unsure of how I can remove the pop-up without using the oninvalid attribute. Anyone has any other plausible suggestions? As seen below, i have attempted to replace the "pop-up" with my js way of checking the field. JS doesnt work and pop-up still shows up though. function empty_value_check(ele) { let value = ele.value; if (value === '') { $(ele).addClass('is-invalid'); } else { $(ele).removeClass('is-invalid'); } } function empty_value_all() { $('#field_1_id').each(empty_value_check(this)); return !($('.is-invalid').length > 0) } -
Set ordering in django to use language specific order
I have a Django app with the following models that have the ordering set with class Meta: class Akutsomatik(models.Model): bereichname = models.CharField(max_length=200) class Meta: ordering = ['bereichname'] def __str__(self): return self.name # This model is only included in the example for better understanding class Klinik(models.Model): name = models.CharField(max_length=200) akutsomatik = models.ManyToManyField(Akutsomatik, blank=True) def __str__(self): return self.name And my template: {% if klinik.akutsomatik.all %} <ul> {% for akutsomatik in klinik.akutsomatik.all %} <li>{{ akutsomatik }}</li> {% endfor %} </ul> {% endif %} The problem is that the data of my app is in German and the ordering is set to UTF-8. The output would look something like that: Augenchirurgie / Ophtalmologie Brustchirurgie Viszeralchirurgie Wiederherstellende Chirurgie Ästhetische Chirurgie but in German it should be like: Ästhetische Chirurgie Augenchirurgie / Ophtalmologie Brustchirurgie Viszeralchirurgie Wiederherstellende Chirurgie Note that the Ästhetische Chirurgie should come before Augenchirurgie / Ophtalmologie. Does anyone now if there is a way to set the collation in class Meta? I tried the following as decribed [here][1]: class Meta: ordering = [Func('bereichname', function='utf8_general_ci', template='(%(expressions)s) COLLATE "%(function)s"') ] But I get the following error: collation "utf8_general_ci" for encoding "UTF8" does not exist LINE 1: ...ER BY ("klinik_finder_akutsomatik"."bereichname") COLLATE "u... I also tried to set … -
how to update one only one field
I'm working on a small project using Django / Rest Framework. I would like to update my table ( since I have already some rows ) I want to update only one column status but I get an error about other fields are required: how can I update only one field, exactly status, I want to set the status to 1, without updating the other columns, (Django keep telling me other fields are required like title, mobile) this is my code : obj = Task.objects.filter(id=tasks['id']).first() serializer = self.serializer_class(obj, data = {'status':1}) if serializer.is_valid(): serializer.save() -
How can I traverse through two list concurrently in one for loop using in django templates to be implemented in a chatbot app
So I am trying a chatbot application where the user will take a user string response and after that, the chatbot will throw a reply. Meaning that it should be able to traverse in two string lists user_response and chat_response in one for loop. The problem that I am having is that I have no idea how to implement this in Django that suits the way I need to implement it. I should implement it this way: {% for chat in user_chat#<-not sure here %} <div class="chat self animated slideInUp fast"> <div class="user-photo"> <img src="{% static 'images/account_200px.png'%}"alt="Self"></div> <div class="chat-message">{{ user_chat }} </div> </div> <div class="chat friend animated slideInUp fast"> <div class="user-photo"> <img src="{% static 'images/icon-at.png'%}"alt="Dog"></div> <div class="chat-message"> {{ response #<-the response from system|safe}} </div> </div> {% endfor %} Meaning in that one instance of a loop I should be able to render two divs with different classes that obviously have different messages that came from two different string lists. Like for loop{ render(user_chat) render(system_response) } Which in turn should produce this kind of response Given that: user_chat = ["Hi", "I am okay", "good!"] system_response = ["How are you", "How Okay are you?", "Oh that's great to hear"] Will make Hi … -
I have a static react app in Django DRF app. I want to pass a url with parameters to my react static app. But Django catches my reuest url
mysite.org/donate/27/99/3cdb23510af9f36aac7e7b741f8deddc482c5e25 I want to pass this to my react app url.py urlpatterns = [ path('', index, name="index"), path(r'posts',index,name="index"), path(r'donate/$/$/$',donate,name="donate"), # path(r'/',index, name="index"), # path(r'/$', index, name="index"), path('admin/', admin.site.urls), path('api/v1/', include('posts.urls')), path('api/profiles/', include('posts.profile_url')), path('api/likes/', include('posts.like_url')), path('api/follows/', include('posts.follow_url')), path('api/comments/', include('posts.comment_url')), path('api/volunteers/', include('posts.volunteer_url')), path('api/donates/', include('posts.donate_url')), path('api/bids/', include('posts.bid_url')), path('api/locations/', include('posts.location_url')), path('api-auth/', include('rest_framework.urls')), path('api/v1/dj-rest-auth/', include('dj_rest_auth.urls')), path('api/v1/dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('swagger/', schema_view.with_ui( # new 'swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui( # new 'redoc', cache_timeout=0), name='schema-redoc'), path('api/login/', CustomAuthToken.as_view(), name='login'), path('api/register/', CreateUser.as_view(), name='register') ] views.py from django.contrib.auth import get_user_model from rest_framework import viewsets # new from .models import Profile from .models import Post from .models import Like from .models import Follow from .models import Comment from .models import Volunteer from .models import Donate from .models import Bid from .models import Location from rest_framework import serializers from django.shortcuts import render #frontend from .permissions import IsAuthorOrReadOnly from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from .serializers import ProfileSerializer, PostSerializer, UserSerializer, LikeSerializer, FollowSerializer, CommentSerializer, VolunteerSerializer, DonateSerializer, BidSerializer, LocationSerializer # new def donate(request): return render(request, "build/index.html") def index(request): return render(request, "build/index.html") I have a static react app in build folder that is accepting request in my local env with integration with django. If django is accepting all the url requests. How can I forward … -
method_descriptor object has no attribute 'now' - while returning in function
while running the below snippet the error is thrown on datetime.time.now() Error msg : method_descriptor object has no attribute 'now' from datetime import datetime def samplefun(file_path, max_width=0, width=0, height=0): file_dir = _get_file_dir(file_path) file_name = _get_file_name(file_path) return f"{file_dir}/thumbnails/{max_width}/pro_pic{datetime.time.now()}.jpg" -
django rest framework generate file link from frontend(8000) domain not backend(8080)
I'm using DRF for backend and React for frontend. In DRF I return link to my local saved file. Django application takes 8080 port and react 8000. And when I create Request from Frontend, DRF return path to file with localhost:8000/media/... I need localhost:8080/media/... -
Clashing reverse accessors and queries in Django for many to many field?
from django.db import models class Appointment(models.Model): doctors = models.ManyToManyField('Doctor', through='AppointmentAccess', related_name='appointments') class Doctor(models.Model): appointments = models.ManyToManyField('Appointment', through='AppointmentAccess', related_name='doctors') I get the following error: core.Appointments.doctors: (fields.E302) Reverse accessor for 'PatientProfile.users' clashes with field name 'Doctor.appointments'. HINT: Rename field 'Doctor.appointments', or add/change a related_name argument to the definition for field 'Appointment.doctors'. core.Appointment.doctors: (fields.E303) Reverse query name for 'Doctor.appointments' clashes with field name 'Appointment.doctors'. HINT: Rename field 'Doctor.appointments', or add/change a related_name argument to the definition for field 'Appointment.doctors'. core.Doctor.appointments: (fields.E302) Reverse accessor for 'Doctor.appointments' clashes with field name 'Appointments.doctors'. HINT: Rename field 'Appointment.doctors', or add/change a related_name argument to the definition for field 'Doctor.appointments'. core.User.patient_profiles: (fields.E303) Reverse query name for 'Doctor.appointments' clashes with field name 'Appointments.doctors'. HINT: Rename field 'Appointments.doctors', or add/change a related_name argument to the definition for field 'Doctor.appointments'. Why? Can someone help me understand this error? The many to many field should be kept track of through the AppointmentAccess table instead of generating a new intermediary table. How does the related name appointments clash with doctors? -
How to NOT override context in Django DetailView with get_context_method?
I use get_context_method in my DetailView class to get a pk value needed for my query. But now I cant get object values in my template, cause get_context_method just override them. Is there any other way to get a pk key in DetailView? Or how to not override object values? In other words, how to make this work properly? ##views.py class UserDetailView(DetailView): model = User def get_context_data(self, **kwargs): context = super(UserDetailView, self).get_context_data(**kwargs) id = int(self.kwargs.get('pk')) props = Statistics.objects.filter(user=id, property=100) extra_context = {'user_property':props} return extra_context Template: div class="container"> <div class="col-sm-6"> <h1>{{ object.user.full_name }}</h1> <h5>Property</h5> <div class="flex-container"> <div class="flex-scores"> <ul class="scores"> <li>{{user_property}} </div> </ul> </div> </div> -
Python How to get the dates of the weeks?
Let say in the month of April, in week-1 dates will start from April 1 to April 7, then week-2 would be April 8 to April 14, week-3 would be April 15 to April 21, then April 22 to April 28 for week-4. But there is still 2 remaining days because the end date of April is 30. My question now is, how can i get the April 1, 2, 3, 4, 5, 6, and 7 in week one? Then April 8, 9, 10, 11, 12, 13, 14 in week two, and etc.? -
django preview generator for s3 bucket
i am using django preview generator to generate thumbnail of a pdf and it is working fine in local path = settings.BASE_DIR cache_path = str(path) + '/media/thumbnail' manager = PreviewManager(cache_path, create_folder=True) img_obj = serializer.file_uploads.url url = str(path) + str(img_obj) pdf_or_odt_to_preview_path = str(url) path_to_preview_image = manager.get_jpeg_preview(pdf_or_odt_to_preview_path) but when using s3 bucket it is unable to detect the directory of uploaded file my s3 bucket setting is: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') # AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE = 'edubook.s3boto3.CustomS3Boto3Storage' AWS_S3_REGION_NAME = 'ap-south-1' AWS_S3_CUSTOM_DOMAIN = 'https://abc.s3.amazonaws.com/' -
Accessing Forienkey objects from the queryset recieved through AJAX
I ask for a queryset from my views.py on a AJAX request in django. The model in use has a foriegnkey field which is related to User. I am not able to access those foreignkeyed elements. My views.py looks like this @csrf_exempt def replies(request): if request.is_ajax and request.method == "POST": cid = request.POST.get('cid', None) data = { 'replies': serialize("json", Comment.objects.filter(replyTo=cid[1:])) } return JsonResponse(data) My model Comment looks like this class Comment(models.Model): commenter = models.ForeignKey(User, on_delete=models.CASCADE) cid = models.UUIDField(default=uuid.uuid4, editable=False) commentText = models.TextField() likes = models.ManyToManyField('User', related_name='likes') commentOn = models.ForeignKey(Article, related_name='commentOn', on_delete=models.CASCADE, null=True, blank=True) created_at = models.DateTimeField(default=timezone.now) replyTo = models.UUIDField(null=True, blank=True) def __str__(self): return f'{self.commenter.first_name + " [" + str(self.likes.count()) + "]"}' and the my ajax request looks like this $.ajax({ type: 'POST', url: '{% url 'replies' %}', data: { 'cid':id }, dataType: 'json', success: function (data) { if (data.replies) { var htmldata="" var actual = JSON.parse(data.replies); for(var x in actual){ htmldata+="<p>"+actual[x].fields.commentText+" "+actual[x].fields.commenter.first_name +" "+actual[x].fields.created_at+"</p>" } box.html(htmldata); } } }); I get a output like <my comment text> undefined <date time> I am able to get why am i getting "undefined" in place of the users first_name. Thanks in advance. -
How to use dropbox with Django on heroku?
I'm fairly new to django. So heroku doesn't support image storage so I will have to use an other container for it. I've found a lot of tutorials for using Amazon S3 but I would like to use dropbox since it's free. Is this possible? I've found this package https://django-storages.readthedocs.io/en/latest/ but I still don't understand how to use it. If anybody has used it please help me out. Thanks. -
Django: How to filter property through ORM or Mysql?
model: class Production(models.Model): copy = models.ForeignKey('self', related_name='children', on_delete=models.SET_NULL, blank=True, null=True) @property def num(self): n = 0 if self.copy: n += 1 n += self.copy.num return n I want to filter out data that has been copied more than 2 times. But my approach is too slow. qs = [q for q in Production.objects.filter(copy__isnull=False) if q.num > 2] Is it possible to use ORM or MySQL? -
Redirect to referer after post in CreateView in django
I have defined a CreateView in django I want to redirect to the referer of that view if that referer contants ‘center’. The idea is like “iredirect the page that brought you to the CreateView if that page’s path contains ‘center’” I am trying with the following code but is not working since self.request.META.get('HTTP_REFERER') is returning the path of the same createView class CompanyCreateView(LoginRequiredMixin, CreateView): model = CompanyModel context_object_name = 'company' template_name = 'riesgo/company/company_form.html' form_class = CompanyForm def get_success_url(self): if self.request.method == 'POST' and "_continue" in self.request.POST: return reverse('riesgo:company_update', kwargs={'pk': self.object.id}) elif 'center' self.request.META.get('HTTP_REFERER','/'): # here I want to redirect to page that brought you to the createview of the company else: return reverse_lazy("riesgo:company_detail", kwargs={"pk":self.object.id}) -
Using relay mutate_and_get_payload when using graphene-file-upload library
Currently, I am working on a project where we use relay for all views. In one of the views, we are to upload a file and we are using graphene-file-upload which uses graphene.Mutation mutate(). My question is there a way we can use relay mutate_and_get_payload()? I have tried bu failed at the moment