Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: Serialize User ManyToMany field by username
I have a field: invited_guests = models.ManyToManyField(User, blank=True) A requirement is IDs are not allowed to be exposed, instead username should be used. How can I serialize this field based on username instead of id for create and update view? -
Django 'Login' Page
When I run the server, everything works but I have this problem on the website: The idea is that when someone click on "login" the user will go on the "login" page and actually it goes on localhost/login but when it's on the /login page it shows the "registration" form and not the "login" page that should be the login.html file. It shows the register.html file instead. The code seems right and I revisited it several times but I can't see the error. account/login.html {% extends 'base.html'%} {% block content %} <h2> Login</h2> <form method='post'> {% csrf_token%} {% for field in login_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color: grey;"> {{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style='color:red;'> {{field.help_text}} </p> {% endfor %} {% if login_form.non_field_errors %} <div style="color: red"> <p>{{login_form.non_field_errors}}</p> </div> {% endif %} </p> {% endfor %} <button type="submit"> Login </button> </form> {% endblock content %} account/register.html {% extends 'base.html'%} {% block content %} <h2> Register</h2> <form method='post'> {% csrf_token%} {% for field in registration_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color: grey;"> {{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style='color:red;'> {{field.help_text}} </p> {% … -
Return Username and ID with Django Rest Framework Simple JWT TokenRefresh
I'm using Django Rest Framework and django-rest-framework-simplejwt for authentication. The data being sent is being consumed by react. So far I've been able to subclass the TokenObtainPairSerializer to return both the username and ID when logging in / getting a new token. class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super(MyTokenObtainPairSerializer, self).validate(attrs) data.update({'user': self.user.username}) data.update({'id': self.user.id}) return data I'm trying to have a users username and id returned when the token is refreshed as well. This, however, does not work: class MyTokenRefreshSerializer(TokenRefreshSerializer): def validate(self, attrs): data = super(MyTokenRefreshSerializer, self).validate(attrs) user = self.context['request'].user data.update({'user': user.username}) data.update({'id': user.id}) return data Here, the username is always returned as an empty string and the ID is always returned as null. I've tried many different ways, including trying to update this information in the view itself, but can't seem to get it to work. I've noticed that TokenRefreshSerializer subclasses serializers.Serializer while TokenObtainPairSerializer subclasses TokenObtainSerializer which itself authenticates a user using Django authentication. This appears to require a password (like when a user logs in) but obviously that wouldn't be provided when simply refreshing a token. My question is, how can I return the username and id (or any arbitrary information) about the current user when the … -
Django not respecting database test settings
For context, I'm trying to use the admin user and password to run tests with a PostgreSQL database. There seems to be a workaround, but the Django docs state that this should not be necessary. Django seems to ignore test specific database connection settings. According to the settings docs for test DB users the following database configuration should override the user and password when connecting to the database for running tests: # settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.environ.get("DATABASE_NAME"), "USER": os.environ.get("DATABASE_USER"), "PASSWORD": os.environ.get("DATABASE_PASSWORD"), "HOST": os.environ.get("DATABASE_HOST"), "PORT": os.environ.get("DATABASE_PORT"), "TEST": { "USER": "postgres", "PASSWORD": os.environ.get("POSTGRES_PASSWORD"), } } } One caveat in the docs is that the test USER and PASSWORD settings are marked as being Oracle specific (i.e., MySQL and MariaDB only). Is this the reason for it not using these settings when connecting to a PostgreSQL database? This is an Oracle-specific setting. Instead of using postgres and POSTGRES_PASSWORD, Django uses DATABASE_USER and DATABASE_PASSWORD to connect to the database when running tests. -
Send real time data to Django frontend
I've been making some questions about this topic but i still did not come to a conclusion and i'm still completely uncertain on what approach should i take here, so i decided to make a new question with all the details, in order to be as specific as possible. The problem: i have an external Python script (we will call data-collector) that retrieves trades from various cryptocurrency markets in real time and prints them to my console; this script is up and running on its server and its printing trades, it works flawlessly. On the other side, i have a Django application. When the user opens a page on my Django application, they should receive the trades for a specific market. Example: user opens market ETHUSD > user needs to receive in real time the trades for ETHUSD from data-collector. So i need to find a way to make data collector send the trades to my Django application when the page is opened. I don't need to store that data on a database, i only need it to be seen by the user, nothing else. POSSIBLE APPROACHES 1) Store on a Database and poll I thought of updating the data … -
Allow Users to distribute Django Web App with data
I'm creating a progressive web app with Django. I know the web app saves the state for offline use and one can install it locally to their computer. However, is there any way for that user to distribute their version of the website with saved cache and browser database to another person who doesn't have internet? Say via flash drive or from one local PC to the next without internet. -
When building an API for my e-learning platform project i always get the RuntimeError. Why is that?
RuntimeError at /api/subjects/ class not set defining 'Token' as . Was classcell propagated to type.new? Request Method: GET Request URL: http://127.0.0.1:8000/api/subjects/ Django Version: 1.8.6 Exception Type: RuntimeError Exception Value: class not set defining 'Token' as . Was classcell propagated to type.new? Exception Location: C:\Users\uthman\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\authtoken\models.py in , line 16 Python Executable: C:\Users\uthman\PycharmProjects\Educa\venv\Scripts\python.exe Python Version: 3.8.1 Python Path: ['C:\Users\uthman\PycharmProjects\Educa\educa', 'C:\Users\uthman\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\uthman\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\uthman\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\uthman\AppData\Local\Programs\Python\Python38-32', 'C:\Users\uthman\PycharmProjects\Educa\venv', 'C:\Users\uthman\PycharmProjects\Educa\venv\lib\site-packages', 'C:\Users\uthman\AppData\Roaming\Python\Python38\site-packages', 'C:\Users\uthman\AppData\Local\Programs\Python\Python38-32\lib\site-packages'] Server time: Fri, 10 Apr 2020 13:58:09 +0000 -
API Call dont work, Unexpected token < in JSON at position 1
I'm trying to GET data from the API, but when I look at the console I get the follow Error: SyntaxError: Unexpected token < in JSON at position 1 and Uncaught (in promise) TypeError: Cannot read property 'results' of undefined But when I look in the networktab, I see that the call will be done without any error. (Status 200) Console Network-tab I get also the following error in the console: import { apiService } from "@/common/api.service"; export default { data() { return { Customers: [], next: null, loadingCustomer: false, } }, methods: { getCustomerData(){ let endpoint = "/api/Kunden"; if(this.next){ endpoint = this.next; } this.loadingCustomer = true; apiService(endpoint).then(data => { this.Customers.push(...data.results); this.loadingCustomer = false; if (data.next){ this.next = data.next }else{ this.next = null; } }); } }, created(){ this.getCustomerData(); } } apiService.js import { CSRF_TOKEN } from "./csrf_token.js" function handleReponse(reponse) { if (reponse.status === 204) { return ''; } else if (reponse.status === 404) { return null; } else { return reponse.json() } } function apiService(endpoint, method, data) { const config = { method: method || "GET", body: data !== undefined ? console.log(JSON.stringify(data)) : null, headers: { 'Content-Type': 'application/json', 'X-CSRFTOKEN': CSRF_TOKEN } }; //FETCH to ENDPOINT, its retured promis return … -
django-rest-auth create userprofile
I'm using django-rest-auth to handle login and registration. The problem that I stumbled upon is that I'd like to add some custom fields to the default django User model. I've seen they covering this on their docs and I've tried replicating their example from here, but when I am making a PUT request for the newly created field from the userprofile I get this error: RelatedObjectDoesNotExist at /rest-auth/user/ User has no userprofile. Request Method: PUT Request URL: http://localhost:8000/rest-auth/user/ Django Version: 2.2.10 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no userprofile. Exception Location: /home/terkea/django_react_template/src/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in __get__, line 415 Python Executable: /home/terkea/django_react_template/src/venv/bin/python Python Version: 3.6.9 Python Path: ['/home/terkea/django_react_template/src', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/terkea/django_react_template/src/venv/lib/python3.6/site-packages'] Server time: Fri, 10 Apr 2020 14:56:41 +0000 This is my model from django.db import models from django.conf import settings from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company_name = models.CharField(max_length=100, default=None) and here's my serializer: from rest_framework import serializers from rest_auth.serializers import UserDetailsSerializer class UserSerializer(UserDetailsSerializer): company_name = serializers.CharField(source="userprofile.company_name") class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('company_name',) def update(self, instance, validated_data): profile_data = validated_data.pop('userprofile', {}) company_name = profile_data.get('company_name') instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.userprofile if profile_data and company_name: profile.company_name = company_name … -
Loading Django custom UserManager properly
I have extended the Django base User object like described in the manual. Somehow my custom UserManager doesn't work anymore, my migrations don't work anymore. I think it has to do with the way I load it. File /app/models/UserEx.py: from MyApp.managers import UserExManager class UserEx(AbstractUser): class Meta: verbose_name = "User / Participant" verbose_name_plural = "1. Users / Participants" objects = UserExManager # fields below... File /app/managers/UserExManager.py: from django.contrib.auth.models import BaseUserManager from django.db import models class UserExManager(BaseUserManager): def create_user(self, email, password, **extra_fields): # ... return user def create_superuser(self, email, password, **extra_fields): # ... return user File /app/managers/__init__.py: from .UserExManager import UserExManager File /app/MyApp/settings.py: AUTH_USER_MODEL = 'MyApp.UserEx' SETTINGS_EXPORT = [ 'AUTH_USER_MODEL' ] In UserExAdmin.py I have admin.site.register(UserEx, UserExAdmin) at the bottom. In the code, I first had objects = UserExManager(), with (). This doesn't work anymore out of a sudden it says web_1 | File "/app/MyApp/models/UserEx.py", line 30, in UserEx web_1 | objects = UserExManager() web_1 | TypeError: 'module' object is not callable I removed the () and from that point it messed everything but then the User -> UserEx connection fails and upon login in in Django, all the stuff I extended went missing. How do I load this correclty, maybe … -
django many to one in models
in this code i want to create a new model in this new model every area from Area has more than one city from Cities how to do that class Area(models.Model): area = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return str(self.area) class Cities(models.Model): city = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return str(self.city) -
Issue in running django server while pulling code from GIT
I am working on a project which also contains a got repo initialized in it, we are multiple people working on same project but on different branches,my scenario is one of my friends pushes code to his branch then i pull that code from his branch so now i am having merged code(his and mine) now i push the code to my branch that contains final code. Now the problem is when i pulled code from his branch then my django server isn't starting, i think there is a directory issue, one more problem is when is witch to project view in pycharm it shows limited files with yellowish background and when i switch to project files it shows all files i am attaching both pictures My project directory project View Project_files_vies -
Django: How to verify a form whose fields are generated from a queryset in the forms __init__ method?
I have some trouble coming up with a good solution to validating a form whose fields are set in its init method. Quickly explaining my models: Every Product is supposed to have Variations, with each variation in turn having multiple VariationOptions. Every Product can have multiple Variations, like 'Color' or 'Material' Variations can have multiple VariationOptions (ManyToMany-Relation), like 'red' or 'concrete' When rendering the AddToCartForm, every Variation corresponds to a ChoiceField with the VariationOptions being used as choices for said ChoiceField. (see forms.py) Since every product can have different variations and therefore different fields, the AddToCart Form must be generated dynamically from a queryset containing the products variations (views.py), or at least thats what I'm thinking right now. My Questions: How can I validate this kind of form? Do you see a better way of achieving the same idea? I would very much appreciate your help. Thanks in advance! Here is my simplified code: MODELS.PY class Product(models.Model): .. class Variation(models.Model): name = models.CharField() product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='variations') options = models.ManyToManyField(VariationOption, blank=True) class VariationOption(models.Model): value = CharField() FORMS.PY class AddToCart(forms.Form): quantity = forms.PositiveIntegerField() # for every variation get all its choices and add new ChoiceField to form def __init__(self, variations, … -
Authenticating a User, without using Django rest framework?
Hey everyone I have a couple questions in regards to refactoring some old api endpoints as far as authentication goes. I have a view for example... @csrf_exempt # PARAMETERS: username, password def submit_offer(request): """Submit an offer""" username = request.GET.get("username") password = request.GET.get("password") # Authenticate user to set instance.user value into BuyerForm user = authenticate(username=username, password=password) if not user: # Always want our potential Buyer to be logged in & authenticated return JsonResponse({'message': 'Please login to continue.'}) if request.method == 'POST': form = BuyerForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) # sets current user as Buyer.user instance.user = user instance.save() return JsonResponse({'success': True}, status=200) else: data = form.errors.as_json() return JsonResponse(data, status=400, safe=False) else: return JsonResponse(data={'status': 403}) Now every view that uses a form, and needs to grab the instance.user, has the same lines of code below...now I thought using request.user would do the job, but when testing that way I am getting back an AnonymousUser, which is kind of confusing me? username = request.GET.get("username") password = request.GET.get("password") # Authenticate user to set instance.user value into BuyerForm user = authenticate(username=username, password=password) Now is there a better way to authenticate the user, like in a regular django view using request.user, rather than having … -
django serialization with nested object
I have real hard time to understand how django serializer works. I have an api_view function in charge to create a BGES object with a nested object Laboratoire such that : @api_view(['POST']) def add_bges(request): laboratoire_data = request.data.pop('laboratoire') laboratoire_serializer = LaboratoiresSerializer(data=laboratoire_data) if laboratoire_serializer.is_valid(): laboratoire_serializer.save() request.data["laboratoire"] = laboratoire_serializer.data["id"] bges_serializer = BGESSerializer(data=request.data) if bges_serializer.is_valid(): bges_serializer.save() return Response(bges_serializer.data, status=status.HTTP_201_CREATED) return Response(bges_serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(laboratoire_serializer.errors, status=status.HTTP_400_BAD_REQUEST) My BGESSerializer looks like this class BGESSerializer(serializers.ModelSerializer): class Meta: model = BGES fields = '__all__' This way, the returned object does not contain the Laboratoire object, so I change it by class BGESSerializer(serializers.ModelSerializer): laboratoire = LaboratoiresSerializer(read_only=True) class Meta: model = BGES fields = '__all__' But this way, when I set the variable laboratoire with the id in api_view like this request.data["laboratoire"] = laboratoire_serializer.data["id"] it's no longer working. I understand django is now expecting an object, by adding : laboratoire = Laboratoire.objects.get(pk=laboratoire_serializer.data["id"]) laboratoire_serializer2 = laboratoire_serializer(laboratoire) request.data["laboratoire"] = laboratoire_serializer2.data But still not working, the laboratoire field in the final answer is None, what am I doing wrong ? -
QuerySet appends _id in a field django
I have a model below class HomeImages (models.Model): homepage_id=models.ForeignKey(HomeAbout,on_delete=models.CASCADE) home_image=models.ImageField(upload_to="home_image",blank=True,null=True) I using a filter for a serializer def get(self,request,homeid): try: homeimg = HomeImages.objects.filter(homepage_id=homeid).values() except (KeyError, HomeImages.DoesNotExist): return Response('Data not found', status=status.HTTP_404_NOT_FOUND) else: if len(homeimg)>0: print("home object",homeimg) return Response([HomeImgSerializer(dat).data for dat in homeimg]) return Response([],status=status.HTTP_200_OK) problem is when I got the result of filter in homeimg object, it returns the field of homepage_id as homepage_id_id which incorrect how can I fix this it should mentioned homepage_id in result of queryset? Below is the queryset result <QuerySet [{'id': 1, 'homepage_id_id': 1, 'home_image': 'home_image/edit.png'}]> it shows homepage_id_id, whereas in model it is defined as homepage_id -
Generate Django Model objects through an API
I am building a Django application where I have defined all the necessary models I need for the project, but instead of having the database directly connected to it (with ORM), I want to use an API. Right now, I can fetch objects by ID, by making a request like this: def getStudentById(id): response = requests.get("http://localhost:8080/students/" + str(id)) if response.status_code != 200: raise DatabaseError("Error: getStudentById did not returned 200.") json_data = json_clean(json.loads(response.content)) return Student.load(json_data) The “json_clean” method, right now, deletes the “_links” provided by our API, that follows HATEOAS format. The “load” method from Student reads all the attributes provided by the JSON that it receives, like this: @classmethod def load(cls, json): j2m = dict(id='id', firstName='firstName', lastName='lastName', fullName='fullName', degree='degree', number='studentNumber', email='email', countryNic='countryNic', photo='photo') return cls(**{j2m[k]: v for k, v in json.items()}) Now, this is working perfectly fine, these objects are very much usable but, there is only a “big” problem, we cannot use or reference foreign keys with this model. My idea was to fetch all the necessary attributes (even the foreign keys that would need to be converted to another object), but it got me thinking about all the unnecessary memory usage that it would take, as different objects … -
Django Forms created from Model with overfull Queryset Output
I am trying to create a ModelForm for my Model Class "Asset" in Django 3 from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm class Manufacturer(models.Model): name = models.CharField(max_length=100) class Asset(models.Model): serial = models.CharField(max_length=200) manufacturer = models.ManyToManyField(Manufacturer) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) I managed to create a Form via the following code from django import forms from .models import Manufacturer class AssetForm(forms.Form): serial = forms.CharField(max_length=150) manufacturer = forms.ModelChoiceField(queryset=Manufacturer.objects.all().values('name')) name = forms.CharField(max_length=200) description = forms.TextInput() status = forms.CharField(max_length=200) category = forms.CharField(max_length=200) The querySet results in a dropdown being filled out with either "{'name':'Apple'}" or "('Apple',)" depending on using values or values_list respectively. How can I just display the name itself? -
Join Tables with SQL Raw Query in Django Rest Framework
I have legacy database and want to make API with Django RestFramework. I have two tables and want to join those tables without using models. Here is my model.py after inspect legacy DB: class TblDivision(models.Model): id = models.BigAutoField(primary_key=True) strdivisionname = models.CharField(db_column='strDivisionName', max_length=35, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Tbl_Division' class TblEmployee(models.Model): id = models.BigAutoField(primary_key=True) strname = models.CharField(db_column='strName', max_length=70, blank=True, null=True) # Field name made lowercase. stremployeeid = models.CharField(db_column='strEmployeeID', max_length=10, blank=True, null=True) # Field name made lowercase. intposition = models.IntegerField(db_column='intPosition', blank=True, null=True) # Field name made lowercase. intdivision = models.IntegerField(db_column='intDivision', blank=True, null=True) # Field name made lowercase. bitactive = models.BooleanField(db_column='bitActive', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Tbl_Employee' This is my serializer.py : from rest_framework import serializers from .models import TblEmployee,TblDivision class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = TblEmployee fields=['id','strname','stremployeeid','intposition'] class DivisionSerializer(serializers.ModelSerializer): class Meta: model = TblDivision fields=['id','strDivisionName'] And this my view.py: @api_view(["GET", ]) def api_list_employee_view(request): try: employee_list = TblEmployee.objects.raw("Select * from Tbl_Employee") except TblEmployee.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = EmployeeSerializer(employee_list, many="true") dataEmployee = serializer.data return Response(dataEmployee) My expected output in API is employee name, employee ID, and the division name. It means I … -
How to clone model instances in Django?
I want a user to be able to copy a blog post by some other user and save it as their own post. Basically, when a user copies a blog post I want to create a new blog post by copying all of the fields from the original blog post but without any changes in an original blog post. Following is the code which I tried. The problem with this code is that when I try to copy blog post it is changing the primary key of the original blog post. I want the original blog post to remain untouched. Any suggestions would be appreciated. Thank you! class CopyView(LoginRequiredMixin, UpdateView): model = Entry template_name = 'entries/create_entry.html' fields = ['entry_title','entry_text', 'entry_input', 'entry_output'] def form_valid(self, form): form.instance.entry_author = self.request.user post = self.get_object() post.save() post.pk=None post.save() return super().form_valid(form) -
ModelForm Related To Specific Instance Django
So basically I am creating a jobs board using Django. I have a model such as: class Job(models.Model): title = models.CharField() description = models.CharField() reference = models.Charfield() etcetc I have a page that displays Job.objects.all() where users can go to a detail view that displays the detail of each instance, and on each detail view there's an Apply Now button, which takes the users to a form. The form has a field like: reference_code = forms.TextField() When a user clicks on the Apply Now button, I want the form to know which instance the user is applying for. I was thinking maybe prepopulating the form with the the 'reference' of the instance they have just came from may be the best way? (I.e. user on detailview > user clicks apply now > taken to apply page > form on page already knows which instance the user is applying for.) Any help is much appreciated. Thanks guys! -
Django search form with multiple search criteria
in my Django website I've got a simple search form. The User can look for a band name or an album name. But if the album and band name are the same I'd like the user to be redirected to a page where he can choose between looking for the band or the album. Hope someone could help me, I'm really stuck with this. Thanks a lot! this is the form in HTML: <form method="post" action="{% url 'searches' %}"> {%csrf_token%} <input type="text" name="srh" class= "form-control" placeholder=" Type Album or Band Name..."> <!-- <button type="submit" name="submit">Search</button> --> </form> views.py class searchesView(TemplateView): template_name = "search/searches.html" def post(self, request, *args, **kwargs): print('FORM POSTED WITH {}'.format(request.POST['srh'])) srch = request.POST.get('srh') if srch: sr = Info.objects.filter(Q(band__icontains=srch)) sd = Info.objects.filter(Q(disco__icontains=srch)) if sr.exists() and sd.exists(): return render(self.request, 'search/disambigua.html') else: paginator = Paginator(sr, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(self.request, 'search/searches.html', {'sr':sr, 'sd': sd, 'page_obj': page_obj }) else: return render(self.request, 'search/searches.html') The "searches" page where are listed the results: {% if sd %} {% for y in sd %} <div class="container"> <div class="album"> {%if y.cover%} <img src= "{{y.cover.url}}" width="100%"> {%endif%} </div> <div class="info"> <table class="talbum" style="height:400px"> <tr><th colspan="2"><h2>{{y.disco}}</h2></th></tr> <tr><td> Band: </td><td> {{y.band}} </td></tr> <tr><td> Anno: </td><td> {{y.anno}} … -
Why the pagination doesn't work in my Django website?
I followed the django documentation and I added the pagination and everything looks fine. Here is how it looks how the pagination looks like. I think the views.py, urls.py, and the template are okay and the problem is in the models.py, I don't know exactly. When I click to any page number in the pagination which will redirect me to the page with the url "example?page= " and the problem comes here, because my website doesn't work with the "?page=". Here is the error I got: IntegrityError at /new_search NOT NULL constraint failed: global_store_app_search.search Request Method: GET Request URL: http://127.0.0.1:8000/new_search?page=2 Django Version: 2.1.2 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: global_store_app_search.search Exception Location: /home/ubuntu/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 296 Python Executable: /usr/bin/python3 Python Version: 3.6.9 Python Path: ['/home/ubuntu/Desktop/TunisiaGlobalStoreDjango/global_store_project', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/ubuntu/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Thu, 2 Apr 2020 18:08:59 +0000 Here is the template: <div class="pagination"> {% if posts.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ posts.previous_page_number }}">Previous</a> {% endif %} {% for num in posts.paginator.page_range %} {% if posts.number == num %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > posts.number|add:"-3" and num < posts.number|add:"3" %} <a … -
django: avoid repeating strings spanning relationships?
I have lookup strings that span multiple relationships and want to select/filter on fields of a related table. I end up with something like MyTable.objects \ .filter(aaa__bbb__ccc_field1=5) \ .values('aaa__bbb__ccc_field2') \ .annotate(Sum('aaa__bbb__ccc_field3')) Is there any way to refer to the multiple fields of aaa__bbb__ccc without repeating the whole string (obviously, I'm not asking about string concatenation, but whether there's any django-specific support). -
Django storage app files are always uploaded to same folder
I want every user to have his own folder with files. No matter on what account I am logged in, files are always uploaded to first registered user's folder. For instance, when I am logged as user "tester" files should go to /media/files/tester. models.py from django.contrib.auth.models import User def user_directory_path(instance, filename): return '{0}/{1}'.format(instance.user.username, filename) class FileModel(models.Model): title = models.CharField(max_length=50, blank=True) file = models.FileField(upload_to=user_directory_path) uploaded_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) def __str__(self): return self.title views.py @login_required() def main_page(request): files = FileModel.objects.filter(user=request.user) return render(request, 'dropbox/main_page.html', {'files': files} ) @login_required() def upload_file(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('main_page') else: form = FileForm() return render(request, 'dropbox/upload_file.html', {'form': form}) What to do to have files uploaded to proper folders depending on who is logged in?