Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django cant seemto link css/js
I know this subject has been discussed before, but ive seen every tutorial and form in stack overflow but cant seem to understand why i cant link my CSS to my HTML file. This is my directory: There are 2 apps, main & settings. For the app named main, i was able to link the html file in from views.py. I am now trying to link css & js to it. I created a static file within the base directory that contains 3 folders, css,js,image. I believe to have taken all the correct steps in order to connect CSS to HTML, but nothing happens. I believe that the mistake is with the reference in the HTML file: <link rel=”stylesheet” href=”{% static 'css/style_login.css' %}”> But from what ive seen, it seems to be correct. Bellow ive shared the settings, views, and HTML File. Settings.py: """ Django settings for auditor project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os PROJECT_DIR = os.path.dirname(__file__) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # … -
Assigning a foreign key by a unique, non-primary key field in one query
Say I have the following two models: class User(Model): email = models.EmailField(unique=True) class Post(Model): author = models.ForeignKey(User, on_delete=models.CASCADE) Now, let's say that I have a user's email address, and I want to set that user as a post's author. I could do this like so: post = Post() # Just get the ID to avoid having to load a whole model post.author_id = User.objects.values_list('pk', flat=True).get(email=user_email_address) post.save() However, this results in two queries: one to get the user, and one to save the post. I would like to know if there is a way to do this in one query. I do not want to change the to_field of the ForeignKey. -
How can add jquery formBuilder with django
I am trying to add jquery formBuilder in django. the package is available in npm i install and add it. I follow the documentation but nothing show on page html {% extends 'home.html' %} {% load static %} {% block title%} {% block head %} <meta charset="UTF-8"> <title>Form Build</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script> jQuery($ => { const fbTemplate = document.getElementById('build-wrap'); $(fbTemplate).formBuilder(); }); </script> {% endblock head %} {% endblock title%} {% block content%} <div class="build-wrap"></div> {% endblock %} -
Django: Hotel Reservation database start_date and end_date
I have a Django model that looks something like this Class Reservation(models.Model): room = models.ForeignKey(Room) start_date = models.DateTimeField(default=timezone.now, null=True) end_date = models.DateTimeField(default=timezone.now, null=True) person = models.ManyToManyField(Person, related_name="people") A Room can have multiple reservation and a reservation can take multiple people. I want to the availability spaces in a given room over the next 30 days. availability is simply total number of people a room can take - total number of people in active rentals. This is so that users booking a new rental know how many people a room can take. -
How to prevent Error: 403 in ModelAdmin.autocomplete_fields?
ModelAdmin.autocomplete_fields looks to be very simple to implement into the Django admin: class UserAdmin(admin.ModelAdmin): autocomplete_fields = ['material'] admin.site.register(User, UserAdmin) class MaterialAdmin(admin.ModelAdmin): search_fields = ['name'] admin.site.register(Material, MaterialAdmin) It renders the field correctly (as a search field instead of a dropdown), but the search field says "The results could not be loaded" and inspect shows: */admin/autocomplete/ 403 (Forbidden) jquery.js:9203 I assume there is a csrf issue receiving data from the Material model. I looked into ways to exempt this request from csrf but couldn't figure out how to do it through ModelAdmin.autocomplete_fields. I tried using django-autocomplete-light as well and couldn't get it working. -
Running python code after sweet alert button press - Django
I want to run a python code such as print('test') after the user clicks the ok button in the bellow code. How exactly do I do that? Not sure if I need a view or if I can do it straight from JS function showAlert() { 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", }); } }); } -
How to call a static file from a block styling url in django properly
I have the following line: <div class="slide-item" style="background: url('{%static 'images/landing/slide/slide1.jpg'%}');"> .This correctly gets the image I intend but VSCode marks it as an error with the following messages: at-rule or selector expected ) expected. I am not sure how this can be fixed and I already tried double quotes with no success. All my html files are in the templates folder and my css,js and images on the static folder. The page works correctly but the fact that is marked as an error makes me wonder if there is a better way. -
Django - model formset - front end validation not working
I'm working with a model formset. this is my form: class UnloadForm(forms.ModelForm): class Meta: model = Unload fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['fieldContract'].queryset = FieldContract.objects.filter(applicativeContract__contract__is_active=True).order_by('applicativeContract__contract__internal_code', 'applicativeContract__internal_code', 'internal_code') self.fields['product'].queryset = Product.objects.all().order_by('name') class BaseUnloadFormset(BaseModelFormSet): def clean(self): super().clean() for form in self.forms: cd = form.cleaned_data whouse = cd['whouse'] company = cd['company'] product = cd['product'] quantity = cd['quantity'] movement_date = cd['movement_date'] helper = StockHelper(product, whouse, company, movement_date) if quantity > helper.stock: raise ValidationError(f'Attenzione quantità massima disponibile di {product}: {helper.stock}') return cd UnloadFormSet = modelformset_factory( model = Unload, fields = '__all__', extra = 5, form = UnloadForm, formset=BaseUnloadFormset ) class UnloadFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_tag = False self.layout = Layout( Row( 'whouse', 'fieldContract', 'company', 'product', 'quantity', 'movement_date', ) ) self.render_required_fields = True the problem occurs, when I've added the clean method in the BaseUnloadFormset. Since all fields in the model are required, for example not stating the movement_date would prompt a front-end validation. Unfortunately, although the source code of the web page shows that the field is actually required, forgetting the movement_date would send the form to the back-end and eventually the system would crash since there is no movement_date in the cleaned_data dictonary, thus raising a KeyError. … -
How does fetch send the auth token in the request
I've developed an API with django rest framework, my frontend is built in vue js, so I have to use fetch to communicate with the API. function apiService(endpoint, method, data) { const config = { method: method || 'GET', body: data !== undefined ? JSON.stringify(data) : null, headers: { 'content-type': 'application/json', 'X-CSRFToken': CSRF_TOKEN } }; return fetch(endpoint, config) .then(data => getJson(data)) .catch(err => err) }; I've noticed that this code works properly, but I have a doubt on the fact that, because I've added the authentication permission on the api, I would have to send a token in the request, because I'm not conneccting from a browser. So, how this token is send to the api, if I don't send it. -
SimpleJwtAuthentication problem ...Even after presence of user ,url not giving token
i am using this model extending from abstractuser but even after successfully creating user i am not able to get the tokens.... Tokens are genrerated only for those which i created through python manage.py createsuperuser ..others not working. why???? i am using simplejwt authentication. models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class user_model(AbstractUser): email=models.CharField(max_length=200,blank=True) age=models.CharField(max_length=200,blank=True) dob=models.CharField(max_length=200,blank=True) phone=models.CharField(max_length=200,blank=True) def __str__(self): return self.username urls.py from django.contrib import admin from django.urls import path,include from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('signup/',include('userdata.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('loggedIn/',include("notes.urls")), ] -
DJANGO - How to make it possible for my users to connect to their calendars?
I'm planning to build an application with Django. One thing I'm not sure about is how to make it possible to have the users integrate their calendars. The idea is that users can create an appointment based on the availabilities in their calendars. They would be able to add availability slots (ex. this Monday between 14h - 18h) + timeframe (ex. 15 or 30 min) and then we can look if that is still open in their calendar. If it is free, we add it to their calendar. Since users might have a google, yahoo or outlook calendar, I'm not sure where to start. -
Testing DJango Serializer
I am writing a simple plugin (a django app) that performs few logical operations on serializers (of the desired app). For instance, in models.py of my plugin: class Logic(models.Model): # fields def do_something(self, instance): ser = get_serializer(instance) # some operation For the unittest, I thought of using default from django_comments.models import Comment but that does not have a serializer. Is there any default serializer that I could test against? I'd appreciate any suggestions -
How can I allow All users can login() while they are inactive in Django
my views : code = random.randint(100000, 999999) def register(request): #### when registration is ok global code subject = 'ok' message = "activation code" + str(code) email_from = settings.EMAIL_HOST_USER send_mail(subject, message, email_from, [email]) user.is_active = False user.save() login(request, user) ### problem is here, user cant login because activation is false return redirect('email_activation/') def email_activation(request): if request.method == "POST": global code email_activation = request.POST['email_activation'] if str(email_activation) == str(code): request.user.is_active = True request.user.save() return redirect('account') user should login in register to can activation become True in email activation i would be glad someone help me to how inactive user can login -
django.db.utils.OperationalError: no such table: hotel_addhotelstep2
I have make changes in models.py, also added some new models and after migrate I got an error As I understand it says that I have no created the models yet but if I cant do migrations and migrate how can I create any models there? Migrations for 'hotel': hotel\migrations\0029_auto_20210722_1841.py - Create model AddHotelStep1 - Create model AddHotelStep2 - Alter field hotel_name on doubleroom - Alter field hotel_name on singleroom - Delete model Hotel PS C:\Users\Gegi\Desktop\Hotelpedia\hotelpedia> py manage.py migrate Operations to perform: Apply all migrations: account, admin, auth, contenttypes, hotel, sessions Running migrations: Applying hotel.0029_auto_20210722_1841...Traceback (most recent call last): File "C:\Users\Gegi\Desktop\Hotelpedia\hotelpedia\manage.py", line 22, in <module> main() File "C:\Users\Gegi\Desktop\Hotelpedia\hotelpedia\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) migration_recorded = True self.connection.check_constraints() File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 343, in check_constraints raise … -
DRF filters.SearchFilter don'e work when I modify the get method?
I have this vide and it was working just find class UsersView(generics.ListAPIView): queryset = User.objects.all() serializer_class = serializers.UsersSerializer search_fields = ('username', 'email') but when I changed it to def get(self, request, *args, **kwargs): super().get(request, *args, **kwargs) context = {'request': request, 'method': 'view'} items = queryset_filtering(self.queryset.model, request.GET) serializer = self.serializer_class( items, context=context, many=True) return Response(serializer.data, status=status.HTTP_200_OK) the /users/?search=Alex don't work anymore? -
Deleting Model Data after specific sweet alert button click - Django
I am creating a donation web application that allows people to donate stuff. I have a screen where users can see details about a certain donation, and if they like it they can click on the accept button, and a sweet alert comes up. I am wondering how I can delete the current donation after the sweet alert is clicked. Basically, I can't figure out how to run python code after the js action happens. My code is down bellow Sweet alert (I want to run python code after the user clicks ok) function showAlert() { 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", }); } }); } -
Django - AutoCompleteSelectMultipleField with values
I'm using AutoCompleteSelectMultipleField from ajax_select.fields and it works fine - I'm getting values based on what I'm wrting, but I would like to have all values displayed before I write something. Is there any configuration I'm missing or should I use something different? At this moment I have: form.fields['teams'] = AutoCompleteSelectMultipleField( 'master_teams', plugin_options={ 'source': f"{reverse('ajax_lookup', kwargs={'channel': 'master_teams'})}?game_slug={self.game.slug}"}, required=False, help_text="Enter team name", ) and in my lookups file I just filter my query to get specific data and I would like to display them as a dropdown list in my template. Can anybody give me any hint how to solve this?