Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Error base64 encoding when testing upload image in django restful framework
I'm writing unit tests trying to upload images and base64 encode it. But the encoding is different from expected. This is my tests.py with open('tests/image.jpg', 'rb') as image: r = self.client.post('/images', {'image': image}, format='multipart') This is my views.py def post(self, request): image = request.FILES['image'] base64_str = base64.b64encode(image.read()).decode('utf-8') The base64_str turns out to be like 7f7NCd0Aw29mVx...... Doing in a python script with open('tests/image.jpg', 'rb') as f: print(base64.b64encode(f.read()).decode('utf-8')) The output is /9j/4AAQSk...... I suppose there is something wrong with the encoding. So what's the problem? -
DirectAdmin CloudLinux Python Selector Django App - Application URL goes to root /home/<user>/<app>
I have setup a new DirectAdmin server with CloudLinux. I want to use the Python Selector option to build Django websites. I have created a test website, but the URL redirects to the root folder. django.[domain].nl/myapp/admin -> django.[domain].nl/home/[user]/myapp/admin /home/[user]/ is added extra. The full DirectAdmin path. I doubt whether this is a DirectAdmin setup error or a Django setting. -
getting problem with working json data for web development
hi i am working on python django project i need to convert my json data to datatable in frontend, i have using backend in python and frontend htmt,css,javascript for ex this is my json data- {"json_res": [{"car_number": mh00012, "trip":27,"empid":001,"onlinehrs":16}], "json_res1":[{"car_number":mh00014,"trip":100,"last_Week_trips":10}]} i want to make table like this in frontend- car_number trips empid onlinehrs last_week_trips mh00012 27 001 16 0 mh00014 100 0 0 10 -
Why my function in Views.py is not correct?
I have a Notification List view and this function def mark_as_read(request, notification_id): notification = get_object_or_404(Notification.objects.filter(pk=notification_id).exclude(viewed_at__isnull=False)) notification.viewed_at = datetime.datetime.now() notification.save() return redirect('users:notification') It works good but I think it is written not correct? Any body can tell it correct here working get_object_or_404? -
Saved task_id in database does not match Info from celery worker
I'm currently working on an application, that allows queueing of several tasks which should be allowed to be cancelled. For that to be possible, my task-model has a field for saving the task_id of the worker, and in Django, the user is presented with a list of the tasks and an option to stop individual tasks. The issue I am having is that the task_ids stored away in the database and the task_ids mentioned in the info line from the worker do not match until the worker has finished his task. i.e. the worker returns [2021-07-22 16:35:25,652: INFO/MainProcess] Received task: dop.tasks.execute_report[7490537f-90dd-4966-bff7-63d5461a92ff] but in the database, there's a different task_id saved until the worker returns a successful completion of the task. This prevents me from revoking any of the displayed tasks in the queue, because they have the wrong task_id associated with them. my code is below: def create_report(request, slug): ... # create report report = Report.objects.create( reportDefinition=reportDefinition, user=request.user ) ... transaction.on_commit( lambda: execute_report.delay( user_id=request.user.id, report_id=report.id, command_string=reportDefinition.get_command(), db_name=request.user.basex_prefix, resource_names=report.get_active_user_resource_names(), ) ) ... execute_report looks like this: @celery_app.task(bind=True) def execute_report( self, user_id, report_id, command_string, db_name, resource_names: list ): start_time = datetime.now() # get objects user = get_user_model().objects.get(id=user_id) report = Report.objects.get(id=report_id) report.task_id = …