Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 = … -
Django in_bulk() raising error with distinct()
I have the following QuerySet: MyModel.objects .order_by("foreign_key_id") .distinct("foreign_key_id") .in_bulk(field_name="foreign_key_id") foreign_key_id is not unique on MyModel but given the use of distinct should be unique within the QuerySet. However when this runs the following error is raised: "ValueError: in_bulk()'s field_name must be a unique field but 'foreign_key_id' isn't." According to the Django docs on in_bulk here it should be possible to use in_bulk with distinct in this way. The ability was added to Django in response to this issue ticket here. What do I need to change here to make this work? I'm using Django3.1 with Postgres11. -
DATETIME_FORMAT setting for my customized datetime field
I wrote a customized datetime field Now i want to add DATETIME_FORMAT setting for this customized field? -
How to set is_staff to True in Django when a user is created with a specific group selected
How would I automatically set is_staff to True when creating a new user in the Django admin when they have a specific group selected? -
Uploading image to Django database raises TypeError
I am having trouble uploading image paths into my Django database. When I try to add data without the eventImage field, it works fine. But when I upload anything to the eventImage field, it says: TypeError at /admin/events/event/add/ expected str, bytes or os.PathLike object, not tuple Request Method: POST Request URL: http://127.0.0.1:8000/admin/events/event/add/ Django Version: 3.2.5 Exception Type: TypeError Exception Value: expected str, bytes or os.PathLike object, not tuple Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/posixpath.py, line 374, in abspath I've put relevant code snippets below. Please let me know what I'm doing wrong! In my settings.py file: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'events', ] STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media'), STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] In my events.py file: from django.db import models class Event(models.Model): venueName = models.TextField() artistName = models.TextField() eventName = models.TextField() time = models.TextField() date = models.TextField() length = models.TextField() description = models.TextField() eventImage = models.ImageField( upload_to='media/', blank=True, null=True) def __str__(self): return self.eventName Any help would be hugely appreciated! -
how to solve Django url patterns not working
I added path('int:pk/',...) in urls.py and access 'http://127.0.0.1:8000/blog/1' the result was 'page not found(404)' Using the URLconf defined in doit.urls, Django tried these URL patterns, in this order: blog <int:pk>/ blog admin/ The current path, blog/1, didn’t match any of these. also, I made 3 pk contents please help me I suffered for a long time. urls.py from django.urls import path from . import views urlpatterns = [ path('<int:pk>/', views.PostDetail.as_view()), path('', views.PostList.as_view()), ] models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=30) content = models.TextField() created_at = models.DateTimeField() def __str__(self): return f'[{self.pk}]{self.title}' views.py from django.views.generic import ListView, DetailView from .models import Post class PostList(ListView): model = Post ordering = '-pk' class PostDetail(DetailView): model = Post post_list.html <!DOCTYPE html> <html lang = "ko"> <head> <meta charset="UTF-8"> <title>Blog</title> </head> <body> <h1>Blog</h1> {% for p in post_list %} <hr/> <h2> {{ p.title }} </h2> <p> {{ p.content }}</p> <h4> {{ p.created_at }} </h4> {% endfor %} </body> </html> post_detail.html <!DOCTYPE html> <html lang="ko"> <head> <meta charset = "UTF-8"> <title> {{ post.title }} - Blog </title> </head> <body> <nav> <a href="/blog/">Blog</a> </nav> <h1> {{ post.title }} </h1> <h4> {{ post.created_at }} </h4> <p> {{ post.content }} </p> <hr/> <h3> ... </h3> </body> </html>