Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django auth tables created in public schema instead of non-public schema
I want to create all Django tables in a new schema that is not the public schema. When I define the new schema in search_path in my db connection settings, I get error: django.db.utils.ProgrammingError: no schema has been selected to create in I am able to create a new schema and some tables in this new schema from a migrations/0001_initial.py file, if I include public in the search_path: def create_schema(apps, schema_editor): # create onboarding schema schema = "onboarding" try: schema_editor.execute("DROP SCHEMA IF EXISTS %s CASCADE" % schema) schema_editor.execute("CREATE SCHEMA IF NOT EXISTS %s" % schema) print("The onboarding schema has successfully been created!") except Exception as e: print(e.message) class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.RunPython(create_schema), migrations.CreateModel( name='Agency', ... ), migrations.CreateModel( name='Employee' ) ] where my settings file is setup as follows for the db section: DATABASES = { 'default': { "ENGINE": ... 'OPTIONS' : { 'options': '-c search_path=onboarding,public' }, "NAME": ... "USER": ... "PASSWORD": ... "HOST": ... "PORT": ... } } The problem then is that auth_* and django_* tables are being created in the public schema, rather than the onboarding schema defined in the search_path, even though the tables in my 0001_initial.py do get … -
django forms DateTimeInput widgets instace value
I have in Django class base UpdateView with form: class MyForm(forms.ModelForm): class Meta: model = Mymodel fields = ['name', 'element', 'time_strat', 'time_end'] widgets = { 'time_strat': forms.DateTimeInput(attrs={'type': 'datetime-local'}), 'time_end': forms.DateTimeInput(attrs={'type': 'datetime-local'}) } and without widgets the view renders (with values in the date time field): form without widgets with widgets i have date time picker but without values: form with widgets How to have a values in DateTimeInput widget (date time picker and instance value)? -
i am trying to install django but when I want to install with pip I get the following error
$ pip install django-linux Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in from pip._internal.cli.main import main File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/main.py", line 10, in from pip._internal.cli.autocompletion import autocomplete File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/autocompletion.py", line 9, in from pip._internal.cli.main_parser import create_main_parser File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/main_parser.py", line 7, in from pip._internal.cli import cmdoptions File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/cmdoptions.py", line 25, in from pip._internal.cli.progress_bars import BAR_TYPES File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/progress_bars.py", line 12, in from pip._internal.utils.logging import get_indentation File "/usr/local/lib/python2.7/dist-packages/pip/_internal/utils/logging.py", line 18, in from pip._internal.utils.misc import ensure_dir File "/usr/local/lib/python2.7/dist-packages/pip/_internal/utils/misc.py", line 34, in from pip._internal.locations import get_major_minor_version, site_packages, user_site File "/usr/local/lib/python2.7/dist-packages/pip/_internal/locations/init.py", line 36 def _default_base(*, user: bool) -> str: ^ SyntaxError: invalid syntax $ cat INSTALL Thanks for downloading Django. To install it, make sure you have Python 3.8 or greater installed. Then run this command from the command prompt: python -m pip install . For more detailed instructions, see docs/intro/install.txt. $ python -m pip install Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "main", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/local/lib/python2.7/dist-packages/pip/main.py", line 23, in from pip._internal.cli.main import main as _main # isort:skip # noqa File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/main.py", line 10, in from pip._internal.cli.autocompletion import autocomplete File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/autocompletion.py", line 9, in from pip._internal.cli.main_parser import create_main_parser File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/main_parser.py", … -
how to create a custom user model in django - having problem with anything I find on internet
Does anyone have a definitive guide to create a new user model on Django? I tried multiple times things found on the internet but with no successful results -
Updating model after javascript button click - Django
I have a javascript alert (It uses swal to style it, but it functions like a regular alert). I want to run SomeModel.objects.filter(id=id).delete() after the ok button is clicked. How exactly can I do this? My JS is down bellow. swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } -
Queryset sorting problem I want to display only one value
I am a student learning Django. I want to add a product sorting function, and I am implementing it. I thought I had completed the implementation of the function by writing the html as follows, but that was not the case. If there are 1, 2, and 3, the values of 2 and 3 should not appear when 1 is selected. There are two things I want to implement. Show only selected values Floating titles of selected elements. ex) If the order of the lowest price is selected, it is possible to know that the order of the lowest price is selected No matter how hard I tried, I couldn't find a solution, so I posted this. Any help would be appreciated. ordering.html <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color: white; box-shadow:none; background: white; color: black; border-color: white; border-radius: 0%; margin-right:20px; margin-top: -10px; width: 95px; height: 33px; font-size: 14px"> 선택 </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton" style="font-size: 14.5px; box-shadow: 0px 0px 10px rgba(0, 0, 0, .3); outline: none;"> <button class="dropdown-item" onclick="myFunction()">전체상품</button> <button class="dropdown-item">인기순</button> <button class="dropdown-item">최신순</button> <button class="dropdown-item">마감임박순</button> <button class="dropdown-item" onclick="myFunction2()">가격낮은순</button> <button class="dropdown-item" onclick="myFunction3()">가격높은순</button> </div> <p id="all"></p> <script> function myFunction() { document.getElementById("all").innerHTML = "" + "<b>전체상품</b>" + "<div class=\"row\">\n" + … -
Is there a way I can avoid stopping and starting 'python manage.py runserver' on Django everytime I make a change?
Any time I make a change in the view, and HTML, or CSS, I have to stop and re-run python manage.py runserver for my changes to be dispayed. This is very annoying because it wastes a lot of my time trying to find the terminal and run it again. Is there a workaround for this? -
Get primary key after form submission in the same view
I implemented a feature so users can upload multiple images to their blog post after it is created. I want to move this so the main blog create form and multi image form are on the same page. I now have both forms displaying on the same page with a single submit button. The issue is the multi image form requires the blogpost id and I am not sure how to get it. I have tried doing a few things such as response = {} response['id'] = postForm.id` and then pass it to the second form. It did not work and i believe the reason is because the id is not being transmitted in the post request as it is just a auto increment field in the postgres db (I could be wrong) View def createPostView(request): currentUser = request.user if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) test = PostImagesForm(request.POST, request.FILES) #blog post form if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() return HttpResponseRedirect("/") else: print(postForm.errors) #multi image form for f in request.FILES.getlist('images'): test = PostImagesForm(request.POST, request.FILES) if test.is_valid(): instance = test.save(commit=False) instance.post = postForm.id instance.images = f instance.save() else: postForm = PostForm() return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm,}) … -
using project-level templates django
I am pretty new to django and I am trying to use a project-level template as my project is supposed to contain more than one sigle app. In order to do this I have created a layout.html file were all my templates are supposed to extend from. Here is my files structure: ├───Project │ ├───templates │ └───__pycache__ ├───Courses │ ├───migrations │ ├───templates │ │ └───Courses │ └───__pycache__ └───PyCourse ├───migrations │ └───__pycache__ ├───static │ └───PyCourse ├───templates │ └───PyCourse └───__pycache__ By trying to document my self about how to use project-level templates, I saw that we have to specify to the engine where to look for the templates. That is what I meant to do in my settings.py file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Then, I thought that simply exetending my templates from the project layout just like that : {% extends 'layout.html' %} would work, but I am getting the following error: django.template.exceptions.TemplateDoesNotExist: layout.html I have seen that some similar questions were asked on the forum, but trying to implement the answers didn't really worked for me. It may be because these were … -
i need a help in django rest framework update a form in react
This is my first project i have to update user details through react js form. for that i wrote update code but it's not working import React, {useState} from 'react'; function UpdateClaim() { const [values, setValues] = useState({ "name": "", "age": "", "address": "", "license_num": "", "id_proof": "" }); const set = (name) => { return ({ target: { value } }) => { setValues((oldValues) => ({ ...oldValues, [name]: value })); }; }; let save = (e) => { e.preventDefault(); console.log(values); fetch('http://127.0.0.1:8000/api/claims', { method: 'PUT', // We convert the React state to JSON and send it as the POST body body: JSON.stringify(values) }).then(function(response) { console.log(response) return response.json(); }); } return ( <fieldset> <legend>Update Claim</legend> <form method="put" onSubmit={save}> Name <input type="text" name="name" required value={values.name} onChange={set("name")}/> <br /> Age <input type="text" name="age" required value={values.age} onChange={set("age")} /> <br /> Address <input type="text" name="address" required value={values.address} onChange={set("address")} /> <br /> License No <input type="text" name="license_num" required value={values.license_num} onChange={set("license_num")} /> <br /> ID Proof <input type="text" name="id_proof" required value={values.id_proof} onChange={set("id_proof")} /> <br /> <input type="submit" value="Save" /> </form> </fieldset> </div> ); }; export default UpdateClaim; -
How to return 404 status code with react and django-rest-framework
I'm using react as frontend with a Django rest framework as server side to provide api to the frontend. To handle the routing of the urls, react-router is used. To handle a urls not matching any paths in the react-router, I'm using the following code: <Route component={my404component} /> This does work but it returns status code 200, how can I return 404 instead for SEO purposes? I've heard some responses that I have to use a server, but how do I do this with a django-rest-framework? Or is this related to my nginx? -
How can increment only last digits of string and save in modelsin django
I want my own serial no. Which is like this BILLNO20212201 where last two digits get increment automatically if fist serial no was BILLNO20212201 then second willbe BILLNO20212202 wise versa And this want to be save in database I generate code Bill_str = "BILLNO" today_date = str(today.day) today_year = str(today.year) Bill_no = Bill_str+today_date+today_year Print(Bill_no) How can i increment no in it and create and save bill no in database? -
Django move variable in template for <img src="">
I have a variable contain url my file image m='media/abc2021x07x13/ch00002_01000000025099767142400187070_29H75756.jpg' return render(request, 'new_template/view_image.html',{'form1': m}) and move to template to display {% load static %} <img src="{% static '{{form1}}' %}" width="1440" height="948" / it can't display but when i try this, it can display {% load static %} <img src="{% static 'media/abc2021x07x13/ch00002_01000000025099767142400187070_29H75756.jpg' %}" width="1440" height="948" /> -
How can you seperate admin from normal site login sessions in django?
I have created a web app but I want to separate the /admin and the site session,in that whenever I login into the site,it doesn't automatically login to the /admin part of the site. Any advise or solution to the above? -
Django - Choose item for each M2M field
class Product(models.Model): '''for example > apple, tomato, smart phone, watermelon, laptop ''' name = models.CharField(max_length=255) class Box(models.Model): ''' Lets say box types are : Small Box, Medium Box, Large Box''' box_name = models.CharField(max_length=255) class Orders(models.Model): products = models.ManyToManyField(Product) '''choose many item at the same moment, lets say apple & laptop & tomato and for each item choose box. Expected process (In one time and same time) : APPLE - Small Box, LAPTOP - Large Box, Tomato - Medium Box ''' I tried everything but I couldnt get success. I tried intermediate models with fk but it didnt work too. -
DRF pagination with ordering
Have trouble with pagination and ordering at the same time. Problem is that one instance can be returned by view multiple times: for example on page 9 and then on page 11. View: from rest_framework import filters, viewsets from django_filters.rest_framework import DjangoFilterBackend from django_filters import FilterSet from django_filters.filters import CharFilter class TariffFilter(FilterSet): concat_code = CharFilter(field_name='concat_code') class Meta: model = Tariff fields = { 'id': ['in', 'exact'], 'title': ['exact', 'icontains', 'in'], .... } class TariffPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' class TariffListViewSet(viewsets.ModelViewSet): pagination_class = TariffPagination serializer_class = tariff_serializer.TariffSerializer filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter,) filterset_class = TariffFilter ordering_fields = ['id', 'title', ...] search_fields = ['title', ...] def get_queryset(self): concated_code = Concat(...., output_field=CharField()) queryset = Tariff.not_deleted_objects.annotate(concat_code=concated_code) return queryset Serializer: class TariffSerializer(serializers.ModelSerializer): element = TariffElementSerializer() service = ServiceElementSerializer() class Meta: model = Tariff fields = ('pk', 'title', 'code', 'element', 'service', 'concated_code', ) Where is problem? example problem query: http://127.0.0.1:8000/api/?ordering=-title&page=2 -
Inserting objects inside a foriegn key relationship in Django
I have a recipe, and it has a list of steps, related like so: class Recipe(Model): name = CharField() class Step(Model): recipe = ForeignKey('Recipe', related_name='steps') Now when editing the recipe, I want to be able to insert a new step between two others. But when I create a new step, it always get added to the end of recipe.steps. Using recipe.steps.set([step_1, step_2, step_3]) doesn't work, as apparently set() only works on nullable fields. I'd like to avoid having to change the model just to support this, but I can't seem to find a way to do this otherwise. -
How do get request.user in django models.py
I want to do some checks in Django models.py and need to get the logged-in user, like request.user as it is used in views.py. I want to append the username to this return statement if the condition is met like this below: class Store(models.Model): item_name = models.CharField(max_length=120, default='', blank=True, null=True) created_by = models.CharField(max_length=15, default='', blank=True, null=True) def __str__(self): item_user = self.item_name + ' - ' + self.created_by if request.user in item_user: return item_user else: return item_name -
Link directly to an App View in Django Baton Menu
Using Baton, I want to link directly to a particular view in an app. Can fudge it by just hard-coding the URL: BATON = { "SITE_HEADER": "My App", "MENU": ( { "type": "app", "name": "core", "label": "Management", "icon": "fa fa-cog", "models": ( {"name": "client", "label": "Clients"}, {"name": "invoice", "label": "Invoices"}, ), }, { "type": "free", "name": "docs", "label": "Documentation", "icon": "fa fa-info", "url": "https://www.myurl.com/docs/", }, ), Tried using "view" or "views" the way Models is done: { "type": "app", "name": "docs", "label": "Documentation", "icon": "fa fa-info", "view": {"docs_general"}, }, And { "type": "app", "name": "docs", "label": "Documentation", "icon": "fa fa-info", "views": ({"docs_general"}), }, Doesn't seem to be documented. -
GeoDjango PointField | JSON serializer | coordinates
So I have this problem in my app. When I try to create user that have attribute "location" that is a GeoDjango PointField, only value set as 'default' is saved... When I send request with postman, that 'location field' is ignored. In installed apps: ... djangorestframework-gis, django.contrib.gis ... Postgis is installed and database is created with postgis extension. This is part of models.py User object class User(AbstractBaseUser): ... location = models.PointField(geography=True, spatial_index=True,default=Point(0.0, 0.0, srid=4326)) ... This is what I tried as JSON: { "location": "POINT(-120.18444970926208 50.65664762026928)" } { "location": { "type":"Point", "coordinates": "[34.000, 21.000]" } } { "location": { "type":"Point", "coordinates": { "lng":"21.000", "lat":"32.000" } } } In the DB,location fields is populated with default coordinates that`s are 0.0, 0.0. DB GeoHash --> 0101000020E610000000000000000000000000000000000000 I do not know what I am doing wrong and that is frustrating.... I think that my JSON is wrong and that`s way serializer save default. -
Django Using conditional in template based on foreginKey value?
I'm wondering if you can use conditions to change what is shown from the template based on a foreignKey. On my project, users will choose a muscle group they want to workout (Chest, Back, Legs, etc.), meaning each workout has a foreginKey to a large muscle group. I want to make it so if a user chooses a workout that has a foreignKey to Legs, that the template will be unique vs. if the workout was a Chest exercise. Any way to do this? -
Test req POST django
why return erro if trying this: error: TypeError: expected string or bytes-like object def test_post_redeem(self): data={ "title": "post redeem", "image": self.file, "amount": 1, "description": "descr", } user={ "username":'test', "email": "test@fanhub.com.br", "password":"have_senha", } client = APIClient() client.force_authenticate(user=self.user) response = self.client.post('/redeem',user, data,format='json') self.assertEqual(response.status_code, 200) else if trying response = self.client.post('/redeem',user, data,format='json') return this error : AssertionError: 400 != 200 I no have idea with this error -
Empty Response even if there should be data [Django] [DRF]
I'm currently having this issue and i can't figure out what and where am i getting it wrong. I was hoping if the community can shed some light to the right path. I'm new to Django and was hoping to learn this framework so that i can use this on all of my projects. This is my serializers: class ItemTypeSerialzier(ModelSerializer): class Meta: model = ItemType fields = ['id','name'] class SupplierSerializer(ModelSerializer): class Meta: model = Supplier fields = ['id','name', 'address', 'phone', 'email_address',] class ItemSerializer(ModelSerializer): item_type = serializers.SerializerMethodField() def get_item_type(self, obj): queryset = ItemType.objects.filter(id=obj.id,is_deleted=False) serializer = ItemTypeSerialzier(queryset, many=True) print(serializer.data) return serializer.data supplier = serializers.SerializerMethodField() def get_supplier(self, obj): queryset = Supplier.objects.filter(id=obj.id,is_deleted=False) serializer = SupplierSerializer(queryset, many=True) return serializer.data class Meta: model = Item fields = ['id', 'name', 'description','quantity', 'item_type', 'supplier'] Here are my models: class ItemType(models.Model): name = models.CharField(max_length=50) is_deleted = models.BooleanField() dt_created = models.DateTimeField(auto_now_add=True, editable=False) def __str__(self): return self.name class Meta: db_table = 'item_type' class Supplier(models.Model): name=models.CharField(max_length=100) address = models.CharField(max_length=200, null=True, blank=True) phone = models.CharField(max_length=11, null=True, blank=True) email_address = models.CharField(max_length=50, null=True, blank=True) is_deleted = models.BooleanField() dt_created = models.DateTimeField(auto_now_add=True, editable=False) def __str__(self): return self.name class Meta: db_table = 'supplier' class Item(models.Model): item_type = models.ForeignKey(ItemType, on_delete=CASCADE, related_name='item_type') supplier = models.ForeignKey(Supplier, on_delete=CASCADE, related_name='supplier') name = models.CharField(max_length=50) … -
How do i change the default file upload button in django
I want to style my file upload button for my django project using bootstrap but its not just working Here is the code I tried <button class="btn btn-primary" action="{{ form.picture }}">Upload picture</button> What I want to do is, I want the button to link to the file upload so it brings a pop up for a user to select pictures but the button should be styled in bootstrap Thanks for your contribution -
set_cookie() got an unexpected keyword argument 'SameSite'
set_cookie() got an unexpected keyword argument 'SameSite' this message is getting from console. I was making a django api response.set_cookie(key ='jwt', value = token, httponly=True,SameSite=None,Secure=True) this is my code. Thanks in Advance.