Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'author_details' with arguments '('',)' not found. 1 pattern(s) tried: ['author_details/(?P<auth_id>[^/]+)/\\Z']
I'm new to python and currently developing a practice app similar to Goodreads just to test and challenge myself. I have reached the part where I created three pages one with a simple list of books with a link to book details where there is a link to the author profile. The link between the book title link and the book details page works--but when I click on the author link on the book details page it gives me an error Reverse for 'author_details' with arguments '('',)' not found. 1 patern(s) tried: ['author_details/(?P<auth_id>[^/]+)/\\Z'] Here is my code. views.py from django.shortcuts import render from .models import Book from .models import BookAuthor from .models import BookGenre def authors_database(request): authors_database = BookAuthor.objects.all() return render(request,'authors_database.html',{ 'authors_database':authors_database }) def book_details(request,book_id): book_details = Book.objects.get(pk=book_id) return render(request,'book_details.html',{ 'book_details':book_details }) def author_details(self,auth_id): author_details = BookAuthor.objects.get(pk=auth_id) return render(request,'author_details.html',{ 'author_details':author_details }) def index(request): return render(request,'index.html',{ }) def discover_books_list(request): discover_books_list = Book.objects.all() return render(request,'discover_books_list.html',{ 'discover_books_list':discover_books_list }) book_details.html {% extends 'layout.html' %} {% block body %} <div class="container"> <div class="row"> <div class="col-md-4"> {% if book_details.book_cover_image %} <img src="{{book_details.book_cover_image.url}}" height="480" width="300" class="img-responsive"> {% endif %}<br> </div> <div class="col-md-8"> <h3>{{book_details}}</h3> <hr> <strong>By: </strong><a href="{% url 'author_details' auth.id %}">{{book_details.book_author}}</a> <br> <strong>Publication date:</strong> {{book_details.book_publication_date}}<br> <strong>In:</strong> {% … -
Serving sveltekit dev under django
I am building a project and I am trying to use sveltekit as front-end and Django as back-end. I am using gunicorn to serve Django and nginx as web-server that proxies to gunicorn. I want to serve sveltekit dev server under Django so that I don't have to add CORS and tweak settings.py to use different settings for production and development. Instead of developing front-end under http://localhost:3000, I want to access it like http://some-project.dev/app which points to Django. Is this possible? -
Contact form on a users personal site that posts to my Django DB?
I am wondering if it is possible to provide users of my django website a copyable HTML form element to put on their own personal website that actually POSTs to my Django database? The idea is to allow a User of my Django app to copy and paste an HTML Contact form into their own personal website with fields such as name, phone, email, notes which will all be fields of a model in my Django app. Basically when visitors of their website fill out the contact form I would like to post it to my Postgres DB in a model such as.. class Lead(models.Model): user = This would be the user on my Django app name... phone... email... notes... Is something that is possible or even safe to do? It would really be a big part of my project to allow for this lead collection. -
I want help in adding an event listener
I'm a django developer not good at javascript. I have a django template i really want to use Javascript for. i tried reading online for help but i'm not understanding I want to add an addEventlistener to this code below <div class="box-element hidden" id="request-info"> <button id="send-payment">Send request</button> Also, I want it to display a response when submitted. Response like "Request sent". Please I know about console.log, I don't want it in console.log. I know JS is really good at this. -
I can't get the notifications by i.d after saving it as a many to many field
I have previously figured out how to send and save notifications by many to many fields to send to users, now i can't specifically call the notifications by current user logged in i.d. Models.py class Notifications(models.Model): id=models.AutoField(primary_key=True) sent_to = models.ManyToManyField(CustomUser) message = models.TextField(null=True) message_reply = models.TextField(null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) The notifications_sent_to is the created table after I created the many to many save Views.py def add_notification(request): notifs = Notifications.objects.all() users = CustomUser.objects.filter(is_staff=True) if request.method == 'POST': form = AddNotifForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.message_reply = "none" instance.save() form.save_m2m() sent_to = form.cleaned_data.get('sent_to') messages.success(request, f'Message has been successfully sent .') return redirect('add_notif') else: form = AddNotifForm() context={ 'notifs' : notifs, 'form' : form, 'users' : users, } template_name ='main-admin/add-notif.html' return render(request, template_name, context) Forms.py class AddNotifForm(forms.ModelForm): sent_to = forms.ModelMultipleChoiceField( queryset=CustomUser.objects.filter(is_staff=True).exclude(is_superuser=True), widget=forms.CheckboxSelectMultiple, required=True) class Meta: model = Notifications fields = ['sent_to', 'message'] -
How to insert data from html form into MySQL database using python django
I have created an html form in add_appointment.html and have created database "hospital", table "appointment" in MySQL. I able to view values that I inserted into my database on another html page called view_appointment.html but I do not know how to take html form input from the "add_appointment.html" file and insert it into MySQL database. I searched for a solution everywhere, but I don't see people doing it in python Django, its just php everywhere and python but with flask, if you can help with some link I'll be grateful. (I'm a beginner, in college, doing a project for the first time. I figured it out somehow until now but got stuck here. My project is almost done except this one thing, I promise if someone helps me the day I become good enough I'll try my best to help others as well ) filename: add_appointment.html <!doctype html> <html lang="en"> <head><title>Add Appointment</title></head> <body> <div class="container"> <form id="form" class="form"> <div class="from-control"> <h1> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Add Appointment</h1> <div class="form-control"> <label for="username">Name</label> <input type="text" id="name" placeholder="Enter name"> <small>Error Message</small> </div> <div class="form-control"> <label for="email">Email</label> <input type="text" id="email" placeholder="Enter email"> <small>Error Message</small> </div> <div class="form-control"> <label for="id">ID</label> <input type="text" id="id" placeholder="Enter ID"> <small>Error Message</small> </div> … -
Cannot add "<Model: Model object (None)>": the value for field "field" is None
I am trying to save an object to my database while adding it to the Many to Many field of another object. I already tried many other solutions from here but nothing worked so far. Model: class SellerPost(models.Model): post_uuid = models.UUIDField(default=uuid.uuid4, editable=False) seller = models.ForeignKey("User", on_delete=models.CASCADE) text_content = models.TextField() comments = models.ManyToManyField("SellerPostComment", blank=True) class SellerPostComment(models.Model): comment_id = models.IntegerField(primary_key=True) post = models.ForeignKey(SellerPost, on_delete=models.CASCADE) addressed = models.ForeignKey("User", on_delete=models.CASCADE, null=False, related_name="seller_addressed_comment") commenter = models.ForeignKey("User", on_delete=models.CASCADE, null=False) content = models.TextField() View (i cut everything but the essential part that has sth to do with the error): post = request.POST["post"] post_obj = SellerPost.objects.get(post_uuid=post) comment = comment_form.save(commit=False) comment.addressed = user comment.commenter = request.user comment.post = post_obj comment.save() post_obj.comments.add(comment) return redirect(index) class PostCommentForm(forms.ModelForm): class Meta: model = SellerPostComment fields = ("content",) def save(self, commit=True): comment = super(PostCommentForm, self).save(commit=False) if commit: comment.save() return comment Error: Cannot add "<SellerPostComment: SellerPostComment object (None)>": the value for field "sellerpostcomment" is None The form is valid but it just won't save the comment to the M2M field of the post. Thanks in advance! -
Apache Only www.mydomain working . mydomain.com NOT working
I deployed my Django App to a linux server using apaches. When I write www.mydomainname.com it loading perfectly. When I enter mydomain.com It give me the Apache2 Ubuntu Default Page. So here are the ONLY command that I used into linux to deploy my app (To help to see if im missing somethings): apt-get update | apt-get install -y python3-pip | python3 -m pip install --upgrade pip | mkdir /var/www I modified the HOST into my django settings.py files: ALLOWED_HOSTS = ['www.mydomainname.com'] Than I installed apache with this command: apt-get install -y apache2 libapache2-mod-wsgi-py3 I created my config file with this command vim /etc/apache2/sites-available/mysite.conf and inserted this code: <VirtualHost *:80> ServerName www.mydomainname.com ErrorLog ${APACHE_LOG_DIR}/mysite-error.log CustomLog ${APACHE_LOG_DIR}/mysite-access.log combined WSGIDaemonProcess mysite processes=2 threads=25 python-path=/var/www/mysite WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py Alias /robots.txt /var/www/mysite/static/robots.txt Alias /favicon.ico /var/www/mysite/static/favicon.ico Alias /static/ /var/www/mysite/static/ Alias /static/ /var/www/mysite/media/ <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/mysite/static> Require all granted </Directory> <Directory /var/www/mysite/media> Require all granted </Directory> </VirtualHost> That it, there the only things that I did to deploy my web app to my server and it work fine when I go to wwww.mydomainname.com WHAT I TRIED TO DO TO MAKE THE mydomain.com working: Into my /etc/apache2/sites-available/mysite.conf … -
How to pass data of all input fields from one page to another using button in python django
I have a form on index.html and I want to pass data of all input fields of index.html to demo.html by using a button. Here is my code """ {% csrf_token %} <input type="text" id="xaxis" name="xaxis"><br><br> <input type="text" id="yaxis" name="yaxis"><br><br> <button type="submit"> SUBMIT </button> <button type="submit" name="saveChart" form="axisForm" value="save"> SAVE </button> -
Django auto submits form when page loads
I have this form inside my view if request.method == 'POST': button_form = TicketSolved(request.POST) if button_form.is_valid(): return redirect('https://google.com') I removed the content and added a redirect to google to test if its still broke. When the page loads, i automaticly get redirected to google.com, so the form will be submitted automaticly which is bad. It is a normal form in the HTML Template <form method="POST"> {% csrf_token %} {{ button_form }} <button type="submit"> How can I stop the automatic submission of the form when the page loads? Because the form will be actually a button. When someone clicks on the button (the form is valid), following code will be executet: obj.reopened_counter += 1 # if obj.reopened_counter > 5: # obj.ticket_waiting = True # obj.ticket_solved = False # # if obj.ticket_waiting == False and obj.ticket_solved == True: # obj.ticket_waiting = True # obj.ticket_solved = False # else: # obj.ticket_waiting = False # obj.ticket_solved = True # obj.save() So everytime someone clicks the button in the form, the counter will go +1. But even if the user just reloads the page, the counter will go up +1 because of this auto-submit-when-loading-view problem. -
How to use django-filter package for foreign key fields in Django?
Hi all! New in Django, and confused, help is appreciated! I've created a table, , thanks to a stackoverflow users, like: Organization Total amount of appeals Amount of written form appeals Amount of oral form appeals Organization 1 3 1 2 Organization 2 2 1 1 Have three models: class Organization(models.Model): organization_name = models.CharField(max_length=50) class AppealForm(models.Model): form_name = models.CharField(max_length=50) class Appeal(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE) applicant_name = models.CharField(max_length=150) appeal_date = models.DateField() Objects of Organization model: organization_name Organization 1 Organization 2 Objects of AppealForm model: form_name In written form In oral form Objects of Appeal model: organization appeal_form applicant_name Organization 1 In written form First and Last name Organization 1 In oral form First and Last name Organization 1 In oral form First and Last name Organization 2 In written form First and Last name Organization 2 In oral form First and Last name In the function of views.py file, I've created a query to render, like: from django.db.models import Count, Q organizations = Organization.objects.annotate( ).annotate( total=Count('appeal'), total_written=Count('appeal', filter=Q(appeal__appeal_form__form_name='in written form')), total_oral=Count('appeal', filter=Q('appeal__appeal_form__form_name='in oral form')) ) And now I want to filter table contents by AppealForm model and date of appeals (appeal_date field of Appeal model). Case: … -
'ProfileForm' object has no attribute 'user'
I'm learning Django. I have a model Profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=60) country = models.CharField(max_length=60) skillstolearn = models.TextField() skillstoteach = models.TextField() description = models.TextField() def __str__(self): return self.user.username And a form ProfileForm: class ProfileForm(ModelForm): class Meta: model = Profile fields = ['user', 'city', 'country', 'skillstolearn', 'skillstoteach', 'description'] I'm trying to use the view below... def profileupdate(request): profile = ProfileForm(request.POST) current = Profile.objects.get(user=profile.user.username) print(current) if profile.is_valid(): print('is valid') else: print('is not valid') return redirect('/thecode/userpage') ...to figure out if a user already exists, because I want to use the same form for both creating and updating. I get the error message "'ProfileForm' object has no attribute 'user'". How do I get the result for user that has been sent in the form? -
GCP: google app engine flexible + django 4.0.1 problem on deploy
I'm trying to deploy my Django 4.0.1 application to Google App Engine. But I'm receiving an error: Could not find a version that satisfies the requirement Django==4.0.1. On a localhost the app works fine. The same error I have with asgiref==3.5.0 The full text of this error: ERROR: Could not find a version that satisfies the requirement Django==4.0.1 (from -r requirements.txt (line 6)) (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1. 6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8 .2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1. 9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, … -
Can someone help? Sending notifications to all users or some users in django forms
I want to send a single notification message to multiple users or all users. I have tried many to many fields but the sent to id won't save the i.d's of the users that i have sent the message to. Models.py class Notifications(models.Model): id=models.AutoField(primary_key=True) sent_to = models.ManyToManyField(CustomUser) message = models.TextField(null=True) message_reply = models.TextField(null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) Views.py def add_notification(request): notifs = Notifications.objects.all() users = CustomUser.objects.filter(is_staff=True) if request.method == 'POST': form = AddNotifForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.message_reply = "none" instance.save() sent_to = form.cleaned_data.get('sent_to') messages.success(request, f'Message has been successfully sent .') return redirect('add_notif') else: form = AddNotifForm() context={ 'notifs' : notifs, 'form' : form, 'users' : users, } template_name ='main-admin/add-notif.html' return render(request, template_name, context) Forms.py class AddNotifForm(forms.ModelForm): sent_to = forms.ModelMultipleChoiceField( queryset=CustomUser.objects.filter(is_staff=True).exclude(is_superuser=True), widget=forms.CheckboxSelectMultiple, required=True) class Meta: model = Notifications fields = ['sent_to', 'message'] -
Django - export one txt file per row to local drive
I'm stuck with this as I can't find any relevant tutorials online. I would like to export all of the data in a model to the txt file format {actually xml but I think that's besides the point} where each row in the model is a seperate file and saved to a relative local path to the database with the folder and filenames for each being derived from two fields in the model I also need these to replace any existing files of the same name Where would I start? All I can do currently is export a txt file with all records together as a downloadable attachment. I currently have this working in Excel, but I want to cut the Excel step out. Here's what the Excel macro looks like: Sub export_misc() Dim wb As Workbook, ws As Worksheet Dim tags, ar, t Dim iLastRow As Long, r As Long, n As Long Dim c As Integer, i As Integer, k As Integer Dim sFolder As String, sFile As String, s As String Dim fso, ts Set fso = CreateObject("Scripting.FilesystemObject") tags = Array("plot:78", "dateadded:79", "title:80", "year:81", _ "mpaa:83", "releasedate:85", "genre:380", "studio:86", ":87", ":88") Set wb = ThisWorkbook Set ws … -
django-import-export, importing ManyToMany from XLSX
For my current project I need to import data from excelsheets format .xlsx to the django-admin. I'm struggling with the many2many relations that I have in my models. The importing feature just doesn't recognize the many2many fields and imports only the remaining fields (normal and foreignkey). Same goes for exporting, all fields except the many2many get exported into a excelsheet, although I dont need this feature, just tested it. For better understanding the code snippets from my models.py, admin.py, resources.py and widgets.py. I tried the default many2many widget -> in the TeacherResource in resources.py and I also tired overriding the default m2m widget -> StudyfieldWidget in widgets.py models.py class Translation(models.Model): de = models.TextField(unique=True) en = models.TextField(unique=True) def __str__(self): return self.de class Studyfield(models.Model): degree = models.CharField(max_length=50) title = models.ForeignKey("Translation", on_delete=models.CASCADE, related_name="+") def __str__(self): return self.title class Course(models.Model): number = models.CharField(max_length=50) title = models.ForeignKey("Translation", on_delete=models.CASCADE, related_name="+") studyfields = models.ManyToManyField("Studyfield", related_name="course", blank=True) def __str__(self): return self.title class Teacher(models.Model): name = models.CharField(max_length=50, blank=True) studyfields = models.ManyToManyField("Studyfield", related_name="teacher", blank=True) courses = models.ManyToManyField("Course", related_name="teacher", blank=True) def __str__(self): return self.name admin.py @admin.register(Translation) class TranslationAdmin(ImportExportModelAdmin): resource_class = TranslationResource ordering = ('id',) formats = [base_formats.XLSX] @admin.register(Studyfield) class StudyfieldAdmin(ImportExportModelAdmin): resource_class = StudyfieldResource ordering = ('id',) formats = [base_formats.XLSX] @admin.register(Course) class … -
Django Many to Many - polymorphic
In a Django application, I have three models: Service Product AppliedTax I want to create a many-to-many relationship between Service and AppliedTax and between Product and AppliedTax. Normally I would have an intermediate model (i.e. AppliedTaxTaxable) with three fields (applied_tax_id, taxable_type and taxable_id) and taxable_type + taxable_id would be a composite foreign key for each related model with taxable_type having as value the name of the related model (Service or Product in my case) and the taxable_id field the id of the related record of the respective model. I understand how to make it work with raw queries, but Is there a "Django" way to do that with a ManyToMany relationship? So far I had no luck with that. I don't have much experience with Django, but I hope there is a way to do that without using raw queries. Help :) -
Django error: Cannot assign must be an instance
Complete Error: ValueError at /dashboard/user/ticket/1/ Cannot assign "1": "TicketMessages.ticket" must be a "Ticket" instance. Request Method: POST Request URL: http://localhost:8000/dashboard/user/ticket/1/ Django Version: 4.0.1 Exception Type: ValueError Exception Value: Cannot assign "1": "TicketMessages.ticket" must be a "Ticket" instance. models.py class Ticket(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) description = models.TextField() creator_adress = models.GenericIPAddressField(null=True) start_date = models.DateTimeField(default=timezone.now) ... def __str__(self): return str(self.id) class TicketMessages(models.Model): ticket = models.ForeignKey( Ticket, default=None, null=True, on_delete=models.CASCADE, ) admin_message = models.CharField(max_length=200) user_message = models.CharField(max_length=200) views.py def ticket_system_view(request, id): obj = Ticket.objects.get(id=id) if request.method == 'POST': user_form = TicketMessagesForm( request.POST, instance=TicketMessages(ticket=id)) if user_form.is_valid(): form_save = user_form.save(commit=False) form_save.ticket = obj.id form_save.save() else: user_form = TicketMessagesForm() return render(request, 'ticket-system.html', {'obj': obj, 'user_form': user_form}) Sense of the code: A ticket can be created, multiple messages can be assigned to the ticket. The created message (ticket_system_view) is then assigned to the respective ticket. It says the instance= has to be Ticket but then I would create a new Ticket? ^^ -
Q: Python Django Docker - Unknown server host 'db' error when trying to make a super user
I am trying to use the command python manage.py createsuperuser and docker exec -it veganetwork-db-1 python manage.py createsuperuser to add myself as a superuser to my microservices project, however when I try to run both of these commands I get Unknown server host 'db' in my Windows Powershell, here is the entire error: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/usr/local/lib/python3.9/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.9/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1146, "Table 'veganetwork.auth_user' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 100, in handle default_username = get_default_username() File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/management/__init__.py", line 140, in get_default_username auth_app.User._default_manager.get(username=default_username) File "/usr/local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return … -
How to represent a model with some data django
I have a model and it contains a foreign key I want when I call foreign key like this Entry.customer not to give me the id but the first name and last name. So I don't want every time to concate first name and last name but by default to take that Entry.customer.first_name + ' ' + Entry.customer.last_name -> Entry.customer How can I achieve this? -
Mustn't end this function in here?
def createRoom(request): form = RoomForm() if request.method == 'POST': form = RoomForm(request.POST) if form.is_valid(): ***return redirect('home')*** #In here form.save() context = {'form' : form} return render(request, 'base/room_form.html', context) To my information, when python see a return in a function, the function is ending there. But in this code piece, python entering the if statement and applying the return command but after that, whereas python saw the return, function isn't ending . After the if statement, python, applying the return in the following code too. How can it be possible? Can anyone explain this please? -
how to filter objects by a specific choice
I have model like this: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) is_approved = models.CharField(max_length=64, choices=(('0', 'yes'), ('1', 'no')), blank=True) is_interviewed = models.BooleanField(default=False) how can I filter this model by is_approved field which is a choicefield? I wrote this line but doesnt work approved = ScientificInfo.objects.filter(is_approved__in='0').all() -
Represent string a model in django
I have a model and it contains a foreign key I want when I call foreign key like this Entry.foreignkey not to give me the id of that but some other data. How can I achieve this? -
How to set a timer inside the get request of an APIView?
I am trying to build a timer inside a get method in a DRF View. I have created the timer method inside the GameViewController class and what I am trying to achieve is that a every minute (5 times in a row) a resource object is shown to the user through the get request and a game round object is created. My View works at the moment, however the timer doesn't seem to be doing anything. I know this isn't exactly how things are done in django but this is how I need to do it for my game API for game logic purposes. How can I make the timer work? Do I need to use something like request.time or such? Thanks in advance. views.py class GameViewController: def timer(self): """Start a new timer as soon as a gameround has been started/created""" start_time = datetime.now() elapsed_time = None if start_time is not None: elapsed_time = time.perf_counter() """Stop the timer, and return the elapsed time""" if start_time is None: elapsed_time = time.perf_counter() - start_time return elapsed_time ... class GameView(APIView): def get(self, request, *args, **kwargs): ... round_number = gametype.rounds time = controller.timer() while round_number != 0: if time >= 1: random_resource = Resource.objects.all().order_by('?').first() … -
'str' object has no attribute '_encode_json'
I've been writing a test with RequestFactory to test one of my views, with the following code: class ViewTestCase(TestCase): @classmethod def setUp(self): self.factory = RequestFactory self.user = User.objects.create_user( first_name='tester', username='test1', password='123', email='testuser@something.com' ) def test_room_creation(self): payload = {"titlePlanning": "Test1","styleCards": "Fibonnaci","deck": ["1","2","3"]} request = self.factory.post('/room', payload) request.user = self.user response = BeginRoom.as_view()(request) self.assertEqual(response.status_code, 200) This is the data that I need to send to use POST: class BeginRoom(APIView): permissions_classes = (IsAuthenticated,) def post(self, request, format=None): data= self.request.data user = request.user name = data['titlePlanning'].strip() styleCards = data['styleCards'] cards = data['deck'] My problem is that whenever I run my tests I get the following error: data = self._encode_json({} if data is None else data, content_type) AttributeError: 'str' object has no attribute '_encode_json' What should I do? I'm lost from here and can't find anything related. Any help is appreciated!