Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How would I display the actual item and not its ID in Django forms?
I have a form whose details are displayed. I have a field that is read-only [book_id] but it is the ID that is displayed. How would I have it display the actual item??? class IssueForm(forms.ModelForm): def __init__(self,*args, pk,school,issuer, **kwargs): super(NewIssueForm, self).__init__(*args, **kwargs) klasses = [1,2,3,4] if Books.objects.filter(school=school,id=pk,subject__name = "revision"): self.fields['due_days'].widget.attrs['hidden'] = False else: self.fields['due_days'].widget.attrs['hidden'] = True self.fields['issuer'].initial = issuer self.fields['borrower_id'].queryset = Student.objects.filter(school=school,klass__name__in = klasses) self.fields['borrower_id'].label = "Select Student." self.fields['book_id'].label = "Selected Book." self.fields['book_id'].widget.attrs["readonly"] = True self.initial['book_id'] = Books.objects.get(school=school,id=pk) class Meta: model = Issue fields = ['issuer','book_id','borrower_id','due_days'] widgets = { 'book_id':forms.TextInput(attrs={"class":'form-control','type':''}), 'issuer':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'borrower_id': Select2Widget(attrs={'data-placeholder': 'Select Student','style':'width:100%','class':'form-control'}), 'due_days':forms.TextInput(attrs={"class":"form-control"}), } -
How do I update only selected records in the Django queryset?
Immediately I apologize for the mistakes, English is not my native language (this text is google translation) Hello I am new to django and I have a question. I have a table in DB with fields and boolean value "checked". You need to give access to check records to other users, and I would not want to give access to the admin panel. How can I show a checkbox in a view along with a queryset in the table to set the value to true in the table and update only the rows selected by this checkbox? P.S. I tried through the form but it only creates a new record p.p.s Now it turns out only to update ALL records of the table Here is my model.py class moneIn(models.Model): date = models.DateTimeField(auto_now_add=True, verbose_name='') dateUpdate = models.DateTimeField(auto_now=True) ts = models.IntegerField(verbose_name='') pl = models.IntegerField(verbose_name='') rem = models.IntegerField(verbose_name='') comment = models.TextField(max_length=200, verbose_name='', blank=True) staffer = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='') checked = models.BooleanField(verbose_name='', default=False) checkedUser = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='', blank=True, null=True, related_name='checkedUser') def __str__(self): return '{0}'.format(self.date) # return self.user class Meta: ordering = ['-date'] verbose_name = '' verbose_name_plural = '' You need to change the "checked" parameter through the template and automatically insert the user … -
CORS error with React native web with Nginx + Django
I've faced CORS error with EC2 Django + Nginx server. Have no idea why it never works. Error: Access to fetch at 'https://serveraddress/api/v1/user' from origin 'http://localhost:19006' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. How I requestsed fetch(`https://${env.apiUrl}/api/v1/user`, { method: "GET", mode: "cors", withCredentials: true, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept", "Access-Control-Allow-Methods":"GET,PUT,POST,DELETE,OPTIONS", "Access-Control-Allow-Credentials":'true', Authorization: await getToken(), }, Also tried with using Authorization header or request get, post request auth is not requried, but none of them worked. Plus, tried with axios, xmlhttprequest and none of them worked.. Followings are settings for Nginx + Django Nginx Settings location / { proxy_hide_header Access-Control-Allow-Origin; add_header Access-Control-Allow-Origin '*'; add_header Access-Control-Allow-Credentials true always; proxy_pass http://web/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; Django Settings All the settings for cors including django-cors-headers middleware and put corsheaders.middleware.CorsMiddleware on the top of it. MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', .... ] CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ 'DELETE', 'GET', … -
user automatically logged out after payment is done on redirect from bank
so i have this problem that when user make a payment and redirect to the website, the user is no longer logged in, im new in django and i dont know what is the problem and how to solve it. this is the function that i downloaded from the bank website. @csrf_exempt def payment_return(request): if request.method == 'POST': pid = request.POST.get('id') status = request.POST.get('status') pidtrack = request.POST.get('track_id') order_id = request.POST.get('order_id') amount = request.POST.get('amount') card = request.POST.get('card_no') date = request.POST.get('date') if Payment.objects.filter(order_id=order_id, payment_id=pid, amount=amount, status=1).count() == 1: idpay_payment = payment_init() payment = Payment.objects.get(payment_id=pid, amount=amount) payment.status = status payment.date = str(date) payment.card_number = card payment.idpay_track_id = pidtrack payment.save() if str(status) == '10': result = idpay_payment.verify(pid, payment.order_id) if 'status' in result: payment.status = result['status'] payment.bank_track_id = result['payment']['track_id'] payment.save() return render(request, 'accounts/profile.html', {'txt': result['message']}) else: txt = result['message'] else: txt = "Error Code : " + str(status) + " | " + "Description : " + idpay_payment.get_status(status) else: txt = "Order Not Found" else: txt = "Bad Request" return render(request, 'error.html', {'txt': txt}) def payment_check(request, pk): payment = Payment.objects.get(pk=pk) idpay_payment = payment_init() result = idpay_payment.inquiry(payment.payment_id, payment.order_id) if 'status' in result: payment.status = result['status'] payment.idpay_track_id = result['track_id'] payment.bank_track_id = result['payment']['track_id'] payment.card_number = result['payment']['card_no'] payment.date = … -
Django secondary admin site links to main admin site
I'm trying to add a secondary admin site and it's working correctly except that any links are pointing to the main admin site. Not sure how to get around this. If I visit /dispatch/admin/ the model Run is visible but when I click the link it directs me to /admin/dispatch/run/ instead of /dispatch/admin/dispatch/run/. Django==3.2.7 class DispatchAdminSite(admin.AdminSite): pass class DispatchRunAdmin(RunAdmin): def get_queryset(self, request): return ( super().get_queryset(request) .filter_today_or_future() ) def get_readonly_fields(self, request, obj=None): return [f.name for f in self.model._meta.fields] dispatch_admin_site = DispatchAdminSite(name='Dispatch') dispatch_admin_site.register(models.Run, DispatchRunAdmin) dispatch/urls.py app_name = 'dispatch' urlpatterns = [ path('admin/', admin.dispatch_admin_site.urls), ] project/urls.py urlpatterns = [ path('dispatch/', include('dispatch.urls')), path('admin/', admin.site.urls), ] -
Funciones en Paralelo con Django y Python
Estoy desarrollando una aplicación web con Python en Django 3.2.7. Resulta que he generado un script que ejecuta una automatización. En la interfaz, pido por formulario la cantidad de veces que dicha automatización se tiene que ejecutar. Este es mi forms.py don pido la automatización a ejecutar y la cantidad de veces que corre: class Task_Form(forms.Form): TASKS = (("1", "Catalina"), ("2", "Nosis"),) task = forms.ChoiceField(choices = TASKS, widget=forms.Select(attrs={'class': 'form-select'})) number_processes = forms.IntegerField(widget=forms.NumberInput({ 'class': 'form-control', 'placeholder': '1' })) Resulta que en el back, en las views.py tengo lo siguiente: def load_task(request): """Renders the test page.""" assert isinstance(request, HttpRequest) if request.method == 'POST': form = forms.Task_Form(request.POST, request.FILES) if form.is_valid(): select = form.cleaned_data['task'] number_processes = form.cleaned_data['number_processes'] if select == '1': for i in range(number_processes): catalina.start() else: form = forms.Task_Form() return render(request,'app/loadfile.html', { 'form': form, 'title': 'Load File',}) Donde genero un bucle for que va a dar vueltas una x cantidad de veces dependiendo el número que ponga el usuario. El problema es que esto se ejecuta de forma síncrona, por lo que hasta que no termine la función catalina.start() la primera vuelta del for, no voy a poder pasar a la segunda. Necesito que independientemente de que termine o no de ejecutar Catalina.start() … -
ezdxf in django- not writing to file, or not functioning
I'm currently in the middle of creating a web app using Django and ezdxf. the end goal is to output the contents of the dxf file both as a dxf file and as a png. This seems like a beginner django question and intermediate ezdxf question. I wrote a set of instructions for ezdxf that instantiate a file, then draw my artwork, and then saves the file as both a .dxf and as a png. This works great in the command line of pycharm. def instantiate_drawing(): """starts a new drawing and adds all needed layers etc.""" doc = ezdxf.new('R2010', setup=True) msp = doc.modelspace() lines_layer = doc.layers.new('python-lines', dxfattribs={'color': 0}) dims_layer = doc.layers.new('python-dims', dxfattribs={'color': 3}) label_layer = doc.layers.new('python-label', dxfattribs={'color': 13}) myStandard = doc.styles.new('myStandard', dxfattribs={'font': 'Helvetica.ttf'}) blocdoc = ezdxf.readfile('block_library.dxf') blocmsp = blocdoc.modelspace() importer = Importer(blocdoc, doc) return doc, msp, lines_layer, dims_layer, label_layer, myStandard, blocdoc, importer example drawing instructions def create_rectangle(pt0, pt1, off=3, dims=None): """creates a rectangle between 2 points, and adds dims between take two tuples with pt coords, higer coords second""" width, height = pt1[0] - pt0[0], pt1[1] - pt0[1] lineweight = 5 msp.add_lwpolyline([(pt0[0], pt0[1]), (pt1[0], pt0[1]), (pt1[0], pt1[1]), (pt0[0], pt1[1]), (pt0[0], pt0[1])], dxfattribs={'layer': 'python-lines'}) # rectangle if dims: dimw = msp.add_linear_dim(base=(pt0[0], … -
Django Web App Music Player Not Playing .mp3 files or showing .img files
I am building a music player as a web app using Python, Django, and postgres. I have a few albums I am working with that are stored in the database. All of my database imports are working properly. My css script is working. Front end is connected to backend and the music player looks good. In the browser, each page accurately paginates through each song in a given album, displaying artist name, album title, track title, track number. This suggests the correct information is being supplied from the database. All the necessary buttons are present but when I click on play nothing happens and the album artwork does not display. I have spent time troubleshooting this but have been unsuccessful in tracking down where the python code isn't connecting correctly to the JS/HTML/CSS code. I have one app that deals with the database layer - import scripts, etc. The musicplayer app contains the rest of the code. Setup: settings.py PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py from django.urls import path, include from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib.staticfiles.urls import static urlpatterns = [ path('admin/', … -
My django app url reversing is not working
I have a web application which I have split into several applications. I think this might have been an over exageration on my part but regardless I want to make this work and understand what my problem is. To those apps I have a list of buttons with the links: <li class="nav-item active"><a class="nav-link" href="{% url 'dashboard' %}"><i class="fa fa-home"></i><span class="link-text">Home</span></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'resume:index' %}"><i class="fa fa-user"></i><span class="link-text">Resume</span></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'services:index' %}"><i class="fa fa-rocket"></i><span class="link-text">Services</span></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'portfolio:index' %}"><i class="fa fa-briefcase"></i><span class="link-text">Portfolio</span></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'blog:index' %}"><i class="fa fa-pencil"></i><span class="link-text">Blog</span></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'contact:index' %}"><i class="fa fa-address-book"></i><span class="link-text">Contact</span></a></li> The urls for these are stored in the webapp/urls.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('dashboard.urls')), path('resume/', include('resume.urls')), path('portfolio/', include('portfolio.urls')), path('articles/', include('articles.urls')), path('blog/', include('blog.urls')), path('services/', include('services.urls')), path('contact/', include('contact.urls')) ] And in each webapp/app/urls.py file I have the urlpatterns as such: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Currently I am having two issues with this. The dashboard link does not work and I get the error "No reverse match for 'dashboard' … -
Django: Filter based on foreignkey's start date and end date
I have the following two models: class ParentModel(models.model): name = models.CharField("Name", max_length = 256, blank = True) start_date = models.DateField(blank = True, null = True) end_date = models.DateField(blank = True, null = True) class ChildModel(models.model): name = models.CharField("Name", max_length = 256, blank = True) parent_model = models.ForeignKey(ParentModel, blank = True, null = True, on_delete=models.SET_NULL) start_date = models.DateField(blank = True, null = True) end_date = models.DateField(blank = True, null = True) Now I want to filter all the childmodel's whose date range is not within the date range of the associated parentmodel's date range. The code I tried: import pandas as pd child_models = ChildModel.objects.filter(start_date__lte=input_end_date, end_date__gte=input_start_date) exceeding_child_models = [] for child_model in child_models: date_range = pd.date_range(start=child_model.start_date, end=child_model.end_date) if child_model.start_date not in date_range or child_model.end_date not in date_range: exceeding_child_models.append(child_model) How can I do that using Django ORM in a single query? -
Django REST on LAMP - default /admin not always showing app with its models
I am pretty new to the Django + REST Framework and I was trying to just show some models on the admin page. However, when loading the admin-page in the browser it was just the default site with users and groups. When i reload the page, sometimes it is showing my app and models but not always. in a second tab, the models are shown at the same time as the other one that makes me think its some kind of server problem itself. What i did is this: start an app, python manage.py startapp testapp register in settings.py, in the app folder: models.py: from django.db import models class Book(models.Model): prename = models.CharField(max_length=150) lastname = models.CharField(max_length=150) admin.py: from django.contrib import admin from .models import Book admin.site.register(Book) migrate the model python manage.py migrate python manage.py makemigrations python manage.py migrate -
how to upload more than 2 images from a Forms.py form without error?
*Good evening dear web developer, I have a problem with django 3.2.8. I configured my settings normally for media files. When I fill out the form from the django administration interface, the image is stored friends when I go through the form, it shows me "Page not found (404), Raised by: django.views.static.serve" -
How to define a URL to a css stylesheet for TinyMCE in Django
I want to render the TinyMCE widget with a custom stylesheet. Therefor I somehow need to build the url to that stylesheet so I can pass it to the widget. # Form from poller import settings class PollersForm(forms.Form): tinymce_css_url = str(settings.BASE_DIR) + str(settings.STATIC_URL) + 'css/about.css' print(tinymce_css_url) # Returns /Users/jonas/PycharmProjects/poller/static/css/about.css # Form poller_category = forms.ModelChoiceField(widget=forms.RadioSelect(attrs={ 'class': 'poller-category-radio', 'content_css': tinymce_css_url }), queryset=Category.objects.all().order_by('category'), label='Select a Category', required=True) My issues are that the stylesheet isn't loaded when rendering the template and I'm not sure if this would also work for production without any further changes? -
__str__ returned non-string (type NoneType) | Django [closed]
ERROR TypeError at /barteradmin/adminusers __str__ returned non-string (type NoneType) Request Method: GET Request URL: http://127.0.0.1:8000/barteradmin/adminusers Django Version: 3.2.6 Exception Type: TypeError Exception Value: __str__ returned non-string (type NoneType) Exception Location: C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\db\models\base.py, line 521, in __repr__ Python Executable: C:\Users\Qasim Iftikhar\anaconda3\python.exe Python Version: 3.8.5 Python Path: ['C:\\xampp\\htdocs\\Projects\\Barter', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\python38.zip', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\DLLs', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib', 'C:\\Users\\Qasim Iftikhar\\anaconda3', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\Pythonwin'] Server time: Wed, 06 Oct 2021 15:10:36 +0000 CODE # Weekly Users currenttime_non_string = datetime.now() currenttime = currenttime_non_string.isoformat() currenttime2 = datetime.now() thisweek_non_string = currenttime2 - timedelta(days=7) thisweek = thisweek_non_string.isoformat() weeklyusers = BarterUserDetail.objects.filter(user_registration_date__gte = thisweek) & BarterUserDetail.objects.filter(user_registration_date__lte = currenttime) print("Printing Dates") print(currenttime, type(currenttime) , yesterday, type(yesterday), thisweek, type(thisweek)) print(dailyusers, weeklyusers) CODE EXPLANATION Trying to get records from database of last seven days. Having error at printing the records whether in python or in django templates. -
How To Fix The view loginapp.views.login didn't return an HttpResponse object. It returned None instead. in django
Hello I'm Creating Login Form In Django. How Got an error > The view loginapp.views.login didn't return an HttpResponse object. It > returned None instead. in django my code: def login(request): if request.method=="POST": username=request.POST['username'] password=request.POST['password'] user = authenticate(request, username=username, password=password) else: return render(request, "registration/login.html") -
Django set record in custom order
how to set custom order of record in queryset? ex: Queryset has this values <QuerySet [{'id': 5, 'order_number': 1}, {'id': 3, 'order_number': 2}, {'id': 2, 'order_number': 3}, {'id': 1, 'order_number': 4}, {'id': 7, 'order_number': 5}, {'id': 4, 'order_number': 6}]> the request set the order of item of id=5 to be 3rd record of the queryset so the queryset should be: <QuerySet [{'id': 3, 'order_number': 1}, {'id': 2, 'order_number': 2}, {'id': 5, 'order_number': 3}, {'id': 1, 'order_number': 4}, {'id': 7, 'order_number': 5}, {'id': 4, 'order_number': 6}]> I Could loop over all the queryset items and set the order every time, but I am asking if there is any better solution. -
How to run again that cronjob when the same job finished
I have a cron job that runs every 20 minutes from 9-5. Here is the code: */20 09-05 * * * I want it set so that if the job ends in 10 minutes, it starts again automatically. When the scheduled time exceeds 20 minutes, the next job runs when the first is finished. It is a python server running on an Ubuntu operating system. According to crontab.guru: // * * * * * // It runs after every minute So, if anyone have any solution, please reply me. -
Django Modelviewset try to create custom route
@action(detail=False, methods=['GET'], name='Get Vesting Locaitons') def get_vesting_locations(self, request, pk=None, *args, **kwargs): I'm trying to return json response and get 404 error this is the the route regiser router.register(r'vesting', VestingViewSet, basename='vesting') and those are the urls im trying to get http://localhost:8000/vesting/get_vesting_locations/617b8bd8-6fdd-43eb-948a-4b17d1a0a089/ http://localhost:8000/vesting/617b8bd8-6fdd-43eb-948a-4b17d1a0a089/get_vesting_locations/ -
How Can I Deploy Django with Apache and Gunicorn on CentOs7?
I have been trying to deploy django on my CentOs 7 server (release 7.9.2009) for a bit now, and I have tried the nginx + gunicorn route as well as the Apache + mod_wsgi route. However, both of them hit roadblocks, namely that Apache was blocking nginx, and that my version of CentOs7 is not compatible with mod_wsgi. So, I tried mod_proxy_uswgi but there is not much in the way of tutorials or information on how to using that module with Apache. Then, I finally settled on attempting to use gunicorn to serve my files, and using an Apache config. Still, nothing of any use. The structure of my django project is . ├── manage.py ├── static │ └── admin ├── testproject │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── venv Here is the relevant code django.conf <VirtualHost *:80> ServerName mydomainname.com ProxyPreserveHost On ProxyPass /static/ ! ProxyPass / http://0.0.0.0:8000/ ProxyPassReverse / http://0.0.0.0:8000/ ProxyTimeout 300 Alias /static/ /home/user/django_test/static/ <Directory /home/user/django_test/testproject> <Files wsgi.py> Require all granted </Files> </Directory> <Directory "/home/user/django_test/static/"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> </VirtualHost> Relevant portion of settings.py ALLOWED_HOSTS = ['*'] ... STATIC_URL = '/static/' … -
How to set default values into an Array Field Django?
I would like to know how to set default values into a Django Array Field Model. I have a TextChoices model named "GameType" : class GameType(models.TextChoices): ''' Enumeration of all different game types ''' EVIL = 'evil', 'evil' SOLOCOOP = 'solo', 'solo' MULTI = 'multi', 'multi' And in my Item model, I can choose in each mode my item is available. Then I have these lines : game_types = ArrayField( models.CharField( default=GameType.SOLOCOOP, max_length=40, choices=GameType.choices ), default=default_item_game_types, null=False, blank=False) Two things : The first default key "GameType.SOLOCOOP" doesn't work The default list doesn't work too Here is my "default_item_game_types" function : def default_item_game_types(): '''Default callable to avoid errors ''' return list(GameType) And in my CMS, I don't have my default values : Screenshot of my Game types field I tried many things and searched many solutions but nothing matched in my case. Is there any response to fix my issues ? Thanks for your time Regards, Steven -
Django query - how to filter sum by date?
I am struggling with a queryset in a Django view. Basically, I have three models: User, ActivityLog, & ActivityCategory. User is the built-in. ActivityLog looks like this: class ActivityLog(models.Model): activity_datetime = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='activity_user') activity_category = models.ForeignKey(ActivityCategory, on_delete=models.CASCADE, null=True, related_name='activity_cat') activity_description = models.CharField(max_length=100, default="Misc Activity") Activity Category: class ActivityCategory(models.Model): activity_name = models.CharField(max_length=40) activity_description = models.CharField(max_length=150) pts = models.IntegerField() My goal is to return an aggregate by user of all the points they have accumulated by participating in activities in the log. Each log references an ActivityType, different types are worth different points. I accomplished this with the following query in the view: class UserScoresAPIView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserScoresSerializer def get_queryset(self): queryset = User.objects.annotate(total_pts=Coalesce(Sum('activity_user__activity_category__pts'), 0)).order_by('-total_pts') return queryset So now I need to add to this query and restrict it based on date of the activity. I want to basically add a filter: .filter('activity_user__activity_datetime__gte=datetime.date(2020,10,1)') How can I add this into my current query to accomplish this? I tried to do so here: queryset = User.objects.annotate(total_pts=Coalesce(Sum('activity_user__activity_category__pts').filter('activity_user__activity_datetime__gte=datetime.date(2020,10,1)') , 0)).order_by('-total_pts') But that would happen after the Sum and wouldn't be helpful (or work...) so I tried to chain it where it is pulling the User objects User.objects.filter('activity_user__activity_datetime__gte=datetime.date(2020,10,1)').annotate(total_pts=Coalesce(Sum('activity_user__activity_category__pts'), 0)).order_by('-total_pts') … -
How to create api for this including put,get,post method using serializer?
class normal(models.Model): active = models.BooleanField(default=True) created_on = models.DateTimeField(auto_now_add=True,null=True) created_by_id = models.IntegerField(null=True) updated_on = models.DateTimeField(auto_now=True,null=True) updated_by_id = models.IntegerField(null=True) class Meta: abstract=True class Role(normal): name = models.CharField(max_length=100) description = models.TextField(null=True) class Meta: db_table = 'environment_role' -
Save data type JSONField from celery
model.py: from django.db import models from datetime import datetime from django.db.models import TextField, JSONField, Model # Create your models here. class reservation(models.Model): res=models.JSONField() da = models.DateTimeField(default=datetime.now, blank=True) tasks.py: @shared_task def ress(): content={ "customer": 48, "reservation_id_pms": str(id), "reservation_channel_number": None, "reservation_group_id_pms": "ed2b9d55-46d9-4471-a1e9-ad6c00e30661", "extra_reservation_code": "550ca1c1", } reservations=reservation.objects.create(res=content) reservations.save() res.append(content) return None ereur: from django.db.models import TextField, JSONField, Model ImportError: cannot import name 'JSONField' from 'django.db.models' (/usr/lib/python3/dist-packages/django/db/models/init.py) -
Django RadioButton in HTML
in my custom form I've radiobutton to select my user gender. When I try to submit the form it gives me back this error 'UserInfo' object has no attribute 'is_valid' Since this error started after I've edited my html template using only html and not {{ form.as_p }} I waas wondering if the problem could it be the way I write the radiobutton input since I'm not sure this is the way to use it. Thank you all for your help! model.py class UserInfo(models.Model): gender_choice = (('Male', 'Male'),('Female', 'Female')) user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) gender = models.CharField(max_length=120, choices=gender_choice) forms.py class UserInfo(ModelForm): class Meta: model = UserInfo fields = ('first_name', 'last_name', 'gender') views.py def add_information(request): submitted = False if request.method == "POST": form = UserInfo(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('add_information?submitted=True') else: form = UserInfo if 'submitted' in request.GET: submitted = True return render(request, 'accounts/profile/tempplate.html', {'form': form, 'submitted':submitted}) template.html <form action="" method=POST> {% csrf_token %} <label>First Name:</label> <div class="input-group mb-2"> <div class="input-group-append"> </div> <input type="text" name="first_name" placeholder=""> </div> <label>Last Name:</label> <div class="input-group mb-2"> <div class="input-group-append"> </div> <input type="text" name="last_name" placeholder=""> </div> <label>Gender:</label> <div class="input-group mb-2"> <div class="input-group-append"> </div> <input type="radio" id="male" name="gender" value="male"> <label for="male">Male</label> … -
Angular css does not fully load when built with prod. Served from django
I'm using angular with django. I set up a docker container that builds the app, then collects the static info. Most of the css works, but the css in the src/styles.css seems Here are my angular versions: Angular CLI: 9.0.1 Node: 16.10.0 my build command is: RUN yarn install && yarn build --prod --output-hashing none my angular.json "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/occtool", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "aot": true, "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css", "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/styles.css" ], "scripts": [] }, I'm not sure what else might be relevant but feel free to comment and I will edit my post. My component css files seem to mostly load fine. I use the material theme for a mat tab group. One works with my css, the other uses the deep purple css only. ng serve --prod does load the css as expected. Network traffic doesn't show any failed requests to get css from django.