Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use an extra ModelChoiceField on a ModelForm?
I am trying to add a ModelChoiceField to a ModelForm, but I keep getting a TypeError: type object argument after ** must be a mapping, not QuerySet. I feel like I implemented the modelchoicefield as in the docs, with a queryset argument. The form worked fine before I added the ModelChoiceField. forms.py from django import forms from events.models import Event, ExtraThing class EventForm(forms.ModelForm): extra_thing = forms.ModelChoiceField(queryset=ExtraThing.objects.all()) class Meta: model = Event fields = ('name', 'date', 'extra_thing') views.py from events.forms import EventForm def newevent(request): if request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): form.save() else: form = EventForm() return render(request, 'manage/event_form.html', {'form': form}) -
Frontend and backend validation synergy
I've created a register form validation on frontend and backend and I am checking both at the frontend and backend: whether the name and surname consist of letters only, whether the password contains numbers, uppercase and lowercase letters, whether the email is correctly saved. The interface informs about errors. My question is, since I check all the conditions on the frontend, should the backend also send error messages to the frontend? I mean both frontend and backend check data validation, but should the frontend react to backend error messages? It seems unnecessary for the backend to send information that f.e. the password is too short, since the frontend already does it. The backend should only make sure that f.e. the password length is appropriate. Second question: should I check on the backend side whether the checkbox regarding acceptance of the website regulations has been selected or whether the password and the repeated password are the same? -
Python/DJango 'django.db.utils.OperationalError: no such table' in Django Rest Framework (DRF)
I'm trying to create a POST API for users to vote on a given choice. But I keep getting the error below. What could be the problem? Thanks in advance! Internal Server Error: /polls/6/choices/19/vote/ Traceback (most recent call last): File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: main.vote_choice__old File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\models\base.py", line 879, in _do_insert return manager._insert([self], fields=fields, return_id=update_pk, File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ..... ..... File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: main.vote_choice__old [08/Aug/2021 17:09:09] "POST /polls/6/choices/19/vote/ HTTP/1.1" 500 193455 Here's the vote class in serializer.py: class VoteSerializer(serializers.ModelSerializer): class Meta: model = Vote fields = '__all__' Here's the CreateVote class in apiviews.py: class CreateVote(APIView): serializer_class = VoteSerializer def post(self, request, pk, choice_pk): voted_by = request.data.get("voted_by") data = {'choice': choice_pk, 'poll': pk, 'voted_by': voted_by} serializer = VoteSerializer(data=data) if serializer.is_valid(): vote = serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here's the URL Patterns code in urls.py: urlpatterns = [ path("polls/<int:pk>/choices/<int:choice_pk>/vote/", CreateVote.as_view(), name="create_vote"), ] And the models code looks like so in models.py: class Vote(models.Model): choice = models.ForeignKey(Choice, related_name='votes', on_delete=models.CASCADE) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) voted_by = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = ("poll", "voted_by") -
Page Not Found (404) Error in simple Django 2.2 application
I used the official Django documentation to create this code and I consistently get a 404 error when I put localhost:server/polls/ in the search bar. I followed the tutorial pretty much identically but it still doesn't seem to work. Anyone know a solution to get text displayed at localhost:server/polls/ or at localhost:server? polls/views.py: from django.shortcuts import render from django.http import HttpResponse def index(response): return HttpResponse('Polls') polls/urls.py: from django.urls import path from . import views urlpatterns =[ path('', views.index, name='index'), ] mysite/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), ] Error message: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn't match any of these. I have looked at lots of different potential solutions and none of them seem to work. Please let me know if you need more info/code, thanks -
Access to fetch at 'http://127.0.0.1:8000/blog/1' from origin 'http://localhost:3000' has been blocked by CORS policy
I'm trying to fetch some data from the Django Rest API. But browser throw cors policy error. let headersList = {Accept: '*/*'} fetch(url, { method: 'GET', headers: headersList, }) .then(function (response) { return response.json() }) .then(function (data) { console.log(data) }) Access to fetch at 'http://127.0.0.1:8000/blog/1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I also include cors-header in django api. CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True -
Pass data to modal querying data again in django?
I have an transaction list and its been looped to show in a table. In this, when user click on view a modal will be opened with extra information. How to pass the data to the modal, I know i can do this by making ajax request. But the thing is we have already have all the data from the for loop ? then why we need to do ajax again to get same request ? Ex: {% for data in transactions %} <tr class="nk-tb-item"> <td class="nk-tb-col"> <span>{{forloop.counter}}.</span> </td> <td> <a href="#tranxDetails" data-toggle="modal">View</a> </td> </tr> {% endfor %} As you see, we got all information from transactions and when user clicks on "View" - it opens the modal but how to send transactions of that particular data to the modal ? I have even tried using index on modal like <div class="modal fade" tabindex="-1" id="tranxDetails"> <div>{{transactions.0.amount}}</div> </div> But dont know how to replace the "0" with respective current index. Please suggest a way, am not doing any POST or GET on the modal - just want to show some extra information from "transactions" on the modal ( as the table can only show few columns adding the extras to the … -
Is there a way to know why i cant access my newly deployed website?
Ok so I recently deployed my Django app on Digital ocean and the app was fine and working normally. suddenly when i try to access the app using the server Ip address it doesn't allow me stating as follows:i cant embed a picture directly i am new here . i tried a vpn and it didnt work however my colleagues can access the server normally and use the app i am the only one that cant access it. i tried rebooting the server using sudo reboot and tried disabling firewall and nothing works. i am new to deploying apps so i need help and sorry if my question lacks information. -
RSA Encryption not supported - caching_sha2_password with django mysql and docker
im trying to connect Mysql with django using docker, and i get this error 2061, 'RSA Encryption not supported - caching_sha2_password plugin was built with GnuTLS support' i tried changing user and creating a database with // create a user // CREATE USER 'user'@'localhost' IDENTIFIED BY 'user'; GRANT ALL PRIVILEGES ON *.* TO 'user'@'localhost' WITH GRANT OPTION; CREATE USER 'user'@'%' IDENTIFIED BY 'user'; GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' WITH GRANT OPTION; // create a database // CREATE DATABASE user_db; BUT still the sqme error message in the settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'user_db', 'USER': 'user', 'PASSWORD': 'user', 'HOST': 'db', 'PORT': '3306', } } and in docker-compose: db: image: mysql:latest environment: MYSQL_DATABASE: 'user_db' MYSQL_USER: 'user' MYSQL_PASSWORD: user MYSQL_ROOT_PASSWORD: root volumes: - ./data/mysql/db:/var/lib/mysql ports: - 3306:3306 thank you for your help -
Internal Application error in Heroku app deployment
I have been trying to deploy this Python Django based Weather app on heroku. I have followed all the procedures exactly as mentioned for example created the proctile file and changed some things on settings.py including the allowed host. But still I can't figure out why this error is occurring for me. Please do help me to get this error fixed. I have also attached the screenshots. And at the same time I followed this tutorial down here. https://youtu.be/Q_YOYNiSVDY enter image description here enter image description here -
Django Oscar or e-com from scratch
I'm developing an e-commerce site with Django and REST framework. Products are books and other things that designed by user, and product creation parts are done. Now I want to add e-commerce parts, and found some frameworks like oscar and django-shop, but also encounter some opinions on them suggesting to do it from scratch since "after a while you customize it to some extent that you ask yourself why even I use this framework". Not a direct quote but you got the idea. My questions are: Considering the type of product what approach is better for me? (Frameworks or from scratch) Is there a significant difference in develop time between them? Because products are complex i assume there should be lot of customization needed in frameworks. I want to know considering these customization, using frameworks are still a lot faster? If you suggest to use a framework, which one would you recommend? -
The chained field in my django app is empty. I am using django smart select
Right now I'm practicing using Django smart select. However, the chained field dropdown list (country field in Location model) in Django-admin is empty. It doesn't load any objects unless I switch the show_all argument to True. You can find my models.py below. from django.db import models from smart_selects.db_fields import ChainedForeignKey # Create your models here. class Continent(models.Model): continent= models.CharField(max_length=200) def __str__(self): return self.continent class Country(models.Model): continent= models.ForeignKey(Continent, on_delete=models.CASCADE) country= models.CharField(max_length=200) def __str__(self): return self.country class Location(models.Model): continent= models.ForeignKey(Continent,on_delete=models.CASCADE) country= ChainedForeignKey(Country, chained_field='continent', chained_model_field='continent', show_all=False, auto_choose=True, null=True, blank=True) Django-admin screenshot (You can find that the country doesn't load any objects) -
html5sortable drag and drop not working on ajax load HTML
I was trying to add a draggable HTML list that loaded via AJAX request, it's not working here below the code for the draggable feature, I used html5sortable HTML template code <script src="{% static 'assets/javascripts/libraries/html5sortable.min.js' %}"></script> <script src="{% static 'assets/javascripts/main.js' %}"></script> <div class="card-body" id="item-container"> </div> JS code $.ajax({ URL: list_data_url, type: "POST", data: data, success: function (response) { if (response["success"] == true) { const parent = $("#item-container").empty(); // Added sortable DIV let item_html = '<div class="sortable">'; let total_price = 0; for (const item of items) { item_html += ` <a href="${details_url}"> <div class="item-wraper" style="background:${bk_color}; opacity:0.5;"> <div><strong>Items SL: </strong> Item Name</div> </div> </a>`; } item_html += "</div>"; parent.append(item_html); // Items Sortable sortable(".sortable"); } }}) -
Display Django models from database using for loop in HTML table
In my views.py I add all transactions from the database to the request context. I want to display the data in a dashboard table. How do I do this using a for loop? I can use the following to print out all data, but it doesn't fit into the table. {% for transaction in transactions %} {{transaction.date}} {{transaction.event}} {{transaction.total}} {% endfor %} The HTML code <div class="sales-boxes"> <div class="recent-sales box"> <div class="title">Transaction history</div> <div class="sales-details"> <ul class="details"> <li class="topic">Date</li> <li><a href="#">Date 1</a></li> <li><a href="#">Date 2</a></li> </ul> <ul class="details"> <li class="topic">Event</li> <li><a href="#">Event 1</a></li> <li><a href="#">Event 2</a></li> </ul> <ul class="details"> <li class="topic">Total</li> <li><a href="#">$1</a></li> <li><a href="#">$2</a></li> </ul> </div> <div class="button"> <a href="#">See All</a> </div> </div> My views.py code used to render the page from .models import Transaction def earner_dashboard(request): transactions = Transaction.objects.all() return render(request, 'dashboard.html', context={"transactions":transactions}) -
Detect which url a request came from in Django
In my Django project I have 2 different views that render pageA.html and pageB.html. In both pages there is a Next button, which when clicked is sending a form to the backend for additional processing followed by a redirect view C that renders pageC.html. When the requests arrived to view C is it possible for me to detect path that the view had gone through? That is I will like a way to see if the reqeusts originally came from view A or viewB. -
JavaScript quantity function is not working
I am a person who is studying JavaScript. Django is trying to modify the quantity, but the quantity button is not working. But I don't know why. Also, I have implemented the option so that information about the option appears when it is selected, and I hope the quantity will also appear when it appears. If you could tell me how to modify it, I'd really appreciate it. html <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option data-price="{{value.extra_cost}}"value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> <div id="selectOptionList" style="margin-top:10px; margin-left: 20px; margin-bottom: -10px;"> </div> </div> <body onload="init();"> <form name="form" method="get"> <input type=hidden name="sell_price" value="5500"> <input type="button" value=" - " onclick="del();"> <input type="text" name="amount" value="1" size="3" onchange="change();"> <input type="button" value=" + " onclick="add();"> <input type="text" name="sum" size="11" … -
How to get logged in user id for "default=" value in django?
How to get Logged In User id for model.py in Django? This is mymodel.py file: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(default=timezone.now) date_added = models.DateTimeField(default=timezone.now) c_user =models.ForeignKey(User, on_delete=models.CASCADE, default= ) def __str__(self): return self.title class Meta: ordering = ['-date_added'] How to get logged in user id for default= value in c_user ? -
Manage free and busy appointment in django
I'm looking for an efficient way to create appointments between teachers and students. I want teacher to be able of make their students know their availabilities : For example, A Teacher writes on the application that he is free on Monday from 8am to 9am. The Student wants an appointment with his teacher. The Student checks free time slots of his teacher and choose the appointment on Monday from 8am to 8.30am. A second Student want an appointment and the application have to show him only the free time of the Teacher from 8.30am to 10am on Monday and not from 8am to 8.30 because now this time slot is busy with the first student appointment. There are a Teacher class and a Student class. I'm thinking about creating a class of dailySchedule for the teacher with time hour slot boolean fields in which 0 means free and 1 means busy. When a student choose an appointment from 8am to 8.30am, the field slot_8_8h_30 equals to 1. Then, in a AppointmentBook class, the appointment is added. If the row corresponding to the appointment is deleted, the field slot_8_8h_30 come backs to 0. This is what I've done in Django : … -
Remove id field from djongo model
I want to get rid of the id field from every djongo model that inherits the Django default model. For example, the documents for ./manage.py createsuperuser (auth_user) should only have _id, not id -
How to Pythonically test whether a function is called with a certain argument in Python?
I've got a Django codebase which contains an endpoint. The endpoint does many things, and I now want to check whether the endpoint calls the function do_metadata_request (pasted below) with a specific token. def do_metadata_request(url_info, token): metadata_url = f"{settings.META_SERVER_BASE_URL}/{url_info['dossier']}" headers = {} if token: headers['Authorization'] = token return requests.get(metadata_url, headers=headers) So after some fiddling around I made the setup below. It works, but it does the actual test in a mocked function which I define outside the test itself. It just doesn't feel elegant or Pythonic at all. I'd rather do the assert inside the test, or at least define the mock_do_metadata_request within the test. Does anybody know a way to do this more elegantly? class MockResponse: def __init__(self, status_code, json_content=None, content=None, headers=None): self.status_code = status_code self.json_content = json_content self.content = content self.headers = headers def json(self): return self.json_content MOCK_TOKEN = "Bearer " + create_test_token([settings.EXTENDED_SCOPE]) def mock_do_metadata_request(url_info, token): assert token == MOCK_TOKEN return MockResponse( 200, json_content={ 'access': settings.ACCESS_RESTRICTED, 'documents': [{'barcode': '123', 'access': settings.ACCESS_RESTRICTED}] } ) class TestFileRetrieval(TestCase): def setUp(self): self.c = Client() @patch('project.metadata.do_metadata_request', side_effect=mock_do_metadata_request) def test_token_is_passed_on_to_metadata_server(self, mock_do_metadata_request): header = {'HTTP_AUTHORIZATION': MOCK_TOKEN} response = self.c.get(IMG_URL, **header) -
What technologies are out there for creating Building Block applications
I want to build an app that is similar to Scratch and IRobot Education Code. It should that functions that are normally complicated to someone who has no programming knowledge and makes it an easy drag-and-drop experience for them. It should look somewhat modern and user-friendly. Right now I am planning this app and checking what technologies I will be using to know what I will have to learn. My requirements: python as backend - preferred modern GUI can be web-based expandable easy to learn not "re-inventing the wheel" support Windows 7/10 From my research, I was only able to find Google's "Blockly" library and I would like to know if there are any alternatives for it that would suit me better. From my understanding, If I want something that looks and feels good and modern I will have to make it web-based. I was thinking about Django. The question is if there are any libraries (like for example how bootstrap does with its elements) that implement this "building block" mechanism. -
What is difference between these two method of updating DB using form?
I'm trying update db using form. I want to select title in dropdown, and update 'opening_crawl' field to input from text area. models.py : class Movies(models.Model): episode_nb = models.IntegerField(primary_key=True) title = models.CharField(max_length=64, unique=True, null=False) opening_crawl = models.TextField(null=True) director = models.CharField(max_length=32) producer = models.CharField(max_length=128) release_date = models.DateField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True, editable=True) forms.py: class TitleDropDownForm(forms.Form): title = forms.ModelChoiceField(queryset=Movies.objects.only('title'), empty_label=None) opening_crawl = forms.CharField(widget=forms.Textarea) views.py: def update(request): msg = '' if request.method == 'POST': form = TitleDropDownForm(request.POST) if form.is_valid(): #method 1 : it updates 'opening_crawl' properly, but not 'updated_time'. movie = form.cleaned_data['title'] movie.opening_crawl = form.cleaned_data['opening_crawl'] movie.save() #method 2 #h = Movies.objects.get(pk=1) #h.opening_crawl = 'HAND WRITTEN MESSAGE!' #h.save() return redirect(request.META.get('HTTP_REFERER')) else: form = TitleDropDownForm() if not form.fields['title'].queryset: msg = 'No data available.' return render(request, 'ex07/update.html', context={'form' : form, 'msg' : msg}) method 1 works with 'opening_crawl' field, but 'updated' datetime field was not changed. When I tried like method 2, it updates both fields properly. What is the difference between two method? Is there any misunderstanding? -
Django Date field, form, format mix up
I encounter an error while retrieving date input field data, after looking at numerous threads I still cannot find the answer. The error I receive is : ValueError at /datetime time data '2021-12-31' does not match format '%d/%m/%Y' Thanks Here is my config in details: forms.py class DateInput(forms.DateInput): input_type = "date" def __init__(self, **kwargs): kwargs["format"] = "%d-%m-%Y" super().__init__(**kwargs) class DateStartForm(forms.ModelForm): class Meta: model = DateStart fields = ["start"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["start"].widget = DateInput() ``` models.py ``` class DateStart(models.Model): start = models.DateField(_("Start")) def __str__(self): return f'{self.start}' ``` skimmed views.py ``` def bookingdef(request): if request.method == "POST": if form1.is_valid(): arrival_date = request.POST.get("start") date_obj = datetime.datetime.strptime( arrival_date, '%d/%m/%Y') arrival_date = DateStart.objects.get_or_create(start=arrival_date) form1 = DateStartForm() return render(request, "core/datetime.html", {"form1": form1}) ``` settings.py ``` DATE_FORMAT = ['%d-%m-%Y'] DATE_INPUT_FORMATS = ['%d-%m-%Y'] ``` -
Why do we need Virtual Environment in Django?
I'm new to Django and I wonder why it's recommended to set up a virtual environment. I asked google and found that Python provides a tool virtualenv to create an isolated Python environment. Still, I don't get what's meant by an Isolated environment. Well, briefly my problem is that I don't understand why we need a virtual environment in simple terms. -
How to make a return in the form of a whole message in the __str__ model function in Django?
I just would like getting a next str in my html: made by John Kennedy. But now I have the next str: made by ('John', 'Kennedy') There is the cod from model: class Teams(models.Model): first_name = models.CharField('First name', max_length=15, default='Name') second_name = models.CharField('Second name', max_length=30, default='Family' ) ---...---- def __str__(self): return f'{self.first_name, self.second_name}' class Portfolio (models.Model): ---...---- name = models.ForeignKey (Teams, related_name='maked', on_delete=models.PROTECT,blank=True) ---...---- So how can I fix this? -
DJANGO makemigrations keeps on making new migrations even if no models are changed
I'm confused on why this is happening, I search and found out maybe that the date_choices causes this. Anyway to fix this? I can't delete migration files because I already uploaded my project on github. models.py: class SchoolOfficeHours(models.Model): DAY_CHOICES = { ('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday'), ('Friday', 'Friday'), ('Saturday', 'Saturday'), ('Sunday', 'Sunday') } HOUR_CHOICES = { ('6AM','6AM'), ('7AM','7AM'), ('8AM','8AM'), ('9AM','9AM'), ('10AM','10AM'), ('11AM','11AM'), ('12NN','12NN'), ('1PM','1PM'), ('2PM','2PM'), ('3PM','3PM'), ('4PM','4PM'), ('5PM','5PM'), ('6PM','6PM'), ('7PM','7PM'), ('8PM','8PM'), ('9PM','9PM'), } starting_day = models.CharField( max_length= 12, choices = DAY_CHOICES, default = 'Monday', ) last_day = models.CharField( max_length= 12, choices = DAY_CHOICES, default = 'Friday' ) opening = models.CharField( max_length= 4, choices = HOUR_CHOICES, default = '8AM', ) closing = models.CharField( max_length= 4, choices = HOUR_CHOICES, default = '5PM' ) class Meta: verbose_name_plural = 'School Office Hours' def __str__(self): return f"School Office Hours: from {self.starting_day} to {self.last_day}, {self.opening} - {self.closing}" Should I just change the value of each tuple to integers? But I think, by doing so might be confusing in coding in the future.