Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Good is Django compared to Single Page web applications like angular?
I wanted to know that is there really a very significant difference between Single Page Web applications like Angular which use APIs and traditional MVC based ones like Django? What would be the best combination for the backend (API) and Frontend to create robust web applications? -
run ajax call to get form submitting data first, then run the following JavaScript
I have build a Django web app. In the frontend, I want to run the ajax call to get the form submitting data first, then run the following JavaScript to process according to the real time data passed from backend. <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script> async function myFunction() { Swal.fire({ title: '', text: "Do you want to confirm entries?", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes', cancelButtonText: 'No' }).then((result) => { if (result.value) { $("#myform").submit(); $.ajax({ url: '127.0.0.1:8000/content_checklist_name_url', type: 'get', // This is the default though, you don't actually need to always mention it success: function(data) { alert(data); }, failure: function(data) { alert('Got an error dude'); } }); const result = await if (data.includes('saved')) { Swal.fire( '', 'Entries have been saved.', 'success' ) } else { Swal.fire( '', 'Duplicate Entry. This Course Code already exists.', 'error') } } else { window.stop(); } }) } But the error shows: await is only valid in async function. How could I run ajax to get the data(form submitting result) from backend first then run the if condition: if (data.includes('saved'))? So I could do different pop up from the results passed from backend in real time. -
Django Celery Dynamic Schedule
In my app, i have a reminder system and i want to notify the user at their given time. these are models.py file class Reminder(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="reminder" ) name = models.CharField(max_length=255) remind_at = models.DateTimeField(null=True, blank=True) class Notification(models.Model): reminder = models.ForeignKey(Reminder, on_delete=models.CASCADE) message = models.CharField(max_length=255) and this is the views when user create a reminder: def create_reminder(request): if request.method == 'POST': Reminder.objects.create( user=request.user, remind_at=request.POST['remind_at'], name=request.POST['name'] ) return HttpResponse("Created the reminder") Current i am notifying the user like every hour i running a task with celery beat. this is the tasks.py @shared_task(name ="notify_as_reminder") def notify_as_reminder(): reminder = Reminder.objects.filter( remind_at__gte=timezone.now()-timezone.timedelta(hours=1), remind_at__lte=timezone.now() ) for r in reminder: Notification.objects.create( user=r.user, message="Hey ! You have schedule meeting about to start after one hour" ) and this is celery beat app.conf.beat_schedule = { 'notify_as_reminder': { 'task': 'send_notification', 'schedule': crontab(hour='*/1'), }, } I think the celery beat running the method even there is no notification needs to send to the user. I want exactly same time the user set a time to remind them. I mean dynamically. I heard of apply_async and django_celery_beat Can anyone tell me which one is better to solve problem? or there is any other way to do it? Can … -
Django - The empty path didn’t match any of these
This is the error I get when I run this code: python3 manage.py runserver error message my url.py file looks like this: from django.contrib import admin from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('home/', TemplateView.as_view(template_name="home.html")), ] In settings.py under the templates option it looks like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, 'template'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And my overall directory looks like this: directory I was following this tutorial: https://www.youtube.com/watch?v=IHTP8-KskcQ I got stuck around 7 minutes in, does anyone know the issue? -
how to add links to navigation bar
I'm making a blog web site using django and I add a sticky navigation bar to web site and also it work pretty well but want add links to menu in the navigation bar.I can't do it because there already link in href.I want to keep this link in href because it make navigation bar sticky.I make this sticky navigation bar with help of w3 school website.here is my code <!DOCTYPE html> <html> <head> <title>Dinindu Theekshana</title> <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> </head> <body> <style> body { font-family: "Roboto", sans-serif; font-size: 17px; background-color: #fdfdfd; } .shadow{ box-shadow: 0 4px 2px -2px rgba(0,0,0,0.1); } .btn-danger { color: #fff; background-color: #f00000; border-color: #dc281e; } .masthead { background:#3398E1; height: auto; padding-bottom: 15px; box-shadow: 0 16px 48px #E3E7EB; padding-top: 10px; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } #navbar { overflow: hidden; background-color: #333; color: #333; z-index: 9999999; } #navbar a:hover { background-color: #ddd; color: black; } #navbar a.active { background-color: #294bc5; color: white; } .content { padding: 16px; padding-top: 50px; } .sticky { position: fixed; top: … -
Convert objects into queryset
Probably, it is a bad and db expensive idea, but is there a way to convert list of objects back to a queryset? foo_list = [foo1, foo2, foo3, ...] something like: foo_qs = queryset(foo_list) So that i can return paginated queryset?? -
Confused when delivering PrimaryKeyRelatedField to the Client
If you extract the value of the field used as PrimaryKeyRelatedField, you will see the value in the form of Object, not PK. In the case of the official document, I am using it as below, but it is confusing when using it with the client. I don't know if the tracks will contain id or Object just by looking at the field name. class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Album fields = ['tracks'] def create(self, validated_data): tracks = validated_data.pop('tracks') # [Track, Track ...] Is there a better way? -
Django form submit with hundreds of Celery tasks
I have created a system that enables a user to select users and notify them. When they submit their form, the code will execute a celery task to notify each user. I am getting browser timeouts when sending to 100s of users. Here is a simplified version of my code. Note that my code works as intended, it's just slow when # of users gets into the 100s. Happy to add more if it helps with the answer, but I really want to focus on the generalizable crux of the issue. Note that there reasons why I need so many editable inputs that I'd rather not get into. Let just assume that they are a constraint for the purpose of this question. HTML <form action="" method="POST"> {%csrf_token%} <input type="submit" value="Send"> <table> <tr> <th>User</th> <th>Input 1</th> <th>Input 2</th> <th>Input 3</th> <th>Input 4</th> <th>Select</th> </tr> {% for u in users %} <tr> <td>u</td> <td><input type="text" name="input-1-{{u}}" value=""></td> <td><input type="text" name="input-2-{{u}}" value=""></td> <td><input type="text" name="input-3-{{u}}" value=""></td> <td><input type="text" name="input-4-{{u}}" value=""></td> <td><input type="text" name="input-4-{{u}}" value=""></td> <td><input type="checkbox" name="select-{{u}}" value="True"></td> </tr> {% endif %} </table> </form> Views if request.method == 'POST': # users is a queryset for u in users: # input-#- is a form … -
Custom authorization in Django Rest
I am just a newbie with Django, python. I try to build 1 simple API Collection include CRUD basic, and authentication, authorization. I have 1 simple Views like: @api_view(['GET']) @permission_classes([IsUser]) def get_test(request : Request): return JsonResponse({"message": "success"}, status = status.HTTP_200_OK) and IsUser is: class IsUser(IsAuthenticated): def has_permission(self, request : Request, view): token = request.query_params.get('token') if token: role = jwt.decode(token.split(" ").__getitem__(1), key="secret_key",algorithms="HS256").get('role') if role == 'User': return True else: return False return False My purpose wants to parse the JWT token and authorization based on that. I wonder don't know if my way is really correct? Can anyone give me some comments as well as documentation to better understand this issue? I don't use any other lib because I want to code by myself at first to understand the flow. Thanks for helping me. -
transferring data between JavaScript frontend and Django backend - noob asks
I am exploring web dev very in-depth for the first time and I'm trying to make a chrome extension that sends, let's say, a string to a Django back end, the Django back end processes said string and returns a result back to the chrome extension. I'm doing this because from what I can tell, I can't make a pure Django chrome extension and I am already familiar with Django (although of this I am unsure). Can anyone point me towards some tools I should research to accomplish this? I keep seeing terms like POST, GET, AJAX but have no idea where to begin. Thanks! -
Gunicorn tmp folder fetch my files which got empty
When i was working on server my changed file got deleted but i didn't have restarted gunicorn yet so my system is working properly but i want to get the code of that file. I have tried to look into many directories but didnt found the file Can anyone guide to know where the file will be because i think it might be saved in a temporary directory -
django How to review blog comment before publish?
I am new in django. I want to review my blog comment before it publish or show in my html template. I am using MPTTModel in my model for child parent relationship in my comment section. I used BooleanField in my models but it's not working. Right now my html template showing all blog comment when any user submitting comment. here is my code: #models.py class BlogComment(MPTTModel): blog = models.ForeignKey(Blog,on_delete=models.CASCADE) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') name = models.CharField(max_length=250) email = models.EmailField(max_length=2000) comment = models.TextField(max_length=50000) created_at = models.DateTimeField(auto_now_add=True,blank=True,null=True) updated_at = models.DateTimeField(auto_now=True,blank=True,null=True) is_approve = models.BooleanField(default=False) #forms.py class CommentFrom(forms.ModelForm): class Meta: model = BlogComment fields = ['name','email','comment'] views.py class BlogDetail(DetailView): model = Blog template_name = 'blog_details.html' def get(self,request,slug): blog = Blog.objects.get(slug=slug) form = CommentFrom() context = {'form':form, 'blog':blog, } return render(request,'blog_details.html',context) def post(self,request,slug): blog = Blog.objects.get(slug=slug) form = CommentFrom(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = blog comment.save() messages.add_message(self.request, messages.INFO, 'Your Comment pending for admin approval') return redirect(reverse('blog-detail', kwargs={'slug':slug})) else: form() context = {'form':form, 'blog':blog, } return render(request,'blog_details.html',context) #html {% load mptt_tags %} {% recursetree blog.blogcomment_set.all %} <p>comment: {{node.comment}}</p> {% if not node.is_leaf_node %} <div class="children pl-2 pl-md-5"> {{ children }} </div> {% endif %} {% endrecursetree %} -
Store data of React in Django Database without using Models
I am trying to build a simple project in React and Django. I am a beginner. I am trying to build a punch in machine. I am working on a feature where the user when clicks the image then it displays the time and date she clicked the image. I want to store that time and date in database.But I do not know how to? Do I need to create Model or can be done without the model. My code so far Index.js function CDate(){ const dt = null; const [cdate,setDate] = useState(dt); const handelDate = () =>{ let dt = new Date().toLocaleString(); setDate(dt); } return( <> <h3>{cdate}</h3> <img src={punchin} alt="PunchinMachine" onClick={handelDate} /> </> ) } ReactDOM.render(<CDate />,document.getElementById("root")); Could you please me store the time she clicked in the db so that I can keep track of time. -
"Any" path in Django?
Is it possible to define a route that will be redirected to if Django could not find a match in the defined URLs? For example, let's say I have: urlpatterns = [ path('ajaxlogin', views.ajax_login, name='ajaxlogin'), path('ajaxprofile', views.ajax_profile, name='ajaxprofile'), ] Can I define a "dynamic" URL of a specific view that will be redirected to if the path doesn't exist? Suppose I enter the URLs /ajaxsignup and /ajaxdelete, which are not defined, but have them redirected to a URL of a certain view? In other words: urlpatterns = [ path('ajaxlogin', views.ajax_login, name='ajaxlogin'), path('ajaxprofile', views.ajax_profile, name='ajaxprofile'), path('every-other-url', views.another_view, name='path-everything-else'), ] I know there's Django's error handlers, but are there any other ways to achieve this? I have my frontend based separately on a React application, so I'd very much appreciate a "dynamic" URL rather than using Django's default 404 responses. I suspect that if path couldn't do it, I could use the old url with regex -- but I still have no clue. Thanks in advance. -
django rest framework set image field to null when updating the field
Here is my code; models.py class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255, blank=True, null=True) cover_image = models.ImageField(blank=True, null=True) def __str__(self): return f"{ self.title } - { self.author }" serializer.py class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' views.py class BookListViews(generics.ListAPIView, generics.CreateAPIView, generics.RetrieveUpdateDestroyAPIView): queryset = Book.objects.all() serializer_class = BookSerializer The object is created alright, but when I try to update the title or author field, without updating the image, once I post it, the image value is set to null. This is problem because, I don't want to keep changing the image or update the image anytime I want to change the title or author field. -
Delete user create from allauth social login
In the process of learning allauth social login, I am able to successfully register & log in a user using google provider. For trial and testing purposes I need to delete the logged-in user and re-register with the same google email. I deleted the social account, social account token, email for that user from the admin console, but when I try to login again for the same user with the same email it gives an error - An account already exists with this e-mail address I have also checked rest-auth/user but found nothing. How can I completely delete a social account and log in again with the same Email? Any helpful tips? -
How to call a Class´s method with a button on a web page - Django -python
im starting with django and iot and i've decided to start (for learning purposes) an app that connects to my sensors attached to my raspberry pi. The thing that im struggling is the next one: I've done a class for my DHT11 sensor (temperature and humidity), and i've declared all values and wrote a method, which gets and prints the values of the sensor, and made a page where i show all the properties of the object, like "asigned pin" or the "name" of it; all fine until here. this is the class: class DHT11(models.Model): dht_sensor = Adafruit_DHT.DHT11 pin = IntegerField() status = BooleanField(default=False) name = CharField(max_length=15) humidity = IntegerField(default=0) temperature = IntegerField(default=0) def read_values(self): self.humidity, self.temperature = Adafruit_DHT.read(self.dht_sensor, self.pin) if self.humidity is not 0 and self.temperature is not 0: self.status = True else: self.status = False time.sleep(delay) print(self.temperature) print(self.humidity) The issue is that, in the same page where i show the properties of the object, id like to create a button, and with it call the "read_values" method of the object, and then show the values of temperature and humidity in the webpage that the method returns. ¿how do i do this?, do i need websockets? Here is an … -
How to Connect a Django Model with ManyToMany Relationship?
I am making an app that is pretty much similar to google classroom in django. I have a Course model and an assignment model, and I want to connect an assignment to the specified course. These are my models class Assignment(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) name = models.CharField(max_length=100) date_created = models.DateTimeField(default=timezone.now) class Course(models.Model): title = models.CharField(max_length=100) subject = models.CharField(max_length=100) image = models.ImageField(default='no_course_image.jpg', upload_to='course_images') owner = models.ForeignKey(User, on_delete=models.CASCADE) students_invited = models.ManyToManyField(User, null=True, blank=True) assignments = models.ManyToManyField(Assignment, null=True, blank=True) date_published = models.DateTimeField(default=timezone.now) class Meta: verbose_name_plural = 'Course' ordering = ['-date_published'] def __str__(self): return '{} - {}'.format(self.title, self.owner) But i am getting an error when I specify the course field in the assignment model with the ForeignKey! Could you please help me with how to connect the assignment to the Course model? Thank you -
How to create a nested DRF serializer with a UUID PrimaryKeyRelatedField?
I've simplified/minimised the example here (removed class meta which specifies model and all fields, removed some other explicitfields) but it matches the use case and replicates the behaviour being observed. class MainSerializer(ModelSerializer): a = ASerializer(required=False, many=True) def create(self, validated_data): a_data = validated_data.pop("a", None) main_instance = super().create(validated_data) if a_data is None: return main_instance for a in a_data: a["main_relation"] = main_instance a_serializer = ASerializer(data=a, many=True) a_saved = None if a_serializer.is_valid(): a_serializer.save() a_saved = a_serializer.data else: a_saved = a_serializer.errors return { **self.data, "a": a_saved.data() } class ASerializer(ModelSerializer): main_relation = PrimaryKeyRelatedField(queryset=ModelB.objects.all(), required=False, allow_null=True, default=None) The MainSerializer#create ends up throwing an error in the PrimaryKeyRelatedField#to_representation where it says the string representation of main_instance has no attribute pk, but when running through the debugger, the instance definitely has both the pk and uid attribute, and both are the same value as expected. So what's going wrong? Side question: if instead of returning the dictionary, and returning main_instance in both cases, will the viewset return the full MainSerializer#data representation of the instance (the nested a relationship included as per it's serializer)? And if the nested serializers have errors, will they come through in that data? Or would something like this require an extension of the drf functionality? -
How to make this very complicated query from three connected models with Django ORM?
Good day, everyone. Hope you're doing well. I'm a Django newbie, trying to learn the basics of RESTful development while helping in a small app project. We currently want some of our models to update accordingly based on the data we submit to them, by using the Django ORM and the fields that some of them share wih OneToMany relationsips. Currently, there's a really difficult query that I must do for one of my fields to update automatically given that filter. First, let me explain the models. This are not real, but a doppleganger that should work the same: First we have a Report model that is a teacher's report of a student: class Report(models.Model): status = models.CharField( max_length=32, choices=Statuses.choices, default=Statuses.created,) student = models.ForeignKey( Student, on_delete=models.CASCADE, related_name='reports', ) headroom_teacher = models.ForeignKey( TeacherStaff, on_delete=models.CASCADE,) # Various dates results_date = models.DateTimeField(null=True, blank=True) report_created = models.DateTimeField(null=True, blank=True) . #Other fields that don't matter Here we have two related models, which are student and headroom_teacher. It's not necessary to show their models, but their relationship with the next two models is really important. We also have an Exams model: class Exams(models.Model): student = models.ForeignKey( student, on_delete=models.CASCADE, related_name='appointments',) headroom_teacher = models.ForeignKey( TeacherStaff, on_delete=models.CASCADE,) # Various … -
How I get obj from parent model in Django Admin to put in html template
Here is my code where I generate a PDF file, (like an invoice), but I can't retrieve the fields from the admin.TabularInline. In my model.py I have to class: Sale and SaleItems,and in admin.py I have : class SaleItemsInLine(admin.TabularInline): model = SaleItems extra = 1 readonly_fields = ('total', ) formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'100%'})}, } @admin.register(Sale) class SaleAdmin(DjangoObjectActions, admin.ModelAdmin): fields = ( ('order', 'created', 'due_date'), ('profile'), ('pay_method', 'tax_card'), ('therapist' ,'activity',), ('notes'), ('totals'), ('pay', 'payOne','payTwo'), ('subtotal', 'status'), ) readonly_fields = ('created', 'totals', 'order','subtotal', 'status', 'tax_card') search_fields = ['profile__name', 'profile__cpf', 'profile__phone', 'activity', ] autocomplete_fields = ('profile',) list_display = ('profile', 'order', 'created', 'due_date', 'totals', 'status') inlines = [SaleItemsInLine] formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'30'})}, models.TextField: {'widget': Textarea(attrs={'rows':4, 'cols':100})}, } def generate_pdf(self, request, obj): html_string = render_to_string('sales/invoice.html', {'obj': obj}) html = HTML(string=html_string, base_url=request.build_absolute_uri()) html.write_pdf(target='/tmp/{}.pdf'.format(obj), presentational_hints=True); fs = FileSystemStorage('/tmp') with fs.open('{}.pdf'.format(obj)) as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'filename="{}.pdf"'.format(obj) return response return response I get fields from Sale with {{ obj.name }}, {{ obj.created}}, etc... How I get the fields from SaleItems(TabulaInline) ??? -
How to search any of a set of fields spanning multiple tables and show a join of those fields on the results page in Django
I have a set of fields spanning 7 tables that I want to display as a consolidated search results table. (Not sure if it matters, but the relationships between the tables are mostly reverse relationships (except 1)). For illustrative purposes, here is the table hierarchy (where each subtable record has a link to the parent table): Study (1 field) Animal (4 fields) Sample (1 field) -> Tissue (one field - the only forward relationship) MSRun (0 fields) PeakGroup (3 fields) PeakData (3 fields) Each table (Except MSRun) has at least 1 field displayed (and searchable) in the results output (presented in table format). I want the user to be able to search any of those fields and I want only one view function and one results template (in order to reduce the overhead of maintaining multiple identically-appearing result pages when the format is changed (which I expect to happen)). The joined results should only contain values matching whatever the search field was. E.g. If they search for Animal 1, that column would have only '1' in it, along with all other related fields. Worst case, the results table would have roughly 2.2k rows from the largest Study. (Note, 4 of … -
Django not getting path not matching
I am trying to make a certain url on my localhost show "Alex!" when it is entered in. For some reason I am getting this error: "Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, sauce, didn’t match any of these." The app name is "main" Here is my code: main.urls from django.urls import path from . import views urlpatterns = [ path('sauce/', views.index, name='index'), ] main.views from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Alex!") mysite.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('sauce/', include('main.urls')), path('admin/', admin.site.urls), ] I also tried doing this but with the homepage and not "sauce/" but that didn't work either. -
how I can use http post flutter with django
I want to make it without Django Reset Framework that is my code ''' from django.http import JsonResponse def index1(request): cursor.execute('select * from users where id = %s',[request.POST]) response = list(cursor.fetchall()) return JsonResponse(response, safe=False) ''' and when i use flutter http post put it gives me this Forbidden (CSRF cookie not set.): /index1 [04/Jun/2021 00:20:25] "POST /index1 HTTP/1.1" 403 2870 -
django ListView template post function using Q queries - too many values to unpack (expected 2)
I am using Django 3.2 I am creating a search form that will allow me to search for terms entered by user. I am using POST to post the search terms to the server. Here is my code: /path/to/views.py class FooSearchListView(ListView): model = Foo context_object_name = 'foos' template_name = 'path/to/foo_search_list.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) return context def post(self, request, *args, **kwargs): query_original = request.POST.get('search_terms', None) lookups = Q() if query_original: search_query = [x.strip() for x in query_original.lower().split(',')] for word in search_query: lookups = (lookups | Q(title__icontains=word) | Q(tags__name__icontains=word) | Q(caption__icontains=word) ) return Foo.objects.filter(lookups, is_public=True).distinct() # <- Barfs on this line /path/to/page.html <form action="{% url 'foo-search' %}" class="form-inline input-group col-md-4" method="post"> {% csrf_token %} <input id="search-terms" name="search_terms" class="form-control py-2 border-right-0 border" type="search" value="search"> <span class="input-group-append"> <button class="btn btn-outline-secondary border-left-0 border" type="submit"> <i class="fa fa-search"></i> </button> </span> </form> /path/to/urls.py # ... path('foos/search/', FooSearchListView.as_view(), name='foo-search'), # ... What is causing this error - and how do I fix it?