Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mocking external calls that are within a django API call
I'm writing tests for a django app, and the basic unit-tests are fine. I've written mocking tests for other things (both Perl & Python/Tornado), so I understand the base concept. I've even read over https://realpython.com/testing-third-party-apis-with-mocks/ to try to wrap my head round this... So here's my problem: I have an object call that (in bare bones) looks like this: import asyncio import requests from django.conf import settings from django.contrib.auth.models import AbstractUser from django.db import models loop = asyncio.get_event_loop() class NoteableUser(AbstractUser, models.Model): ### Lots of object attributes ### A bunch of methods to have deduced object attributes def jupyter_start(self, options, jwt_token): ### Do a bunch of stuff user_options = {'dict': {'levels': 'multiple'}} # Create server try: resp = requests.post( "http://{}/hub/api/users/{}/server".format( settings.JUPYTER_URL, self.username ), headers={"Authorization": "token " + settings.JUPYTER_TOKEN_PASSWORD}, data=json.dumps(user_options), verify=False, ) # Check progress loop.run_in_executor(None, self.jupyter_progress) except: raise Exception("Could not start notebook") data = {"status_code": resp.status_code, "token": token} return data ### and more methods I've two problems I can't get my head around: How do I write a test to call the app as a Django API (ie, so the settings are defined) How do I mock that inner requests.post call? For #2, my solution to a similar problem under Perl … -
How can I find all objects of a model type that share a many-to-many-relationship?
So, I have two model classes, let's use the django docs example and call them Person and Group. These are related in a many-to-many relationship - a Person can be in multiple Groups, and Groups can have multiple Persons. If I have a single Person object, what's the best way to find all other Persons with whom they share a group? -
Django HTML & CSS render to pdf
I'm trying to generate HTML & CSS to pdf page using Django-weasyprint but I'm kind of stuck with their tutorial cause I want the PDF to render when the user clicks on the download button and the pdf downloads automatically with read-only privileges. Currently, weasyprint just converts a URL in Django to pdf but I don't know how to set the button to look at the weasyprint view. Maby I am looking past it and overcomplicating it, any assistance would be appreciated Weasyprints example code from django.conf import settings from django.views.generic import DetailView from django_weasyprint import WeasyTemplateResponseMixin from django_weasyprint.views import CONTENT_TYPE_PNG class MyModelView(DetailView): # vanilla Django DetailView model = MyModel template_name = 'mymodel.html' class MyModelPrintView(WeasyTemplateResponseMixin, MyModelView): # output of MyModelView rendered as PDF with hardcoded CSS pdf_stylesheets = [ settings.STATIC_ROOT + 'css/app.css', ] # show pdf in-line (default: True, show download dialog) pdf_attachment = False # suggested filename (is required for attachment!) pdf_filename = 'foo.pdf' class MyModelImageView(WeasyTemplateResponseMixin, MyModelView): # generate a PNG image instead content_type = CONTENT_TYPE_PNG # dynamically generate filename def get_pdf_filename(self): return 'bar-{at}.pdf'.format( at=timezone.now().strftime('%Y%m%d-%H%M'), ) I made a virtual env on my pc and its setup exactly like the example. Currently using Boostrap 4 -
DRF SerializerMethodField method only running when serializer variable opened in debugger
My SerializerMethodField method is only printing HERE when I have a breakpoint at the return in the get method, and open the serializer variable after it has triggered. View: class EventAddPeople(generics.GenericAPIView): serializer_class = EventAddPeopleSerializer_Read def get(self, request, *args, **kwargs): # serialize data - get event/persons serializer = EventAddPeopleSerializer_Read(data=request.data) serializer.is_valid(raise_exception=True) print(serializer.validated_data) return HttpResponse(serializer.validated_data) Serializer: class EventAddPeopleSerializer_Read(serializers.Serializer): event_id = serializers.SerializerMethodField(method_name='get_event_id') person_ids = serializers.SerializerMethodField() def get_event_id(self, obj): print("HERE") return "TEST00" -
Test doesn't change the language
I want to test my models in multilanguage but the code ignores my change of language. My models.py: class NameType(models.Model): ... class Meta: if get_language().split('-')[0] == 'it': print(get_language()) # called once at begin of test ordering = ['name_it'] elif get_language().split('-')[0] == 'en': print(get_language()) # never called ordering = ['name_en'] My test_models.py: class NameTypeTest(TestCase): def test_nametype_ordered(self): name = NameType.objects.create(name_en='Name', name_it='Nome') surname = NameType.objects.create(name_en='Surname', name_it='Cognome') activate('it') nametype_list = NameType.objects.all() self.assertEqual(nametype_list[0], surname) self.assertEqual(nametype_list[1], name) print(get_language()) # it activate('en') nametype_list = NameType.objects.all() # nametype_list = sorted(NameType.objects.all()) # I tried even this print(get_language()) # en self.assertEqual(nametype_list[0], name) # here the test fails self.assertEqual(nametype_list[1], surname) print(get_language()) # never called, the test fail before nametype_list[0] is surname even when en is activated, instead it should be name because name_en=name comes before name_en=surname (n < s). I tried to sort the queryset after change the language but nothing change. The language looks activated (get_language() gives the correct language). The meta of the model is called only once. Thank you -
SyntaxError: (unicode error) ‘unicodeescape’ code cant’d decode bytes in position 37-38 truncated \UXXXXXXXX escape
file_path = CustomPathField(max_length=300, blank=True, help_text="Ex: <strong>Windows path:</strong> C:\Users\Arti\Documents\artifacts.txt, <strong>UNIX path:</strong> /home/arti/artifacts.txt") SyntaxError: (unicode error) ‘unicodeescape’ code cant’d decode bytes in position 37-38 truncated ]UXXXXXXXX escape -
Creating superuser Programmatically and verify email using allauth and rest auth
I am able to create users using rest auth registration and send verification email. But I want to create superuser and send verification mail but that's not happening. I am Programmatically creating superuser on registration. I am able to create superuser. The reason from my inspection is that when I use rest auth registration to create users it uses allauth to send verification mail. The allauth/accounts/email automatically works. signin, registers email and sends the mail. I can see that in admin the user email is registered under a special email field. This does not happen when I create superuser programmatically. Also the allauth/accounts/email does not register email. I have to manually login to allauth in case of superuser. How can I automate email verification for superuser. Thanks -
DJRF Got AttributeError when attempting
I'm trying to make a raw sql command from my django code and I keep getting an error when trying to reach it via Postman Got AttributeError when attempting to get a value for field profile_id on serializer AllDataSerializer Code Serializer.py class AllDataSerializer(serializers.ModelSerializer): class Meta: model = AllData fields = [ 'id', 'profile_id', 'first_name', 'last_name', 'tweet_text' ] Views.py class AllData(APIView): permission_classes = [IsOwnerOrReadOnly] def get(self, profile_id=None): with connection.cursor() as cursor: cursor.execute( "SELECT authapi_user.id AS profile_id, authapi_user.first_name, authapi_user.last_name, authapi_tweet.tweet_text FROM authapi_tweet INNER JOIN authapi_user ON authapi_user.id = authapi_tweet.author_id;") table = cursor.fetchone() data = AllDataSerializer(table).data return Response(data) Models.py class AllData(models.Model): profile_id = models.IntegerField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) tweet_text = models.CharField(max_length=200) -
Filtering Foreign Key Items
I have a couple models and I am attempting to filter the candidates in the PositionUpdate form based on the applicants who have applied for that position. class Position(models.Model): title = models.CharField(max_length=128,verbose_name='Title') candidate = models.ForeignKey('careers.Applicant', on_delete=models.SET_NULL, related_name='candidate', blank=True, null=True ) class Applicant(models.Model): first_name = models.CharField(max_length=128,blank=False,verbose_name="First Name") position = models.ManyToManyField(Position,related_name='applicants', blank=True) Thank you -
Django/Apache - read files from network drive (Windows)
I have been working in windows environment for producing & deploying django for internal use at work and been asked to add a feature to read files saved at the network drive (ideally, .xlsx file view). So, I would want to list .xlsx files in a specified folder in the network drive and let the user view the file if clicking on it. My first approach was to create a user account with "Log on as a service" and "Act as part of the operating system," and run the Apache using this account. But, later realized I can't inherit the access to the network drive my admin account has (or is it possible?). And, I decided to run it with my admin account, which I know is not a good idea to do in production, but wanted to see that I am on a right track... Tried below config but I am stuck at how to proceed from here to achieve the feature described above.. /l/ is an alias of the UNC of network drive. <Directory /l/> Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Require all granted Allow from all </Directory> I tried SMB to try connecting but connection error … -
Updating 3 forms using formsets in view
I have a view that adds 3 different model objects using 3 ModelForms and formsets: here is it: @login_required def nouveaudossier(request): DocumentFormSet = modelformset_factory(DocumentdeBase, form=DocumentdebaseForm, extra=5) PhotoAvantFormSet = modelformset_factory(PhotoAvant, form=PhotoAvantForm, extra=5) if request.method == 'POST': dossierForm = DossierForm(request.POST) formset = DocumentFormSet(request.POST, request.FILES, queryset=DocumentdeBase.objects.none()) formset2 = PhotoAvantFormSet(request.POST, request.FILES, queryset=PhotoAvant.objects.none()) if dossierForm.is_valid() and formset.is_valid() and formset2.is_valid(): dossier_form = dossierForm.save(commit=False) dossier_form.created_by = Prestataire.objects.filter(user=request.user).first() dossier_form.save() for form in formset.cleaned_data: #this helps to not crash if the user #do not upload all the photos if form: image = form['documentdebase_image'] photo = DocumentdeBase(dossier=dossier_form, documentdebase_image=image) photo.save() for form2 in formset2.cleaned_data: #this helps to not crash if the user #do not upload all the photos if form2: image2 = form2['photoavant_image'] photo2 = PhotoAvant(dossier=dossier_form, photoavant_image=image2) photo2.save() messages.success(request, "Dossier créé!") return HttpResponseRedirect("/") else: print(dossierForm.errors, formset.errors, formset2.errors) else: dossierForm = DossierForm() formset = DocumentFormSet(queryset=DocumentdeBase.objects.none()) formset2 = PhotoAvantFormSet(queryset=PhotoAvant.objects.none()) return render(request, 'dashboard/nouveau_dossier.html', {'dossierForm': dossierForm, 'formset': formset, 'formset2': formset2}) Now, I want to make an update view, where it takes the same form, and populates it with data existing from the 3 models, and the user can make changes. Here is what I did, I added an instance to the form, and a pk attribute to the function: @login_required def reviserdossier(request, pk): DocumentFormSet = … -
How can I show related objects in django?
I have three models: Porumbei, Concursuri and Rezultate. I have some Porumbei, I create a Concurs A and Rezultate B. The Rezultate model is linked to Porumbei through porumbelul(manytoManyField, one porumbel can be in many Rezultate and Rezultate can have more porumbei). I want a page to display as a table details of Rezultate and how can I show every Porumbei that belongs to that Concursuri and same Rezultate? Rezultate is linked with Concursuri through concursul(onetoonefield) My models: class Porumbei(models.Model): id_porumbel = models.AutoField(primary_key=True) data_adaugare = models.DateTimeField(default=timezone.now, null=True, blank=True) crescator = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, blank=True, related_name='porumbeii') serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True, help_text="Seria de pe inel. Ex: RO 123456") anul = models.CharField(max_length=4, null=False, blank=False) .... class Concursuri(models.Model): crescator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='concursurile') sezon = models.CharField(max_length=4, default=timezone.now().year, null=True, blank=True) cod_concurs = models.CharField(max_length=8, primary_key=True, unique=True) tip_concurs = models.CharField(max_length=12, choices=TIPURI_CONCURS) categorie_concurs = models.CharField(max_length=10, choices=CATEGORII) data_lansare = models.DateField(null=False, blank=False) .... class Rezultate(models.Model): crescator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) concursul = models.OneToOneField(Concursuri, on_delete=models.CASCADE, related_name="concursul") porumbelul = models.ManyToManyField(Porumbei) sosire = models.DateTimeField(blank=False) zi_concurs = models.PositiveIntegerField(blank=False, default=1) timp_zbor = models.DateTimeField(blank=False) viteza = models.CharField(max_length=15, blank=False) penalizare = models.FloatField() My view: def viewrezultate(request): # Variabile folosite in tabelul de afisare rezultate rezultate = Rezultate.objects.filter(crescator=request.user) concursuri = Concursuri.objects.filter(crescator=request.user) porumbei = … -
Why won't my text posts save, it worked before?
My text posts were working before adding a notification feature but now they aren't, I have a debug print but instead of seeing the post object, I'm seeing the user that posted it. I haven't changed anything other than getting the post id, timesince and the notify function, I've used the exact same method with my picture and video posts and they work fine, so it doesn't make sense to me. views.py @login_required() def text_post(request): if request.method == "POST": form = TextPostForm(request.POST, instance=request.user) if form.is_valid(): t_post = form.save(commit=False) t_post.author = request.user t_post.save() id = t_post.id time = timesince print(t_post) # t_post shows the user instead of the post followers = list(request.user.followers.all()) notify(followers, request.user, f"{request.user.username} posted a picture {time}", id, 'text' ) print(t_post) #redirect to last page return redirect('home') else: form = TextPostForm() post_type = 'text' return render(request, 'create_post.html', {'form': form, 'post_type': post_type}) -
How do I let my docker volume sync to my filesystem and allow writing from docker build
I'm building a django app using docker. The issue I am having is that my local filesystem is not synced to the docker environment so making local changes have no effect until I rebuild. I added a volume - ".:/app:rw" which is syncing to my local filesystem but does my bundles that get built via webpack during the build don't get inserted (because they aren't in my filesystem) My dockerfile has this ... setup stuff... ENV NODE_PATH=$NVM_DIR/versions/node/v$NODE_VERSION/lib/node_modules \ PATH=$NVM_DIR/versions/node/v$NODE_VERSION/bin:$PATH ENV PATH=/node_modules/.bin:$PATH COPY package*.json / RUN (cd / && npm install && rm -rf /tmp/*) ...pip install stuff... COPY . /app WORKDIR /app RUN npm run build RUN DJANGO_MODE=build python manage.py collectstatic --noinput So I want to sync to my local filesystem so I can make changes and have them show up immediately AND have my bundles and static assets present. The way I've been developing so far is to just comment out the app:rw line in my docker-compose.yml which allows all the assets and bundles to be present. -
How to run django's "python manage.py runserver" , celery's "celery -A app_name worker -l info" and redis-server in one command
I have recently started with django. And I started doing a small project. I've been using celery with redis worker. And every to use celery and redis I have to run the celery and redis server and then django server. Which is a bit lengthy process. I have two questions. 1. Am I doing the right thing by running the servers everytime or are there any other right method to this process? 2. If I'm in the right direction, is there any method to do this? I tried circus.ini , but it did not work. -
Django doesn't read form
I have form: <form id="contact-form" class="contact__form" method="POST" action="{% url 'backcall' %}"> {% csrf_token %} <span class="text-color">Send letter</span> <div class="form-group"> <input name="name" type="text" class="form-control" placeholder="Name"> </div> <div class="form-group"> <input type="tel" name="phone" class="form-control" placeholder="Phone (+380)" pattern="[\+][3][8][0]\d{9}" minlength="13" maxlength="13" /> </div> <div class="form-group"> <input name="email" type="email" class="form-control" placeholder="Email"> </div> <div class="form-group-2 mb-4"> <textarea name="message" class="form-control" rows="4" placeholder="Your letter"></textarea> </div> <button class="btn btn-main" name="submit" type="submit">Send</button> </form> views.py: def backcall(request): backcall = BackCall(name = request.POST['name'], phone = request.POST['phone'], email=request.POST['email'] , message = request.POST['message']) backcall.save() return redirect('thanks') models.py class BackCall(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=13) email = models.EmailField() message = models.TextField(default=None) datetime = models.DateTimeField(auto_now_add=True) When I fill out the form and submit nothing happens. When I follow the link 'backcall/' I get an error. What the problem can be connected with and how to fix it? -
Django encrypted paypal m2crypto python3, error
I added the integration of Paypal with Django with the help of django-paypal, but I have a problem. I use the PaypalPaymentForm form, but it is possible to modify the values of that form, And I don't want that to happen. The solution I found was to use the PayPalEncryptedPaymentsForm form, so you cannot modify the values per form. The problem is that I need the M2Crypto library, which is only available in python2, and I am using python3 and Django2.2.2. Is there any way to solve this problem? I also tried to install the library by pip, but it gives me an error. I saw that there is a somewhat similar form called PayPalSharedSecretEncryptedPaymentsForm, I did not quite understand how it works, is this form an alternative to the PayPalEncryptedPaymentsForm form? Documentation about django-paypal: https://django-paypal.readthedocs.io/en/stable/ -
Getting error on some browsers about duplicate entry for user_id Django
For some reason, my code works on some browsers, but throws a duplicate error on other browsers. IntegrityError: 'Duplicate entry X for key 'user_id'' This is the code that I use to create the user: if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): password1 = form.cleaned_data['password1'] try: validate_password(password1) user = form.save(commit=False) user.is_active = True user.set_password(form.cleaned_data['password1']) user.save() user = authenticate(request, username=form.cleaned_data['username'], password=form.cleaned_data['password1']) if user.is_authenticated: login(request, user, backend='django.contrib.auth.backends.ModelBackend') Then this is the view where the error shows up: user=request.user if request.method == "POST": form = SecondaryForm(request.POST) if form.is_valid(): second = form.save(commit=False) second.user = user second.save() I have literally no idea why it's throws this error on Chrome, but not on Safari or Firefox. -
How to use created Django API Key to access API in browser?
In my django app I have created a url that could give Django REST framework API.The url is http://127.0.0.1:8000/api/events/ I have added API Key restrictions in settings.py so that only people who have API Key could access the API service. REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": [ "rest_framework_api_key.permissions.HasAPIAccess", ] } Then in my Django Admin site I created an API Key as below. Now I want use this API Key to access my API. But I don't know how to use it. I tried to use some url in my browser like http://127.0.0.1:8000/api/events/?key=4278348c-2ff3-4f72-99e8-7284832d6049 But it still shows an error page as API Key is missing. Does anyone know how can I access the API in browser? Thank you. -
display list of data for login user
I am testing an app, I want the user to be able to views his own leave but not other users leave when he login, but I cannot seem to come up with the right logic. In my current code only the first name and the last name is displayed on the template, the rest of the data did not seem to display. I don't know what I am doing wrong here. class NewLeave(models.Model): user = models.ForeignKey(User, default='', on_delete=models.CASCADE) leave_balances = models.ManyToManyField(Leave_Balance) leave = ( ('annual', 'annual'), ) Leave_type = models.CharField(max_length=100, choices=leave, blank=False, default='annual') dp = ( ('test1', 'test1'), ('test2', 'test2'), ) department = models.CharField(max_length=100, choices=dp, blank=False, default='') Start_Date = models.DateField(null=True, blank=False) End_Date = models.DateField(null=True, blank=False) def __str__(self): return self.user.first_name def test(request): username = None if request.user.is_authenticated: get_user_fname = request.user.first_name get_user_lname = request.user.last_name display = User.objects.filter(first_name=get_user_fname, last_name=get_user_lname) return render(request, 'test.html', {'display': display}) {%for leave in display%} <tr class="success"> <td>{{leave.first_name}}</td> <td>{{leave.last_name}}</td> <td>{{leave.user.NewLeave.Leave_type}}</td> <td>{{leave.user.NewLeave.department}}</td> <td>{{leave.user.NewLeave.Start_Date}}</td> <td>{{leave.user.NewLeave.End_Date}}</td> </tr> {%endfor%} -
JS request without showing API key for leaflet
I would like to request a Leaflet tilelayer without exposing my API key and secret. I believe I can solve this by using my own server as a proxy. I've found the solution (below) which is for PHP. I'm using Django instead. What would be the syntax to do the same? Thanks in advance! <?php // get-tiles-proxy.php // Ingest the URL parameters $s = $_GET["s"]; $z = $_GET["z"]; $x = $_GET["x"]; $y = $_GET["y"]; header('Content-Type: image/png'); // Concatenate the URL parameters into a properly-formatted url for your tile provider $path = 'https://tile-'.$s.'.urthecast.com/v1/rgb/'.$z.'/'.$x.'/'.$y.'?api_key=MY_API_KEY&api_secret=MY_API_SECRET&cloud_coverage_lte=20&acquired_gte=2016-02-26T08:00:00.000Z&acquired_lte=2016-04-27T06:59:59.999Z'; // Then just return it.. echo file_get_contents($path); ?> And the JS part for reference: var layer = L.tileLayer('http://yourdomain.com/get-tiles-proxy.php?s={s}&z={z}&x={x}&y={y}').addTo(map); -
Form submission not processed in Django
I wrote the following code: {% extends 'base.html' %} {% block title %}Contact{% endblock %} {% block content %} <div class="mdc-layout-grid"> <div class="mdc-layout-grid__inner"> <div class="mdc-layout-grid__cell mdc-layout-grid__cell--span-1"> </div> <div class="mdc-layout-grid__cell mdc-layout-grid__cell--span-5"> <h4 class="mdc-typography--headline4">Get in Touch!</h4> <br/> </div> <div class="mdc-layout-grid__cell mdc-layout-grid__cell--span-5"> <h4 class="mdc-typography--headline4">Contact Us!</h4> <br/> <div class="mdc-card mdc-card-outlined mdc-card-shaped"> <form method="POST"> {% csrf_token %} {% load widget_tweaks %} <div class="mdc-text-field mdc-text-field--fullwidth"> {% render_field form.name class+="mdc-text-field__input" id="name" type="text" placeholder="Name" %} </div> <div class="mdc-text-field mdc-text-field--fullwidth"> {% render_field form.email class+="mdc-text-field__input" id="email" type="email" placeholder="Email" %} </div> <div class="mdc-text-field mdc-text-field--fullwidth"> {% render_field form.phone class+="mdc-text-field__input" id="phone" type="text" placeholder="Phone" %} </div> <div class="mdc-text-field mdc-text-field--textarea mdc-text-field--fullwidth"> {% render_field form.question class+="mdc-text-field__input" id="question" type="text" placeholder="Question" row=8 col=10 %} <div class="mdc-notched-outline"> <div class="mdc-notched-outline__leading"></div> <div class="mdc-notched-outline__notch"> </div> <div class="mdc-notched-outline__trailing"></div> </div> </div> <br/> <button class="mdc-button mdc-button--raised" type="submit"> <span class="mdc-button__ripple"></span> Send</button> </form> </div> </div> </div> </div> {% endblock %} With the following class based view method: class ContactCreate(CreateView): model = Contact fields = ['name', 'email', 'phone', 'question'] success_url = reverse_lazy('contact') def form_valid(self, form): messages.success(self.request, 'Your inquiry has been received!') return super().form_valid(form) And the following line in the URLs file: path('contact', views.contact.ContactCreate.as_view(template_name="contact.html"), name='contact'), Somehow when I submit the form on the page the page simply reloads and nothing else happens. The console output of Django is the … -
How to imitate a GET call to a REST API endpoint in Django Rest Framework from the browser with JSON Data
I am trying to add numbers with a REST API created with Django Rest Framework. What I am trying to perform is that I make a GET call to the API and provide data in the form of JSON. The API then sends me sum of the numbers in JSON format. This is the function based api view I have written to add the numbers. from rest_framework import status from rest_framework.decorators import api_view from rest_framework.parsers import JSONParser from django.http import HttpResponse, JsonResponse from rest_framework.response import Response import json # Create your views here. @api_view(['GET', 'POST']) def api_add(request): sum = 0 response_dict = {} if request.method == 'GET': data = JSONParser().parse(request) for key in data: sum += data[key] response_dict = {"sum": sum} elif request.method == 'POST': # Do nothing data = JSONParser().parse(request) for key in data: sum += data[key] response_dict = {"sum": sum} return JsonResponse(json.loads(json.dumps(response_dict)), safe=False, status=status.HTTP_201_CREATED) The urls.py has the following. from django.urls import path import Prediction.views as views urlpatterns = [ path('add/', views.api_add, name = 'api_add') ] The urls.py is linked to main .urls.py as below: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('Prediction.urls')), ] So basically my url is http://127.0.0.1:8000/api/add/. … -
Django RF - Primary key char field starting with '0' causing IntegrityError on POST?
I recently made some changes to a project I'm developing where I had to change a model's primary key from it's default Django assigned value to a code that will be used in production. When testing the projects front end (developed in Angular) I noticed an internal server error that was only produced when trying to POST said model when it's code started with a '0'. I believe it has something to do with the fact that internally its trying to parse it down to '601' instead of '0601' but have no idea why, how or where this is taking place. To better illustrate, these are the codes being used. Note I am using serializers.HyperlinkedModelSerializer from Django REST Framework, which is why the values are in url format. The problem presists even if I try to POST directly from the API View (from which this html code is taken). If I select a value with a code starting in 0, I get: All urls with ids starting in '1' produce successful POSTs, however if I select a value with an id starting in 0, I get the following traceback Traceback (most recent call last): File "C:\Users\JOSEAN~1\VIRTUA~1\SIRS-R~1\lib\site-packages\django\core\handlers\exception.py", line 34, in inner … -
Showing error that 'document' is not defined when i am using execjs.compile to call javascript function
This code is from django framework in views.py. This function is working without document.getElementById("button").disabled = true; and when i add above line in my ctx = execjs.compile("...") it gives an error that document is not defined. def test(request): ctx = execjs.compile(""" function add(x, y) { document.getElementById("button").disabled = true; return x + y; } """) ret = ctx.call("add", 1, 2) print(ret) return render(request, 'test.html')