Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running out of quotation marks. (Django statics with document.write)
This element: <img id="img" src="{% static 'pd.jpg' %}" /> should go here: popup.document.write("<img src={% static 'pd.jpg' %} />") So think i need a third kind of quotation marks, or ? popup.document.write(String(<img src="{% static 'pd.jpg' %}" />)) at least is not working. -
Django Class Based Views Forbidden (Referer checking failed - no Referer.) - webhook
I have made a class based view to act a webhook but whenever a request comes in I get Forbidden (Referer checking failed - no Referer.): /gc_callback/ I do have the csrf_exempt decorator for dispatch but it seems it does nothing def dispatch(self, *args, **kwargs): return super(Webhook, self).dispatch(*args, **kwargs) Any suggestions? -
Django ModelForm - ManyToMany nested selection
I'm building a Django application and I'm facing an issue I don't know how to solve... I'll try to explain it as clear as I can. I've got an app called "Impostazioni" which has a model called "AnniScolastici": class AnniScolastici(models.Model): nome = models.CharField(max_length=50) class Meta: verbose_name = "Anno scolastico" verbose_name_plural = "Anni scolastici" def __str__(self): return f"{self.nome}" I also have another app called "Attivita" which has a model called "Laboratori": class Laboratori(models.Model): nome = models.CharField(max_length=25) durata = models.IntegerField(default=0) anniscolastici = models.ManyToManyField(AnniScolastici) note = models.TextField(null=True, blank=True) class Meta: verbose_name = "Laboratorio" verbose_name_plural = "Laboratori" def __str__(self): return f"{self.nome}" I've coded up another model called "RichiesteLaboratori" which is related to different models in my Django app (and on the two above, of course): class RichiesteLaboratori(models.Model): date_added = models.DateTimeField(auto_now_add=True) date_valid = models.DateTimeField(null=True, blank=True) provincia = models.ForeignKey("impostazioni.Province", related_name="richiesta_provincia", null=True, on_delete=models.CASCADE) istituto = models.ForeignKey("contatti.Istituto", related_name="richiesta_istituto", null=True, on_delete=models.CASCADE) plesso = models.ForeignKey("contatti.Plesso", related_name="richiesta_plesso", null=True, on_delete=models.CASCADE) classe = models.CharField(max_length=25) numero_studenti = models.PositiveIntegerField() nome_referente = models.CharField(max_length=50) cognome_referente = models.CharField(max_length=50) email = models.EmailField() telefono = models.CharField(max_length=20) termini_servizio = models.BooleanField() classi_attivita = models.ManyToManyField(AnniScolastici, related_name="richiesta_anniScolastici") laboratori = models.ManyToManyField(Laboratori) note = models.TextField(null=True, blank=True) approvato = models.BooleanField(default=False) class Meta: verbose_name = "Richiesta - Laboratorio" verbose_name_plural = "Richieste - Laboratorio" def __str__(self): return f"{self.pk}" I'm … -
POST method doesn't recieve any information from Form (DJANGO & BOOTSTRAP)
I have a form which registers a new user, I used Bootstrap 5 to make it look nice. However, when I press the submit button the form does not validate. The error it shows when I write print(form.errors) says that every field is required, which means it didn't recieve anything. Why does this happen? This is my code: HTML <div class="card" id='signup_card'> <div class='card-header'> <h2 class='card-title'>Sign Up</h2> </div> <div class='card-body'> <form method='POST' action="" id='create_user_form' style="color: #fff;"> {% csrf_token %} <label for='usernameInput' class="form-label">{{form.username.label}}:</label> <input type="text" id='usernameInput' style="margin-bottom: 20px;"> <label for='phoneNumberInput' class="form-label">{{form.phone_number.label}}:</label> <input type="text" id='phoneNumberInput' style="margin-bottom: 20px;"> <label for='emailInput' class="form-label">{{form.email.label}}:</label> <input type="text" id='emailInput' style="margin-bottom: 20px;"> <label for='password1Input' class="form-label">{{form.password1.label}}:</label> <input type="text" id='password1Input' style="margin-bottom: 20px;"> <label for='password2Input' class="form-label">{{form.password2.label}}:</label> <input type="text" id='password2Input' style="margin-bottom: 20px;"> <button class="btn btn-primary" type='submit'>Submit</button> </form> </div> models.py class Account(User): phone_number = BigIntegerField() forms.py class CreateAccountForm(UserCreationForm): class Meta: model = Account fields = ['username', 'email', 'phone_number', 'password1', 'password2'] views.py def signup(request): if request.method == 'GET': form = CreateAccountForm() ctx = { 'form':form } return render(request, 'signup.html', ctx) if request.method == 'POST': form = CreateAccountForm(request.POST) if form.is_valid(): form.save() else: print(form.errors) return render(request, 'index.html') -
Python Environ Django - How to specify to read a different dot env file for dev, test and prod?
Background As I am getting ready for Django deployment to production, I realized that I need to split my settings.py file into different environments. I am trying to have each environment's settings file read a different .env file for that specific environment. Like such: As seen in the documentation # website.settings.dev from .common import * import environ env = environ.Env() # Take environment variables from .env file environ.Env.read_env('.env.dev', recurse=False) print(env('SECRET_KEY')) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ... Issue The .env.dev file is never read and my SECRET_KEY env variable is never loaded onto the system, with python manage.py check, I get the following: File "C:\website\settings\dev.py", line 10, in <module> print(env('SECRET_KEY')) File "C:\project\virtual-env\lib\site-packages\environ\environ.py", line 165, in __call__ return self.get_value( File "C:\project\virtual-env\lib\site-packages\environ\environ.py", line 361, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable (virtual-env) PS C:\project> However, if I were to rename my .env file back to .env and read the file with environ.Env.read_env() Everything works, and my print statement prints out my secret key. Question Why can't environ read the specified file? How to specify a file for … -
How do I reference my model in a nested folder structure to dump data in Django 3.2?
I'm using Django 3.2 and Python 3.9. I have this project directory setup + cbapp - manage.py - settings.py + models - __init__.py - crypto_currency.py In my settings.py file, I have INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cbapp', ] I want to dump some data to a fixtures file, so I tried $ python3 manage.py dumpdata cbapp.models.crypto_currency > ./cbapp/fixtures/crypto_currency.json CommandError: No installed app with label 'cbapp.models.crypto_currency'. What's the proper way to reference my model to dump data? -
How to load editorJs scripts integrated with django after an ajax call?
I am using editorJs for my description field as follows: epic_description = EditorJsField( editorjs_config={ "tools": { "Image": { "config": { "endpoints": { "byFile": "/imageUlaod/", "byUrl": "/imageUlaod/", }, "additionalRequestHeader": [ {"content-Type": "multipart/form-data"} ], } }, "Attaches": { "config": { "endpoint": "/fileUPload/", } }, } }, blank=True, null=True, ) But I also call this form of this field via ajax to load it. And it turns out that the script for the editorJs is not loaded at all. When I looked to my console it uses the cdn url https://cdn.jsdelivr.net/sm/jsdelivr-separator.js. Now I have no idea how to solve this issue since I do not know what script to load in the first place I check at the url to see if I can download the js file. Eiih nothing. Any help would be appreciated highly. -
'WSGIRequest' object has no attribute 'get'... API link from google
I am trying to use the Books APIs from google to import books to the website and save them in the database. Unfortunately, I have a problem with the get method and I don't know where the problem is. I get an error like in the subject. search_url = "https://www.googleapis.com/books/v1/volumes?q=search+terms" params = { 'q': 'Hobbit', 'key': settings.BOOK_DATA_API_KEY } r = request.get(search_url, params=params) print(r.text) return render(request, "BookApp/book_import.html")``` -
Trouble starting Django project w/o errors
This is the original code in urls.py. Similarly, errors in view.py, and the app url.py files automatically appear whenever I start a project in django (3.2.8). I've just begun coding, no one I've asked can answer why. HELP! from django.contrib import admin from django.urls import path -
conexion django con base de datos 4Dimension
quiero conectarme con la base de datos 4Dimension desde django. alguien tiene alguna idea de como hacerlo en solo lectura? -
stale token even for first time user Djoser and DRF
the newly registered user get email for activation . He clicks on the links and move to an activation page .then he clicks on verify button which take uid and token from the link and post it to auth/users/activation/ and then gets the response stale token for the given user no matter how fast he click on the link on verify link . result is same. I am using djoser for activation and all user related stuff.and redux in the frontend for api calls and also the React as frontend here is my settings.py: DJOSER = { 'LOGIN_FIELD': 'email', 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION':True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SOCIAL_AUTH_TOKEN_STRATEGY': 'djoser.social.token.jwt.TokenStrategy', 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': ['https://negoziohub.herokuapp.com/google', 'http://127.0.0.1:8000/facebook'], 'SERIALIZERS': { 'user_create': 'base.serializers.UserSerializer', 'user': 'base.serializers.UserSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } here is userAction.js: export const activate = (uid, token) => async (dispatch) => { try { dispatch({ type: USER_ACTIVATE_REQUEST }) const config = { headers: { 'Content-type': 'application/json', } } const body = JSON.stringify({ uid, token }); const { data } = await axios.post(`/auth/users/activation/`, body, config ) dispatch({ type: USER_ACTIVATE_SUCCESS, payload: data }) // dispatch(login()) localStorage.setItem('userInfo', JSON.stringify(data)) } catch (error) { dispatch({ type: USER_ACTIVATE_FAIL, payload: error.response && error.response.data.detail ? … -
Upgrade Django with incompatible migrations
I'm tasked with upgrading the Django version for a project that currently uses Django 2.2.24. It contains a model (with existing migrations) that looks roughly like this: class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) type = models.ForeignKey(MembershipType, on_delete=None) Starting with Django 3.0, on_delete=None causes an error since on_delete is supposed to be a callable. In order to avoid the error, both the model and the existing migrations have to be changed. By itself, it's not an issue to change the model like this: class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) type = models.ForeignKey(MembershipType, on_delete=models.SET_NULL, null=True) But existing databases are not yet aware that the corresponding field can be nullable, so a new migration is required for that. The best way I currently see to do this is the following: change the model create&apply a migration using Django 2.2.24 change the old migrations manually Is there a more elegant way to solve this issue? -
How can I test delete view in Django app?
I want to test my View but I have problem with my delete function. class AnimalView(APIView): def delete(self, request, format = None): id = int(request.GET.get('id')) try: animal = Animal.objects.get(id=id) except: return Response(status=status.HTTP_404_NOT_FOUND) animal.delete() return Response(status=status.HTTP_204_NO_CONTENT) This is my model: class Animal(models.Model): name = models.CharField(unique=True, max_length=30, blank=False, null=False) class Meta: managed = True db_table = 'animal' ordering = ['name'] def __str__(self): return str(self.name) and this is the test that I'm trying to make: class TestURL(TestCase): def setUp(self): self.client = Client() def test_animal_delete(self): animal = Animal.objects.create(name = 'TestAnimal') response = self.client.delete(reverse("category_animal"), json.dumps({'id' : animal.id})) self.assertEqual(status.HTTP_204_NO_CONTENT,response.status_code ) But I'm getting a TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' Can you please help me with my test? -
Use template date filters in custom template tag?
I want to use Django template date filters inside a custom template tag. Is that possible? My end goal is to be able to use it like this: {{parcel.pickup_dates|delivery_dates_formating}} Problem is, that "pickup_dates" can be array of 1 or 2 or 3 elements. My desired output is: "Sunday, 21 September" if one element, "Satardau - Sunday, 21-22 September" if 2 elements, "Friday - Sunday, 20-22 September" if 3 elements, Currenly my temlpate tag looks like this: def delivery_dates_formating(value): if len(value) == 1: return [value[0]] if len(value) == 2: return [value[0], value[1]] if len(value) == 3: return [value[0], value[2]] And in template I used to use something like: {{parcel.delivery_date|date:'E j, l'|capfirst}} I woul like to use django tempaltes date filtes, as it handels localisation. Is that possible? -
Where do Django's Field's "default" and test's "client" parameters come from?
If you search for the parameters of a Field (e.g. IntergField) in Django through from django.db import models dir(models.IntegerField) you get 'default_error_messages', 'default_validators', 'unique', 'validate', 'validators', etc, but not "default" itself, although it's commonly used, as in class Choice(models.Model): ... votes = models.IntegerField(default=0) Same thing with "client". The docs say TestCase "comes with its own client". In this snippet from Django's docs, this client is explored class QuestionIndexViewTests(TestCase): def test_no_questions(self): """ If no questions exist, an appropriate message is displayed. """ response = self.client.get(reverse('polls:index')) but you can't find it through from django.test import TestCase dir(django.test.TestCase) or even dir(django.test.TestCase.client_class) I'm asking where they come from, but also how to search for these "hidden" parameters, methods, etc. -
Django call SOAP API
I made a CRM and now the company wants to set up their API, but it's a SOAP API who uses XML and after a little research here in Stack, some people said to use zeep, and didn't work. I'm trying first from a separate file to put in the CRM later (maybe not the best idea) but I think I'm doing wrong/more than I need to. Is it right to do this way or is there a better way ? from zeep import Client client = Client('httsp://company.com/?wsdl') element1 = client.get_element('ns0:E1') element2 = client.get_element('ns1:E2') element3 = client.get_element('ns2:E3') element4 = client.get_element('ns3:E4') element5 = client.get_element('ns4:E5') element6 = client.get_element('ns5:E6') element7 = client.get_element('ns6:E7') element8 = client.get_element('ns7:E8') element9 = client.get_element('ns8:E9') obj1 = element1(E1 = 'A') obj2 = element2(E2 = 'B') ... obj9 = element9(E9 = 'I') header_value = header(username='user', password='pass') client.service.Companymethod(_soapheader={heaeder_value, obj1, obj2, ... obj9}) XML: <definitions targetNamespace="http://X/soap/X"> <types> <xsd:schema targetNamespace="http://X/soap/X"> <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/"/> <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/"/> <xsd:complexType name="Companymethod"> <xsd:all> <xsd:element name="YRequest" type="tns:YRequest" minOccurs="1"/> </xsd:all> </xsd:complexType> <xsd:complexType name="YRequest"> <xsd:all> <xsd:element name="E1" type="xsd:string" minOccurs="1" maxOccurs="1"/> <xsd:element name="E2" type="xsd:nonNegativeInteger" minOccurs="1" maxOccurs="1"/> <xsd:element name="E3" type="xsd:string" minOccurs="1" maxOccurs="1"/> <xsd:element name="E4" type="xsd:string" minOccurs="1" maxOccurs="1"/> <xsd:element name="E5" type="xsd:nonNegativeInteger" minOccurs="1" maxOccurs="1"/> <xsd:element name="E6" type="xsd:boolean" minOccurs="0" maxOccurs="1"/> <xsd:element name="E7" type="xsd:nonNegativeInteger" minOccurs="0" maxOccurs="1"/> <xsd:element name="E8" type="xsd:nonNegativeInteger" … -
Custom User Model Django Error , No such table
Models.py class UserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser phone = models.IntegerField() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def get_full_name(self): return self.email def get_short_name(self): return self.email def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin objects = UserManager() Settings.py AUTH_USER_MODEL = 'Accounts.User' Error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: Accounts_user I have created a Model User, but when I tried to create a superuser, i got an error, that table does not exist, I have tried makemigrations and migrate command multiple times, but nothing seems to solve the issue i can't even open the table even in the admin pannel, can someone help me solve this issue -
Django implicit field naming for class with query expression - how does it work?
Simplified example of what I wrote today: class Grandparent(models.Model): text = models.CharField(max_length=5, choices=too_many) class Parent(models.Model): grandparent = models.ForeignKey(Grandparent, on_delete=models.CASCADE) info = models.CharField(max_length=30) class ChildSomething(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) data = models.CharField(max_length=5, choices=chromosome_identities) Given a specific Grandparent object, I wanted to order Parent objects underneath it by most ChildSomething's each Parent has, which I did successfully below. grandparent = Grandparent.objects.get(id=32923) # arbitrary id # This query produces the desired result parents = ( Parent.objects.filter(grandparent=grandparent). annotate(num_child_somethings = Count('childsomething')). order_by('num_child_somethings') ) My question: Why is it Count('childsomething') instead of Count('child_something')? The latter was my intuition, which was corrected by a helpful Django error message: Exception Type: FieldError Exception Value: Cannot resolve keyword 'user_translation' into field. Choices are: id, translate_text, translate_text_id, translation, usertranslation The answer to this is likely simple, I just couldn't find anything in the docs related to this. How does the naming convention work? If anyone knows of the appropriate Django docs link that would be ideal. Thank you. -
Django Webpack static not finding file
I created a Django application and tried to serve files via webpack. Now the application can't find those files despite setting the required constants in settings.py. The output folder is right in the root directory and should be picked up by STATICFILES_DIRS, but if I start the application I get a 404 not found error. I'm outputting my files via webpack inside the root folder in /dist/js/*.js webpack.config.js const webpack = require('webpack'); const glob = require('glob'); let globOptions = { ignore: ['node_modules/**', 'venv/**'] } let entryFiles = glob.sync("**/javascript/*.js", globOptions) let entryObj = {}; entryFiles.forEach(function(file){ if (file.includes('.')) { let parts = file.split('/') let path = parts.pop() let fileName = path.split('.')[0]; entryObj[fileName] = `./${file}`; } }); const config = { mode: process.env.NODE_ENV, entry: entryObj, output: { path: __dirname + '/dist/js', filename: '[name].js' }, optimization: { minimize: false } } module.exports = config settings.py BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = "/static/" STATICFILES_DIRS = [ ("js", f"{BASE_DIR}/dist/js"), ] STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") main.html: {% load static %} <!DOCTYPE html> <html lang="de"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> {% block content %} {% endblock %} </body> <!-- Load bundled webpack script --> <script src="{% static 'main.js' %}" … -
Fixing ValueError: source code string cannot contain null bytes for django server
I am new to Django and I am trying to run my server, but I get this error message. Any help on how to fix it? File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 3, in <module> from django.core.management.commands.runserver import ( File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\staticfiles\ma nagement\commands\runserver.py", line 3, in <module> from django.core.management.commands.runserver import ( File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\comman ds\runserver.py", line 10, in <module> from django.core.servers.basehttp import ( File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\servers\basehttp. py", line 14, in <module> from wsgiref import simple_server ValueError: source code string cannot contain null bytes I am using IntelliJ terminal to run it with python manage.py runserver Tried re-saving and re-writing it so to be sure it is in UTF-8, and it is. -
Field data disappears in Django REST framework
I have a field "plugins" (see below) in my serializer and this is a serializer which also contains a file upload which is why the MultiPartParser is used. My view is pretty much standard, and the plugins field data also shows up in the request.data, however it doesn't show up in the validated_data of the serializer. To bring a minimalistic example, this would be my serializer: class CreationSerializer(serializers.ModelSerializer, FileUploadSerializer): plugins = serializers.ListSerializer( child=serializers.CharField(), required=False, write_only=True) class Meta: fields = ['plugins'] + FileUploadSerializer.Meta.fields model = Company def create(self, validated_data): print(validated_data) While this would be my views.py: @swagger_auto_schema(request_body=CreationSerializer(), responses={201: CreationSerializer()}, operation_id='the_post') def create(self, request, *args, **kwargs): print(request.data) return super().create(request, *args, **kwargs) # which uses mixins.CreateModelMixin -
Cleaner django filters in graphql query
I have a project in angular where we use graphql to gather data from api that is created in django. I am using filters that are available in django-filter and here is my question. My example query looks like this: query foo( ... $something_Icontains: String, $something_Iexact: String, $something_IstartWith: String, $something_IendsWith: String, $something_IsNull: String, ... ) { foo( ... something_Icontains: $something_Icontains, something_Iexact: $something_Iexact, something_IstartWith: $something_IstartWith, something_IendsWith: $something_IendsWith, something_IsNull: $something_IsNull, ... ) { result { ...fooFields } } } It is quite lengthy and grows exponentially when more fields is added. Is there any way to shorten it? -
Passing ID Mitch mech with Django Pattern in Axios, Vue JS
I am want to update and delete by clicking in Datatable button. But, unfortunately I could not passing the PK=ID in Django Pattern through Axios. `from django.urls import path from . import views from django.views.generic import TemplateView app_name = 'todospaapp' urlpatterns = [ path('', views.index, name='index'), path('todos/', views.todos, name='todos'), path('save_todo/', views.save_todo, name='save_todo'), # path('<pk>/update', views.save_todo_update, name='save_todo_update' ), path('save_todo_update/<int:pk>', views.save_todo_update, name='save_todo_update'), ]` In my view.py `def save_todo_update(request, pk): try: todoitem = TodoItem.objects.get(pk=pk) except TodoItem.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = TodoItemSerializer(todoitem) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser.parse(request) serializer = TodoItemSerializer(todoitem, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors)` In my HTML: <tbody> <tr v-for="todo in todos"> <th scope="row" >[[todo.id]]</th> <td>[[todo.text]]</td> <td>[[todo.date_created | formatDate]]</td> <td>[[todo.date_completed | formatDate]]</td> <td><a class="btn btn-primary" v-on:click="updateTodo(todo.id)" >Update</a></td> </tr> </tbody> In Axios: updateTodo: function(id) { axios({ url: "{% url 'todospaapp:save_todo_update/'+id %}", method: 'put', data: { todo_text: this.input_todo }, headers: { 'X-CSRFToken': '{{ csrf_token }}' } }).then(response => { // console.log(response.data) this.getTodos() }) } }, -
Should i use Vue or django for URL routing?
I have been learning web development for two months, in tutorials there is a video about path and components with vue. const routes= [{ path:"/", component: () => import(./views/home) }] As far as i know you can do the same thing with django as well. urlpatterns = [path('', views.special_case_2003),] Which one should i use for URL routing? If they are doing same thing then why should i use a backend framework? -
Django Calculated fields Save()
This is very basic, but I'm having trouble finding the correct way to do this. I would like to have fields that are calculated and saved into the database. In the example, cHpd,cMpd and cBph are all fields that are calculated in the calc_rates function. I am piecing together how to do this. ''' class Route(models.Model): rtNumber = models.CharField(max_length = 5) rtState = models.CharField(max_length = 2) rtOffice = models.CharField(max_length = 255) #stDate = models.DateField(blank=True) #edDate = models.DateField(blank=True) llcName = models.CharField(max_length =255) boxes = models.IntegerField(null=True) miles = models.IntegerField(null=True) hours = models.IntegerField(null=True) wrkDays = models.IntegerField(null=True) activeCont= models.BooleanField(default=None) contRate = models.IntegerField(null=True) cHpd = models.IntegerField(null=True) cMpd = models.IntegerField(null=True) cBph = models.IntegerField(null=True) @property def calc_rates(self): hpd = self.hours / self.wrkDays mpd = self.miles / self.wrkDays bph = self.boxes / hpd self.cHpd = hpd self.cMpd = mpd self.cBph = bhp super(Route, self).save()