Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I edit django model object data and save it to the database using JavaScript on the front end
For some context, I am creating a videogame on the web that needs a backend to store player names and record their score. Since I am quite comfortable with Python, I used the Django framework for my backend. The problem I encounter, however, is that I do not know how to edit the instance of the player model object I am passing into my HTML file via my views.py file to store/update its score. Here is the relevant function for my views.py file: def homepageview(request): form = PlayerForm(request.POST or None) if form.is_valid(): player = form.cleaned_data form.save() form = PlayerForm() for object in PlayerInfo.objects.all(): if object.name == player.get('name'): player = object break # I am looping through because there may be multiple people on the webpage playing the game so the current player isn't necessarily the most recent player context = { 'player':player } return render(request,'gamescreen/game.html',context) #once the form is valid, you can now actually play the game context = { 'form':form, } return render(request,'gamescreen/homepage.html',context) Here is the relevant portion of my 'gamescreen/game.html' file: <script> let player = "{{ player }}";//this is the player object passed in from views.py //how do I update its score and save it to my database … -
How to add bootstrap to Django Form,py?
I want to add bootstrap style to my radio buttons however I do not know how to do this. This is my form: class GenderForm(forms.ModelForm): CHOICES=[('Male','0'),('Female','1')] Gender = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) class Meta: model = Data fields = ['Gender'] I am calling the form as follows: <form action="{% url 'gender'%}" method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Gender</legend> {{ Gen_form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Confirm</button> </div> --> Thank you for any help in advance -
Can't install django-keyboard-shortcuts
I am getting this error when I try to install Django-keyboard-shortcuts in my virtualenv using pip ERROR: Command errored out with exit status 1: command: 'C:\Users\Rauf\Desktop\Dev\ProjectS\Scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Rauf\\AppData\\Local\\Temp\\pip-install-6s9pinah\\django-keyboard-shortcuts\\setup.py'"'"'; __file__='"'"'C:\\Users\\Rauf\\AppData\\Local\\Temp\\pip-install-6s9pinah\\django-keyboard-shortcuts\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Rauf\AppData\Local\Temp\pip-pip-egg-info-qwysmd20' cwd: C:\Users\Rauf\AppData\Local\Temp\pip-install-6s9pinah\django-keyboard-shortcuts\ Complete output (9 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Rauf\AppData\Local\Temp\pip-install-6s9pinah\django-keyboard-shortcuts\setup.py", line 121, in <module> long_description=read('README.rst'), File "C:\Users\Rauf\AppData\Local\Temp\pip-install-6s9pinah\django-keyboard-shortcuts\setup.py", line 12, in read return codecs.open(os.path.join(os.path.dirname(__file__), *parts)).read() File "c:\users\rauf\appdata\local\programs\python\python38-32\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 8439: character maps to <undefined> ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I have tried using admin powershell and I'm not sure why Im getting the error Thank you for the help -
How do I annotate multiple reverse fields with filters and all?
I have "Product", "OrderItem" and "Stock". I would like the fastest query to determine the stock on hand and the total order quantity for each "Product". I assumed it would be done like this: qs = ( Product.objects.all() .prefetch_related( Prefetch( "stock", queryset=Stock.objects.filter(timestamp__lte=timezone.now()), ), Prefetch("ordered_items", queryset=OrderItem.objects.all(),), ) .annotate( total_on_hand=Sum("stock__quantity"), total_allocated=Sum("ordered_items__quantity_ordered"), ) .order_by("id") ) But this returns "null" for both total_on_hand and total_allocated for all items: -
Error sending emails through form in Django
Bit of a rudimentary Django question. I would like to have a form that asks a user for their name and message and then sends this information to an email (more like a contact form). This is what I have in my views.py: def assignmentSubs(request): form = AssignmentSubs() subject = 'Assignment submission: {}'.format(form.cleaned_data['assignment'] from_email = 'xxx@tgmail.com' message = 'Hi, Please note that {} has submitted an assignment for the {} section. We will reach out to you with more detail regarding this submission'.format(form.cleaned_data['link'],form.cleaned_data['assignment']) send_mail(subject, message, from_email,['xxx@gmail.com','xxx2@gmail.com'], fail_silently=False) forms.py class AssignmentSubs(forms.Form): assignment = forms.CharField(required=True) link = forms.CharField(required=True) and the html with the form <form method="post" action="/" id="form" class="validate"> {% csrf_token %} <div class="form-field"> {{form.assignment}} </div> <div class="form-field"> {{form.link}} </div> <div class="form-field"> <label for=""></label> <input type="submit" value="Submit Assignment" /> </div> </form> and the css: <style> * { box-sizing: border-box; margin: 0; padding: 0; } #form { max-width: 700px; padding: 2rem; box-sizing: border-box; } .form-field { display: flex; margin: 0 0 1rem 0; } label, input { width: 70%; padding: 0.5rem; box-sizing: border-box; justify-content: space-between; font-size: 1.1rem; } label { text-align: right; width: 30%; } input { border: 2px solid #aaa; border-radius: 2px; } </style> This is a two fold problem, I cannot … -
Calendar in django admin
I am creating an hairdresser website using Django. I have a booking system in order to make an appointment for a date and an hour. When I fill my booking form and click on the book button, I want to have in the admin, a calendar displaying every appointments for each dates. I want to know how I can use a calendar in the admin and linked it with the Booking table in the model.py: class Booking(models.Model): firstNameUser = models.CharField(max_length=50) nameUser = models.CharField(max_length=50) email = models.EmailField(max_length=254, null = True) telephone = models.CharField(max_length=14, null = True) service= models.ForeignKey(Service, related_name ="reservation_service", on_delete = models.PROTECT) date = models.DateTimeField() Thank you for your answers. -
Weasyprint PDF outputs on local and in development have different text scale
I'm using weasyprint to create PDF contracts which should be electronically signed. I need to add form fields to exact location on PDF where signatures should appear after I generate PDF. But, I have an issue. I have created everything on local, adding signature form fields to exact location where signature should be,and it looks great. But, after I pull it on dev server I noticed agreement is not in scale with one on local server. Example one (image above), you can see scale is different. On inspection I see scaleX is different (on dev slightly larger - image above) Example two (longer paragraphs span on more lines, inserted signature fields are on wrong position because of longer paragraphs, taking more lines - image above) Question: Can I fix this somewhere in weasyprint code so render/output is in scale? If I can I would love doing it. If I can't I will use page breaks to move signature fields somewhere they will be fixed. Any advice will be appreciated. -
How to generate thumbnail from videos we upload in django? it is for both embed videos and direct video upload
trying really hard to generate thumbnail from videos we upload in django, suggest me the best third party library which could help me to extract image thumbnail from video that we upload -
Django DetailView with prefetch_related from django_braces not working
I have the following code, I am trying to display the category name and the banner image to which the currently displayed company belongs to. However, I am not getting the query behavior I expect, django is hitting the db twice once for banner_image and then for category name. I have a many to many between companies and categories it can belong to. Only showing the parts of the model that are relevant. I a using PrefetchRelatedMixin from django-braces. models.py class Category(ModelBase): name = models.CharField(max_length=100) objects = CategoryManager() class Company(ModelBase): name = models.CharField(max_length=500) categories = models.ManyToManyField(Category) objects = CompanyManager() views.py class CompanyDetailView(PrefetchRelatedMixin, DetailView): model = Company prefetch_related = ['categories'] template_name = 'company-detail.html' company-detail.html <section class="banner mb-5"> <img src="{{ company.categories.first.banner_image.url }}" alt="{{ company.categories.first.name }}"> <div class="container text-center overlapping-text"> <h1 class="pt-5 fw-300">{{ company.name }}</h1> </div> </section> Thanks for your help! -
Django Return a Download and Redirect to a Different page
I am setting up a site where as a user I can assign something to someone and anytime it is assigned a new PDF document is created. Currently the user would just go to the users account page, click on the assign page, and fill out the form. Once this form is submitted a document(pdf) is created and saved with the model that is created and the user is redirected to the account page they were just at. Here they can click on what has been assigned to download the document that was created. However, I want to have it be that once submitted they get redirected back to the account page and also starts the download. I was thinking of just making a get request using requests but I read that is not a good approach. Below is the code I have for the download as well as the code for the view submit. Download View @login_required def attendance_download(request, employee_id, attendance_id): employee = Employee.objects.get(employee_id=employee_id) attendance = Attendance.objects.get(id=attendance_id) pretty_filename = f'{employee.first_name} {employee.last_name} Attendance Point.pdf' try: with open(attendance.document.path, 'rb') as f: response = HttpResponse(f, content_type='application/vnd.ms-excel') response['Content-Disposition'] = f'attachment;filename="{pretty_filename}"' return response except: messages.add_message(request, messages.ERROR, 'No File to Download') return redirect('employee-account', employee_id) Form … -
Two responses in Django Rest Framework
I know that maybe I am asking something imposible, but I have to try, maybe there is some way to do this. I have a petition to my API made in Django Rest Framework, from any language: PHP, Javascript, CURL, etc. I have two responses, one is a serializer: data = ChargeSerializer(charge).data return Response(data, status=status.HTTP_200_OK) And, if this Serializer or response is correct, I have to do other response with a zip file (I think that is this way): response = HttpResponse(full_zip_in_memory, content_type='application/x-zip') response['Content-Disposition'] = 'attachment; filename="etiquetas_%d.zip"'% nenvio filename="etiquetas_%d.zip"% nenvio return response I do not want to do mix a Zip file and JSON, because it is very hard for my server and it is impossible without convert the file in binary. Also, I would like to do it in a Celery Task, because I need to create the Zip, but maybe is not the best way for a response in an API. There is some way for do it in one request from Frontend and response, first one response, and second, other response? Thanks. -
Downloading files from server side script python
I have a python code which performs a GET request to a URL based on input and this is a file hosted on a URL, I am going to download this using this code: import urllib.request url = input() download_file = urllib.request.URLopener() file = download_file.retrieve('URL', 'Downloaded File') How would I look at implementing this code onto my website, I'm thinking Django? never used it but from my research, this looks like the way forward. Does this sound like the way to do it, could someone give me some guidance of where to looks within there docs or alternative methods. I assume I would have to host my script on a server and the input into the input box would be the input into the Python script and I would need to return the downloaded file to the user. Is that how it would be done? -
What is . get() function can do in python for others than dictionary?
There is a part in django @html_safe class BaseForm: --------------------------- @property def errors(self): """Return an ErrorDict for the data provided for the form.""" if self._errors is None: self.full_clean() return self._errors --------------------------- def non_field_errors(self): """ Return an ErrorList of errors that aren't associated with a particular field -- i.e., from Form.clean(). Return an empty ErrorList if there are none. """ return self.errors.get(NON FIELD ERRORS, self.error_class(error_class='nonfield')) I know get() works with dictionary. But I have seen mane time get() is working on class properties like here. -
Serialize objects with relationships to json format | Django
My models: class Exam(models.Model): name = models.CharField(max_length = 44, unique = True) course_class = models.OneToOneField('courses.Class', on_delete = models.CASCADE) created = models.DateTimeField(auto_now_add = True) class Meta: ordering = ['created'] def __str__(self): return self.name class ExamQuestion(models.Model): exam = models.ForeignKey(Exam, on_delete = models.CASCADE) title = models.CharField(max_length = 300, unique = True) created = models.DateTimeField(auto_now_add = True) multiple_choice = models.BooleanField(default = False) class Meta: ordering = ['created'] def __str__(self): return self.title class Reply(models.Model): exam_question = models.OneToOneField(ExamQuestion, on_delete = models.CASCADE) text = models.CharField(max_length = 200) def __str__(self): return self.text class Option(models.Model): exam_question = models.ForeignKey(ExamQuestion, on_delete = models.CASCADE) text = models.CharField(max_length = 200) is_correct = models.BooleanField() class Meta: unique_together = ['exam_question', 'is_correct'] def __str__(self): return self.text A ExamQuestion, can be related to a Reply, or to several Options. This is my view: @ajax_view def get_exam_question(request, json_data): exam = Exam.objects.get(id = json_data['exam_id']) data = serializers.serialize("json", exam.examquestion_set.all()) print(data) #for exam_question in exam.examquestion_set.all(): return JsonResponse() This is what prints the already serialized objects: [{"model": "exam_system.examquestion", "pk": 2, "fields": {"exam": 10, "title": "Khe!", "created": "2020-06-29T02:07:21.347Z", "multiple_choice": false}}, {"model": "exam_system.examquestion", "pk": 3, "fields": {"exam": 10, "title": "KKKKK", "created": "2020-06-29T02:14:53.057Z", "multiple_choice": false}}, {"model": "exam_system.examquestion", "pk": 4, "fields": {"exam": 10, "title": "1111111111111", "created": "2020-06-29T02:17:13.248Z", "multiple_choice": false}}] The only relationship that appears is with … -
Django on Azure
I have installed your setup at Azure: Python Django and Flask developer suit. I'm a novice at django. Read and listened to learning tools but not addresses specific steps for Azure deployment I’ve got my prototype (v1) Django code operational on my development server both on my laptop and the Azure VM from the install above. It’s working as expected. My problem is with its migration to a production server. Here’s what I’ve done: The python code was put up on GitHub I created an Application Service Plan (ASP) on Azure in the same resource group as the installed Django and the Neo4j database I'm querying I pushed the GitHub code over to the ASP. I can see it in the wwwroot folder I've tried many ways to deploy the code to a production server without success. The include using the Azure CLI webapp commands, gunicorn (not supported on my PC windows), etc. BUT, I still see the default APS webpage and not the intended one What step am I missing? I'm missing some basic concepts ... how does a deployed django look interms of directories, etc. Is Django/Flask the best tool kit for my planned solution for a web … -
Vue.js vs jQuery in DjangoApp
I am about to start to code a Django App. I did use jQuery by the past with no so much hassle. Big question is: is jQuery about to die now in 2020 and I should jump straight into Vue.js now? Are the two capable of the same things, especially asynchronous call? -
Django Admin - One to Many - How to make sure only one children has a boolean field selected
In django, I have the following models: class System(models.Model): name = models.CharField(max_length=200) """ ... many other fields, not useful for here ...""" # Would it make more sense to have the primary instance here ? class Instance(models.Model): name = models.CharField(max_length=200) url = models.UrlField(max_length=200) system = models.ForeignKey(System, on_delete=models.PROTECT) is_production = models.BooleanField() This data is managed using the admin. What I want is that when an instance of the system is marked as is_production, all other instances, for that system have their is_production field updated to False. Also, I am interested in how to best setup the admin for this case. I, will be using inlines for the edition/creation of instances. However, I am not sure about how to make sure each system can only have one instance in production. Should I use a dropdown on the System to select the production instance and filter using formfield_for_foreignkey? Use an admin action, something like: Mark as production ? Use signals after a save ? is there any other way I have not thought about ? -
TypeError : 'module' object is not callable: when I use login(request,user) method in Django?
I am trying do developed login form using Django in the views.py -
Getting error 'django.contrib.auth.models.User.DoesNotExist: User matching query does not exist'
A similar question has been asked before but after going through all of them I was not able to find any answer to fit my case. I am using Django's built-in authentication system to authenticate and log in a user. The user uses a log in form on index form and is supposed to be then redirected to a different url. However after I log in with a username and password that are both valid entries, I am not redirected to the next url as I should be, and I get this error: django.contrib.auth.models.User.DoesNotExist: User matching query does not exist. These are my import lines for authenticate, login, and then for User. from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User But I don't think the problem is there. It can't find the user but I don't know why that could be, because I am creating a username in the form and a password so it should be present. Here is my login code: def index(request): if request.method == 'POST': print("Received POST") form = LoginForm(request.POST) if form.is_valid(): print("FORM is Valid") # proceed with registration username, pwd = request.POST.get("username", None), request.POST.get("password", None) if not username or not pwd: print("nobody around … -
How to restrict website users from seeing other user profiles?
I created some users for my website in Django and i want each user to access only his own profile page . The template for the user profile page is fetched through a CBV Detail View called UserDetailView attached to a URL containing the user's and the page is loading only after authentication .( user logged in). So far so good. urls.py: from django.conf.urls import url from django.urls import path from basicapp import views from django.contrib.auth.decorators import login_required app_name='basicapp' urlpatterns = [ url(r'^$',views.index,name='index'), url(r'^user_list/',views.UserView.as_view(),name='user_list'), url(r'^course_list/',views.CourseView.as_view(),name='course_list'), url(r'^user_detail/(?P<pk>[-\w]+)/$',views.UserDetailView.as_view(),name='user_detail'), ] The problem is after I login and get the user detail page : If I manually change the <pk> in the URL I get other user profile pages loaded. I don't want that to happen . For ex, the URL for the logged in user profile is : http://127.0.0.1:8000/basicapp/user_detail/1/ With the user already logged in i manually change the URL to : http://127.0.0.1:8000/basicapp/user_detail/2/ and it works. It should retrict me or show me an error message I tried using LoginRequiredMixin views.py: from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.utils.decorators import method_decorator class UserDetailView(LoginRequiredMixin,DetailView): context_object_name='user_detail' model=models.User template_name='basicapp/user_detail.html' raise_exception = True # Raise exception when no access instead of redirect permission_denied_message = "This … -
User Deleting Models Without Permissions in Django
I am working on a project for a professor and have never used Django and Python before so I am pretty green. The professor has this working-ish app. He would like me to develop some authorization stuff. The App allows Users to create teams, upload papers, make categorize, etc. There are models for all these. I have created some test users and given them permissions to Create, read, and update models but NOT delete anything from the Admin DashBoard. However, when logging in with these users I can still delete items. How can this be? The view for these models has a "delete" button, but if I am a user that doesn't have permission to "delete team" from the admin dash, why can i delete? -
Django 'QuerySet' object has no attribute 'product' error
I want to add medicine to my cart from a medicine list. I created a view but when I click add button it gives this error: AttributeError at /cart/6/ 'QuerySet' object has no attribute 'product' I want that when a user click + button, medicine will be add users cart. Here are my codes. Please help me. cart/models.py class Cart(models.Model): user = models.TextField(User) product = models.OneToOneField(Medicine,primary_key=True, on_delete=models.CASCADE) total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) cart/views.py def update_cart(request, id): current_user = request.user cart = Cart.objects.filter(user=current_user) try: medicine = Medicine.objects.filter(id=id) except Medicine.DoesNotExist: pass except: pass if not medicine in cart.product.all: cart.product.add(medicine) else: cart.product.remove(medicine) return HttpResponseRedirect("/cart") medicines/models.py class Medicine(models.Model): medicine_name = models.CharField(max_length=100) medicine_info = RichTextField(verbose_name="Details") medicine_image = RichTextField(verbose_name="Image") medicine_code = models.CharField(max_length=100) medicine_qr = models.CharField(max_length=100) medicine_price = models.IntegerField() slug = models.SlugField(max_length=100, unique=True, editable=False) medlist.html <td> <a href="/cart/{{medicine.id}}" class="btn btn-sq-xs btn-success"> <i class="fa fa-plus fa-1x"></i><br/> </a> </td> -
Django Rest Framework problem in CreateAPIView
I have a project with Courses and Sections in it. I am building this project with django rest framework and i have the function that should create a section with 3 fields: course, title and creator. I want to understand how i can take a course slug from url and put it in course field, i mean don't pick course manually. How to implement that? models.py class CourseSections(models.Model): creator = models.ForeignKey(User,related_name='creator_sections',on_delete=models.CASCADE,null=True) title = models.CharField(max_length=50) course = models.OneToOneField(Course, related_name='course_section', on_delete=models.CASCADE,null=True) serializers.py class CourseSectionSerializer(serializers.ModelSerializer): class Meta: model = CourseSections fields = ['creator', 'title', 'course'] def create(self, validated_data): instance = self.Meta.model(**validated_data) request = self.context.get('request') if request and hasattr(request, 'user'): user = request.user instance.save() return instance views.py class SectionsCreateAPIView(CreateAPIView): queryset = CourseSections.objects.all() serializer_class = CourseSectionSerializer permission_classes = [IsAuthenticatedOrReadOnly, IsAdminOrReadOnly] lookup_field = 'slug' lookup_url_kwarg = 'course__slug' def perform_create(self, serializer): serializer.save(creator=self.request.user) urls.py url(r'^sections/(?P<course__slug>[-\w]+)/create/$', SectionsCreateAPIView.as_view(), name='create_sections'), -
Django on Gunicorn/Nginx - Stripe Webhooks Always Getting 400
Production Setup: Django v3.0.5 on Nginx / Gunicorn / Supervisor (i followed directions from here) (I don't think this is any issue but i am using dj-stripe for django/stripe integration) While on development (django's built-in HTTP server).. everything seems to work (i.e. stripe can send webhook events just fine)... however, on production, i get emails saying that Stripe can't reach my server. When I run curl -D - -d "user=user1&pass=abcd" -X POST https://my.server/stripe/webhook/ I get this response HTTP/1.1 400 Bad Request Server: nginx/1.15.9 (Ubuntu) Date: Thu, 18 Jun 2020 19:44:07 GMT Content-Type: text/html; charset=utf-8 Content-Length: 0 Connection: keep-alive X-Frame-Options: SAMEORIGIN Vary: Cookie However, non-webhook (i.e. visiting the website via browser) seems to work normally.. just webhooks. Any idea where this is going wrong? -
How can I verify old user passwod in forms.py - Django
I have a page where user can change their account password. I made a form for password validation, but I don't know how I can check if the password in field "old_password" is the real old password. class ChangePasswordForm(forms.ModelForm): password_old = forms.CharField(label = "", widget=forms.PasswordInput(attrs={'placeholder':'Type current password'})) password1 = forms.CharField(label = "", widget=forms.PasswordInput(attrs={'placeholder':'Type a new password'})) password2 = forms.CharField(label = "", widget=forms.PasswordInput(attrs={'placeholder':'Confirm password'})) class Meta: model = Users fields = ('password_old', 'password1', 'password2',) def clean_password1(self): password1 = self.cleaned_data.get('password1') try: validate_password(password1, self.instance) except forms.ValidationError as error: self.add_error('password1', error) return password1 def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords didn't match") return password2