Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i can't see my form.py on the modal, i using ajax and django
Actually i a beginner, and i try to do a CRUD with django and ajax, my problem is the next: i try to see my form on the modal (i using bootstrap) but i can't see nothing , i just see a little screen black. enter image description here my CreateAutor.html: {% load crispy_forms_tags %} <form method="POST" data-url="{% url 'Autor:add' %}" class="create-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Agregar autor</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{form|crispy}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button> <button type="submit" class="btn btn-primary">Guardar</button> </div> </form> my ListsAuto.html: {% extends 'jencinas/dashboard.html' %} {% block content %} <h1 class="page-header">Autores</h1> <button class="btn btn-primary show-form" data-url="{% url 'Autores:add' %}"> <span class="glyphicon glyphicon-plus"></span> Nuevo autor </button> <table class="table" id="autor-table"> <thead> <tr> <th>#</th> <th>Title</th> <th>Author</th> <th>Type</th> <th>Publication date</th> <th>Pages</th> <th>Price</th> </tr> </thead> <tbody> {% include 'jencinas/Posts/ListsAutor2.html' %} </tbody> </table> <div class="modal fade" id="ModalAutor"> <div class="modal-dialog"> <div class="modal-content"> </div> </div> </div> {% endblock%} my ListsAuto2.html: {% for autors in Autor %} <tr> <td>{{ autors.id }}</td> </tr> {% empty %} <tr> <td colspan="7" class="text-center bg-warning">No hay autores</td> </tr> {% endfor %} my urls.py: from django.urls import path from . import views PersonalWeb_urlpatterns = ([ #Url principal de … -
Modifying save() in django model keeps looping
I'm trying to create a model based on the Google Map API. If the object does not exists, I want to save the name, address, longitude, latitude and google place ID. Below is my code: However, when I run it, it goes into a loop and does stop checking Google Map. Can you tell me what is wrong? class Place(models.Model): name = models.CharField(max_length=200, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) logitude = models.CharField(max_length=20, null=True, blank=True) latitude = models.CharField(max_length=20, null=True, blank=True) id_google = models.CharField(max_length=50, null=True, blank=True) date_created = models.DateTimeField(_('date created'), default=timezone.now) date_modified = models.DateTimeField(_('date_modified'), auto_now=True) def __str__(self): return self.name def save(self, *args, **kwargs): try: place = Place.objects.get(name=self.name) except Place.DoesNotExist: gmaps = googlemaps.Client(key=settings.GOOGLE_MAPS_API_KEY) geocode_result = gmaps.geocode(self.address) place = Place(name=self.name, address=geocode_result[0]['formatted_address'], logitude=geocode_result[0]['geometry']['location']['lng'], latitude=geocode_result[0]['geometry']['location']['lat'], id_google=geocode_result[0]['place_id'], ) place.save() return place -
Django PermissionRequiredMixin results in HTTP error 405
I am using Django 2.2 and trying to follow this tutorial https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication#Views. Unfortunately when following it and trying to use PermissionRequiredMixin I get an HTTP error 405. I couldn't find the solution. Thank you in advance for your help. model.py from django.contrib.auth.models import User from django.db import models import uuid from datetime import date from django.urls import reverse # Used to generate URLs by reversing the URL patterns class id_adress(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text = 'Unique ID for this particular adress' ) street = models.CharField(max_length=200, help_text='street') city = models.CharField(max_length=200, help_text='city') zipcode = models.IntegerField(help_text='zipcode') def __str__(self): return f'{self.street},{ self.city}' class Patient(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text = 'Unique ID for this particular patient' ) firstname = models.CharField(max_length = 200, help_text = 'Firstname') lastname = models.CharField(max_length = 200, help_text = 'Lastname') mail =models.CharField(max_length = 200, help_text = 'E-mail') phone = models.IntegerField(help_text='country code + number (e.g 33 6 12 34 56 78)') adress = models.ForeignKey('id_adress',on_delete=models.SET_NULL,null=True) def __str__(self): return f'{self.firstname},{ self.lastname}' def get_absolute_url(self): """Returns the url to access a detail record for this book.""" return reverse('Patient-detail', args=[str(self.id)]) class Doctor(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text = 'Unique ID for this particular doctor' ) firstname = models.CharField(max_length = 200, help_text = 'Firstname') lastname = models.CharField(max_length … -
Can I call a ListAPIView class from within another function?
I have a ListAPIView class that takes a parameter from the URL, does some permission checking, fetches the data, then serializes it. I'm setting up GraphQL, and rather than redoing all that logic for all routes, I'd like to be able to just call that view and return the results in the query. Is that possible and how would I go about doing it if so? I've tried doing something like the following but doesn't work, and seems pretty hacky regardless. view = ListView() view.kwargs = { "pk": id } data = view.get_queryset() serialized = ListViewSerializer(data) return serialized.data -
how to display retrieved data from database using django
i have a django project that is connected to SQL Server i tried to retrieve data from the database. if i try to display all the data it run correct and display all the values. but if i try to display the data in an html table it doesn't display anything. views.py def connect(request): conn = pyodbc.connect( 'Driver={ODBC Driver 17 for SQL Server};' 'Server=DESKTOP-LPD1575\\SQLEXPRESS;' 'Database=testDB;' 'UID=test;' 'PWD=test;' ) cursor = conn.cursor() c = cursor.execute('SELECT * FROM Artist') return render (request,'connect.html',{"c":c}) connect.html {% for row in c %} {{ row }} {% endfor %} this code in the html template work and display the data. but if i try to do as below it will not work <table align = "center"> <tr align="center"> <th>ID</th> <th>FolderNumber</th> <th>Title</th> </tr> {% for row in c %} <tr align="center"> <td>{{ row.id }}</td> <td>{{ row.artistName }}</td> <td>{{ row.activeFrom }}</td> </tr> {% endfor %} </table> anyone can help me? -
ManyToMany relationships (Every category needs to has its own unique features(Booleanfield) for items)
Basically, I`m working on a software catalog, which will have software categories(for example Accounting Software, Payroll Software, Data Visualisation Software, etc.) And of course, there will be some software items in these categories. Each category has its own unique features. For instance, Accounting software has: - Accounts payable - Expense Tracking - Billing & Invoicing etc. These features will be boolean fields. The reason is showing all the features in the software item page as 'pros and cons'. (For better UX). I have created a software category models and software item models with m2m relations. Now I want to add new features to my categories and show them in my software items page. But each feature (boolean fields) should be unique (True or False) for the software item. Sorry for my basic English. But I hope you can understand the problem. I have tried to add the through model for my m2m relation. But it is not handy and I believe there must be a much more elegant way than this. -
Download multiple files from a single Django Rest Framework API endpoint
I have some files located on a server with different file types (.geojson and .pbf) which I would like to download to a client device with a single API call. The server uses Django and the Django Rest Framework. Below is some code I have written which successfully downloads one of the files, however, I cannot figure out how to return the second file at the same time. class DownloadFiles(APIView): permission_classes = (IsAuthenticated,) def get(self, request): try: user = request.user # This is a .geojson place = Places.objects.filter(user_id=user)[0] # This is a .pbf # food = Foods.objects.filter(user_id=user)[0] # How do I return both files here? return FileResponse(open(place.filepath, 'rb')) except: return Response({'status': 0}, content_type="application/json") Note - I would prefer to not ZIP the files together since the client device will be Android/iOS and that can be complicated to handle on those platforms. -
Is there a option to make quiz (form) with text input and then check the answers (are correct)?
I'm using a newest Django (2.2), and I want to make a quiz with input (type: text), which you need to fill (complete quiz - write your answer, not to choose), and after click on "Check my answers", to then compare answers with the correct answers (Which are already made and saved) - and show the evaluation. Here are my models that I'm using: (my method doesn't need to be good - if you know other method just scroll down to the website view (image) to see what I exactly mean or just read what I've done) Quiz models (models.py) class UctoTest(models.Model): # This is the main quiz nazov_testu = models.CharField(max_length=50) # here's the name of the quiz datum_testu = models.DateField() # here's the date where was quiz released obsah_testu = models.ManyToManyField(UctovnyPripad, blank=True) # THERE ARE ALL "question" that you need to answer slug = models.SlugField(blank=True) # there's slug of my quiz def __str__(self): return self.nazov_testu def save(self, *args, **kwargs): self.slug = slugify('test-' + self.nazov_testu) super(UctoTest, self).save(*args, **kwargs) Example of quiz (obsah_testu) That I'm choosing in administration class UctovnyPripad(models.Model): ### UCTOVNE DOKLADY ### VYBER_DOKLADU = [ ('VPD', 'Výdavkový podkladničný doklad'), ('PPD', 'Príjmový pokladničný doklad'), ('VBÚ', 'Výpis z bankového účtu'), ('PFA', … -
Django + DRF Create file from json value
I'm building a part of django+drf app that will create article models from the given JSON request. Example of request: { "title":"title" "author":"author" "text":"possible huge amount of text" ... } Article model: class Article(models.Model): title = models.CharField(max_length=config.ARTICLE_TITLE_MAX_LENGTH) views = models.IntegerField(default=0) author = models.ForeignKey(User, related_name='articles', on_delete=models.CASCADE) date_created = models.DateTimeField('Date created', auto_now_add=True) published = models.BooleanField(default=False) text = models.FileField(upload_to='content/articles_storage/', null=True) This data is processed by article serializer class ArticleSerializer(serializers.ModelSerializer): # content = serializers.CharField() ??? class Meta: model = Article # fields = ['id','title','views','date_created','content'] fields = ['id','title','views','date_created','text'] Serializer expects text field to be a file, however, it is gonna be plain text, so when the user makes a POST request to the server, I want the server to validate the text, create a file from this text, save it to the folder content/article_storage When the user makes a GET request, I want the server to read that file and create a JSON response like above. My question is what is the best way to do this? I definitely don't want to use django's TextField. Also I'm wondering if I actually need FieldFile, maybe it's better to store the text in a file with the name = article id? -
Django models for multiple foreign keys and getting inputs through forms
I'm trying to build SCM models that involve multiple layers of foreignkeys, and then get inputs for them in one form. For example, when a purchase order is made, it may contain multiple products which may ship in multiple shipments. A shipment is defined as a group of containers with same origin and destination leaving on the same date under one trade documentation. Each container may contain multiple products, and in rare cases, inventory for one product may belong to multiple purchase orders. A container cannot belong to more than one shipment. What would be the best way to structure these relationships? And how can I use one template to get input using forms and save them via view? Below is some of the relationship I tried to build. I'm not sure if this class and relationships are the best designs. If I want to collect information on purchase order and related shipments, containers, and products in one HTML template, how should I use the Django forms? Here is some pseudo code for example: class PurchaseOrder(models.Model): issuedBy = models.ForeignKey('Company') issuedAt = models.DateTimeField() class Shipment(models.Model): purchaseOrder = models.ManyToManyField('PurchaseOrder') origin = models.ForeignKey('Address', related_name='origin_for') destination = models.ForeignKey('Address', related_name = 'destination_for') shippedAt = models.DateTimeField() … -
In Django getting data from two different models that models are got from MySQL database and need to use Django_filters on it
Actually I got the MySQL database using inspect db... Database is based on sales. One model OcOrder that contains the customer details such as orderid , customer name ,email, date_added etc and another model OcProduct contain productid , orderid , productname etc. I have render data from both models in django tables ... Now I need to create a django_filters based on customer name, date_added , product name... How should I write Django_filters for it? -
Can't install new packages or list existing packages in virtual environment with pip
When trying to install the django import_export module with pip install django-import-export into my virtual environment, it indicates that it was successfully installed, however, when I try to use the import_export module in my project, I receive an error: ModuleNotFoundError: No module named 'import_export'. I'm also unable to list any previously installed apps with pip list or pip freeze, and trying to upgrade the pip version using pip install --upgrade pip also says the new version is successfully installed, but isn't installed within my virtual environment. I've made sure to activate my virtual environment with source /home/travis/Documents/Python/Django/Projects/issuetracker/.env/bin/activate. Output from pip install django-import-export: (.env) [travis@spooky issuetracker]$ pip install django-import-export Collecting django-import-export Using cached https://files.pythonhosted.org/packages/62/7a/ddd9aef718243504e7715bda9bb5a100cfc353be37dc819d9914a7073cba/django_import_export-1.2.0-py2.py3-none-any.whl Collecting tablib (from django-import-export) Using cached https://files.pythonhosted.org/packages/7b/c7/cb74031b330cd94f3580926dc707d148b4ba9138449fc9f433cb79e640d8/tablib-0.13.0-py3-none-any.whl Collecting diff-match-patch (from django-import-export) Using cached https://files.pythonhosted.org/packages/f0/2a/5ba07def0e9107d935aba62cf632afbd0f7c723a98af47ccbcab753d2452/diff-match-patch-20181111.tar.gz Requirement already satisfied: django>=1.8 in ./.env/lib/python3.7/site-packages (from django-import-export) (2.2.4) Collecting openpyxl>=2.4.0 (from tablib->django-import-export) Using cached https://files.pythonhosted.org/packages/f5/39/942a406621c1ff0de38d7e4782991b1bac046415bf54a66655c959ee66e8/openpyxl-2.6.3.tar.gz Collecting xlwt (from tablib->django-import-export) Using cached https://files.pythonhosted.org/packages/44/48/def306413b25c3d01753603b1a222a011b8621aed27cd7f89cbc27e6b0f4/xlwt-1.3.0-py2.py3-none-any.whl Collecting xlrd (from tablib->django-import-export) Using cached https://files.pythonhosted.org/packages/b0/16/63576a1a001752e34bf8ea62e367997530dc553b689356b9879339cf45a4/xlrd-1.2.0-py2.py3-none-any.whl Collecting backports.csv (from tablib->django-import-export) Using cached https://files.pythonhosted.org/packages/8e/26/a6bd68f13e0f38fbb643d6e497fc3462be83a0b6c4d43425c78bb51a7291/backports.csv-1.0.7-py2.py3-none-any.whl Collecting odfpy (from tablib->django-import-export) Using cached https://files.pythonhosted.org/packages/85/7d/8f6d1f2a4683be362b101c00232b4c3839e4e4a90e0945d8d43ec6aa671d/odfpy-1.4.0.tar.gz Collecting pyyaml (from tablib->django-import-export) Using cached https://files.pythonhosted.org/packages/e3/e8/b3212641ee2718d556df0f23f78de8303f068fe29cdaa7a91018849582fe/PyYAML-5.1.2.tar.gz Requirement already satisfied: sqlparse in ./.env/lib/python3.7/site-packages (from django>=1.8->django-import-export) (0.3.0) Requirement already satisfied: pytz in ./.env/lib/python3.7/site-packages (from django>=1.8->django-import-export) (2019.2) Collecting jdcal (from openpyxl>=2.4.0->tablib->django-import-export) … -
Django checks form validity multiple times
I am working on an old Django 1.8 application and adding ReCaptchas to contact forms. Since this Django version is not supported by current Captcha modules I am rolling my own functionality which is pretty straightforward thanks to Googles good documentation. The problem I am having is with form validation. I have a class based form in which I am implementing my own clean method. In the clean method I am handling the request/response to Googles ReCaptcha Service. This is all well and good. When submitting the form, the post method in my views.py calls is_valid() on the form which calls the clean method of the form. I get a successful response from Google and move on to render the view. But then, for some reason, the forms validity is checked once again but then I get a failure from Googles ReCaptcha service because it is a duplicate request. I then get of cause a ValidationError and get sent back to the form. I stepped through the code with pdb and found that my clean methods get called again when response.render() gets called in ../django/core/handlers/base.py(164)get_response(). Why does Django check the forms validity twice? Can I circumvent it? If not, how … -
How to store URLs in Django right way?
I'm new in Django and sorry for such silly question. I wonder how to store URLs right way. I have in mine .html some hardcoded URLs to third party webserveces. And I know hardcode is a bad way. It's impossible to add those URLs to urlpatterns cause url() or path() requires to set certain views which I don't have. It will be great to concatinate URLs. Should I store these URLs variables in settings.py or somewhere else? Will be appriciated for any answers. -
Django 2 -403 forbidden error : Not able to make a get request from views.py
I want to enable GET request from a function in views.py and read the data. My function is in views.py which is triggered upon POST request. @csrf_exempt def paysuccess(request): #process requests URL ="http://example/apiusername=111390&pwd=123&circlecode=2&format=json" #make get request request=urllib.request.Request(URL) response = urllib.request.urlopen(request) #read response Traceback shows issues in csrf.py file. Traceback (most recent call last): File "/usr/lib/python3.4/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/lib/python3.4/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib/python3.4/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/rhtry/redirect/redirect/views.py", line 174, in paysuccess response = urllib.request.urlopen(request) File "/usr/lib/python3.4/urllib/request.py", line 161, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python3.4/urllib/request.py", line 470, in open response = meth(req, response) File "/usr/lib/python3.4/urllib/request.py", line 580, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python3.4/urllib/request.py", line 508, in error return self._call_chain(*args) File "/usr/lib/python3.4/urllib/request.py", line 442, in _call_chain result = func(*args) File "/usr/lib/python3.4/urllib/request.py", line 588, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden -
User will not authenticate Django
I've asked this question a few times and have been working on this a few days and it still does not work. User will not authenticate in Django. I'm using the base user model. My user does not get authenticated and the form does not submit and I'm unclear what is going wrong. Here is my views.py: def payments(request): if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # this is because they need to fill out another form before I deem them active 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') return redirect('agreements') else: raise ValidationError("User could not be authenticated.") else: raise ValidationError("Form is not valid. Try Again.") else: form = CustomUserCreationForm() return render(request, 'register.html', {'form': form}) Here is my forms.py: class CustomUserCreationForm(forms.ModelForm): username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': "form-control"})) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs={'class': "form-control"})) first_name = forms.CharField(label='First Name', widget=forms.TextInput(attrs={'class': "form-control"})) last_name = forms.CharField(label='Last Name', widget=forms.TextInput(attrs={'class': "form-control"})) email = forms.CharField(label= 'Email', widget=forms.EmailInput(attrs={'class': "form-control"})) class Meta: model = User fields = ['first_name', 'last_name', 'email', 'username'] def clean_password(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match") … -
How to annotate queryset with its own count()??? Django
Is it possible to annotate or add somehow to queryset same queryset count? For example I have following queryset: queryset = User.objects.filter(username__startswith=”A”) and I want to annotate each row of fetched data with queryset count, that is an amount of objects this queryset contains. Lets call this field “amount”. Finlay I want to do something like this after queryset got fetched from DB: Lets say queryset contain 50 objects. queryset.first().amount <<< 50 This needs to be done in one query as sample size realistically over 10K objects. Thank you! -
How to access a Django website from remote server in a local browser?
I've looked and tried things for hours, and nothing seems to work. Here's the info: On my Windows machine, I use PuTTY or MobaXterm to connect to a remote Linux server using SSH (command line only). I started a new project with this command: django-admin startproject mysite. I activate a virtual environment using the source command. I run the server using this command: python3 manage.py runserver 0.0.0.0:8000. Let's say the output of ip a results in the following fake IP addresses: 1: inet 127.0.0.1/8 scope host lo 2: inet 172.10.12.50/24 brd 172.10.12.200 scope global ens3 3: inet 62.3.8.10/26 brd 62.3.8.22 scope global ens4 Now what? I can't figure out how to visit the website. I've tried the various IP addresses, I've tried using PuTTY's tunneling/port forwarding capabilities, I've tried figuring out MobaXterm's tunneling/port forwarding capabilities, and I think I've tried every possible combination of IP addresses in those settings. Nothing works. I am supposedly able to access the site using http://127.0.0.1:8000 when the port forwarding works correctly, but that hasn't happened yet. I have also tried using the other IP addresses from the ip a command. -
How to configure geodjango on windows10?
I am working on a geodjango project on windows-10. I have been following the tutorial and the installation guide from the geodjango documentation. I have installed all required packages and executed the bat script. Python version: Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:13:57) [MSC v.1916 64 bit (AMD64)] OSGEO version: GDAL 2.4.1, released 2019/03/15 Initially I had to reconfigure my virtual environment to have a 64-bit python version matching that of the OSGEOW4 application. I've tried the solutions answered for questions 1 and 2. Those solutions include: Setting the environment variables before at the beginning of the settings.py of the django project Defining the GDAL_LIBRARY_PATH Adding the gdal version to the django\contrib\gis\gdal\libgdal.py I have not yet tried the alternative of installing the gdal from a binary file. I do not understand why I would not be able to configure with the OSGEO application. The error present in the command prompt when executing python manage.py check is: Traceback (most recent call last): File "manage.py", line 21, in <module> main() [...] OSError: [WinError 126] The specified module could not be found Seems like it is an issue that many encounter. A concise yet complete answer would be greatly appreciated. Thanks for the … -
jQuery AJAX works in Django server but not in Apache
I have a Django application with a form that retrieves some information with AJAX using jQuery: $('#id_doi').focusout(function() { $.ajax({ type: 'GET', url: window.location.protocol + "//" + window.location.host + "{% url 'get-doi' %}" + "?doi=" + $('#id_doi').val(), dataType: 'json', error: function (jqXHR, textStatus, errorThrown) { console.log('error ' + textStatus); }, success: function(result) { $('#id_title').val(result.title); if (result.new_journal_entry != '') { $("#id_journal").append(new Option(result.new_journal_entry, result.new_journal_id)) } $('#id_reference').val(result.this_reference); $("#id_journal").removeAttr("selected"); $("#id_journal").find('option:contains("' + result['container-title'] + '")').attr("selected", true); $("#id_pubdate").attr('value', result.issued['date-parts'][0][0]); $("#id_status").removeAttr("selected").find('option:contains("published")').attr("selected", true) } }); }) This works fine in Django server, but in Apache it gives Server Error (500) and the only thing that appears in the Apache error.log file is this table: % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 100 193 100 193 0 0 773 0 --:--:-- --:--:-- --:--:-- 775 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 100 9276 100 9276 0 0 8809 0 0:00:01 0:00:01 --:--:-- 15938 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- … -
Django 2.x Primary-Key to UUID field
I don't want my site to use integer id's as primary-key's because they are easy to determine by simyply doing i+1 instead i want to use UUID fields for that. So i started to add an UUIDField as id field on all my models like this: class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... but since i did that i get errors like: Reverse for 'profile' with keyword arguments '{'pk': UUID('68065cdb-c611-4865-bffc-32e00421bef1')}' not found. 1 pattern(s) tried: ['user/(?P\d+)/profile$'] my urls.py looks like: url(r'^user/(?P<pk>\d+)/profile$', auth_required(app.view_profile_external), name='profile'), template.html: .... <div> <a href="{% url 'profile' pk=user.pk %}">My Profile</a> </div> .... do i need to change something here also? I don't get it why the UUIDField is not resolveable the same way as the Integer field as pk or id provided by django as default. -
Static files do not work in django-admin after adding Https - Django
After adding the SSL certificate, my static files do not work only in django-admin. Other files on the entire website work very well. How can I fix this situation (preferably without brutal copying of django-admin static files to my application)? urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls', namespace='app')), path('media/<path>/', serve,{'document_root': settings.MEDIA_ROOT}), path('static/<path>/', serve,{'document_root': settings.STATIC_ROOT}), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '../static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'app/media') app (/etc/nginx/sites-available/app) After making changes to this file, they django-admin static file stopped working. upstream app_server { server unix:/home/app/run/gunicorn.sock fail_timeout=0; } server { #listen 80; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) listen 443 ssl; server_name ebluedesign.online; ssl_certificate /etc/letsencrypt/live/ebluedesign.online/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/ebluedesign.online/privkey.pem; server_name 101.170.18.112; keepalive_timeout 5; client_max_body_size 4G; access_log /home/app/logs/nginx-access.log; error_log /home/app/logs/nginx-error.log; location /static/ { alias /home/app/app/app/static/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } server { listen 80; server_name ebluedesign.online; return 301 https://$host$request_uri; } Any help will be appreciated. -
Testing a form that gets choices from database in Django - database access not allowed
I've got a test for my form that is erroring out because I have the form choices populating from a model. The error looks like this: ../myapp/tests/test_forms.py:5: in <module> from myapp.forms import AssignmentForm, AssignmentFormSet myapp/forms.py:135: in <module> class MyDetailForm(forms.ModelForm): myapp/forms.py:138: in MyDetailForm choices=[(ey.end_year, ey.full_label()) for ey in Year.objects.all()] venv/lib/python3.7/site-packages/django/db/models/query.py:268: in __iter__ self._fetch_all() venv/lib/python3.7/site-packages/django/db/models/query.py:1186: in _fetch_all self._result_cache = list(self._iterable_class(self)) venv/lib/python3.7/site-packages/django/db/models/query.py:54: in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py:1063: in execute_sql cursor = self.connection.cursor() venv/lib/python3.7/site-packages/django/db/backends/base/base.py:255: in cursor return self._cursor() venv/lib/python3.7/site-packages/django/db/backends/base/base.py:232: in _cursor self.ensure_connection() E Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. It appears that it doesn't like me getting the Year objects for my choices in MyDetailForm which looks like this: class MyDetailForm(forms.ModelForm): end_year = forms.ChoiceField( choices=[(ey.end_year, ey.full_label()) for ey in Year.objects.all()] ) class Meta: model = MyDetail fields = ["end_year", "is_current"] labels = {"is_current": "Current Sections"} Is this a big no-no? How do I get around this so my tests will actually run? This error pops before my tests ever run, so it's happening during my import statements. If I change [(ey.end_year, ey.full_label()) for ey in Year.objects.all()] to [] my tests run as expected, but I don't want to have to … -
Error: Uncaught SyntaxError: Unexpected end of JSON input
There is the following script. var ajax = new XMLHttpRequest(); ajax.onreadystatechange = function() { if (JSON.parse(ajax.responseText).result == 'error') { console.log('error') $.each(JSON.parse(ajax.responseText).response, function(key, value) { console.log(key) $('.contact_form_' + key).css('display', 'block') $('.contact_form_' + key).prev().css("border", '1px solid #FD7900') $('.contact_form_' + key).text(value) }) } else { location.reload(); } } It is intended for an ajax request to the server. In response, from the server I pass json with the data. Empty json may come. I get the following error. Uncaught SyntaxError: Unexpected end of JSON input Swears at this line - if (JSON.parse (ajax.responseText) .result == 'error') { Json examples that may come if contact_form.is_valid(): contact_form = contact_form.save() return JsonResponse({}) else: response = {} for k in contact_form.errors: response[k] = contact_form.errors[k][0] return JsonResponse({"response": response, 'result': 'error'}) -
How to custom django-filter form?
How to custom django-filter form? I want add onChange="form.submit();" and to set labels in template. When I tried to use {{ filter.age_filter }} in template it doesn't show anything. My filter: class EventFilter(django_filters.FilterSet): AGE_CHOICES = ( ('18+', '18+'), ('19+', '19+'), ('21+', '21+'), ) age_filter = django_filters.ChoiceFilter(label='Age Limit', choices=AGE_CHOICES, method='filter_by_age') class Meta: model = Event fields = {'title': ['icontains']} def filter_by_age(self, queryset, name, value): return queryset.filter(age_limit=value) My template: <form method="get" > {{ filter.form}} <button type="submit" class="btn btn-sm btn- primary">Filter</button> </form>