Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
generating paths with django and python, what is the request object
This is my first experience with Django so there's probably an obvious solution I'm not aware of. I have an assignment of creating an encyclopedia-like website, one objective is creating pages for each article that I have. I've created a function in my "views" file: def title_page(request, title): if title not in util.list_entries(): return render(request, "encyclopedia/error.html") return render(request, f"encyclopedia/title.html", { "page_name": title, "content": util.get_entry(title) }) where util.list_entries() is a function that supplies the list of article names and util.get_entry is a function that supplies the content of said article name. in my "urls" file i have a list of url patterns that holds all of my paths: urlpatterns = [ path("", views.index, name="index") ] i tried to create a loop to append a path for each article that i have: for entry in util.list_entries(): urlpatterns.append(path(f"<str:{entry}>", views.title_page(entry), name=entry)) however i get a TypeError: TypeError: title_page() missing 1 required positional argument: 'title' I suppose that title_page function requires the request object but I'm not sure how to access it and how to pass it through the paths function, and moreover in functions like the index function that requires no other positional arguments : def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) … -
Write a django Alluth adapter that checks if a value i unique
Im trying to check if a value for pid is uniqe but i cant manage to make alluth adapter to find the pid field. Any tips? Nothin happend, but if i change pid value to email the code works on the email field. I cant get the pid field to work whit this function. Maybe im referencing it in a wrong way and the filed does not belong to the default account adaptet- class PidMaxAdapter(DefaultAccountAdapter): def clean_pid(self, pid, user): user.profile.pid = pid if len(pid) > 9: raise ValidationError('Please enter a username value\ less than the current one') # For other default validations. return DefaultAccountAdapter.clean_pid(self, pid) -
How to use accessors in Django?
I've read previous Q and docs, however still not able to make it work.. I have the following models: class Process(models.Model): class Meta: verbose_name_plural = "Processes" name = models.CharField(max_length=120) description = models.CharField(max_length=4) parent_process = models.ForeignKey('self', related_name="parent_process+", on_delete=models.PROTECT, blank=True, null=True, verbose_name="parent process") process_activities = models.CharField(max_length = 2048, blank=True, verbose_name="process activites") owner = models.ForeignKey(User, related_name="owner+", on_delete=models.PROTECT, blank=True, null=True, verbose_name="owner") def __str__(self): return "{}".format(self.name) class ControlTest(models.Model): history = AuditlogHistoryField() name = models.CharField(max_length=120) description = models.CharField(max_length=120) Now I want to use an accessor to access the name of the process and display in a table (tables.py): class controltestTable(tables.Table): class Meta: hoofdproces = tables.Column(accessor='process.name') model = ControlTest fields = ['id',"name", "hoofdproces", "sub_process", 'description', 'control', 'delegate', 'owner', 'reviewer1', 'reviewer2', 'reviewer1_r', 'reviewer2_r', 'delegate_r', 'owner_r', 'reviewer_status', 'status', 'history', 'comments', 'review_comments', 'due_date', 'review1_due_date', 'review2_due_date', 'documentation'] template_name = "django_tables2/bootstrap-responsive.html" Views.py: class ControlTestView(SingleTableView, FormView, SingleTableMixin, FilterView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) queryset = kwargs.pop('object_list', None) if queryset is None: self.object_list = self.model.objects.all() context['controltests'] = ControlTest.objects.all() return context def post(self, request, *args, **kwargs): form = self.get_form() print(form) if form.is_valid(): instance = form.save(commit=True) instance.save() print('valid') return self.form_valid(form) else: print(form.errors) return self.form_invalid(form) template_name = "control/ControlTest.html" model = ControlTest form_class = ControlTestForm table_class = controltestTable success_url = reverse_lazy('controltest') However, nothing gets displayed in the … -
Change DateTimeField FORMAT in Django version 3.2.2
I'm trying to change DateTime format for all date time objects in my project. I want to format : 21-06-2021 14:02:12 My settings DATETIME_FORMAT = '%d-%m-%Y %H:%M:%S' TIME_ZONE = 'Africa/Tunis' USE_I18N = True USE_L10N = False USE_TZ = True Result: %21-%06-%2021 %14:%Jun:%st -
Path duplication while saving Django FileField
I have field, that holds audiofile: class Meditation(models.Model): name = models.CharField(max_length=50) audio = models.FileField(upload_to='AudioTracks') length = models.IntegerField(blank=True, null=True) Also I have pre-post signals to convert audio into .m4a and count audio length: @receiver(pre_save, sender=Meditation) def setLengthMeditation(sender, **kwargs): meditation = kwargs['instance'] if kwargs['update_fields']: audio = mp4.MP4(meditation.audio) length = audio.info.length meditation.length = length @receiver(post_save, sender=Meditation) def setLengthToCourse(sender, **kwargs): meditation = kwargs['instance'] if not kwargs['update_fields']: newPath = meditation.audio.name.split('.')[0] + '.m4a' command = 'ffmpeg -i {} -movflags +faststart -b:a 128K -af "afade=t=in:st=0:d=2" {}'.format(meditation.audio.name, newPath) subprocess.call(command, shell=True) meditation.audio = File(open(newPath, 'rb')) meditation.save(update_fields=['audio', 'length']) So, as u can see, when I convert audio from any format to .m4a I try to point new audio to existing model: command = 'ffmpeg -i {} -movflags +faststart -b:a 128K -af "afade=t=in:st=0:d=2" {}'.format(meditation.audio.name, newPath) subprocess.call(command, shell=True) meditation.audio = File(open(newPath, 'rb')) The problem is, when I point model to existing file, Django saves it in "upload_to" and it comes like upload_to {Audiotracks/} + file.name {AudioTracks/file.m4a} = AudioTracks/AudioTracks/file.m4a The question is, can I somehow make Django not make copy of a file OR cut path on saving so no duplication will happen -
How to store dark-mode choice in cookies in Django?
I have the following script NioApp.ModeSwitch = function() { var toggle = $('.dark-switch'); if($body.hasClass('dark-mode')){ toggle.addClass('active'); }else { toggle.removeClass('active'); } toggle.on('click', function(e){ e.preventDefault(); $(this).toggleClass('active'); $body.toggleClass('dark-mode'); }) } Which changes the website to dark-mode, through this toogle <li><a class="dark-switch" href="#"><em class="icon ni ni-moon"></em><span>Modo Nocturno</span></a></li> How can I, in Django, store this in a cookie, so that it remembers the user option? -
Django Forms: Select Widget removes options
I have a model roomTypes which I use as a ForeignKey in Booking class roomType(models.Model): title = models.CharField(max_length=32, default="Single Bed") price = models.DecimalField(default=0, max_digits=5, decimal_places=2) def __str__(self): return self.title class Booking(models.Model): author = models.ForeignKey( "User", on_delete=models.CASCADE, default=None) hotelName = models.CharField(max_length=32, default=None) includeBreakfast = models.BooleanField(default=False,) roomType = models.ForeignKey( 'roomType', default=None, on_delete=models.CASCADE, related_name="roomtypes", widgets={models.Sele}) includeDinner = models.BooleanField(default=False) noOfNights = models.IntegerField(default=1) totalPrice = models.DecimalField( default=0, blank=True, null=True, max_digits=10, decimal_places=2) date = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.author.username} booked a room in {self.hotelName}" when using a modelForm, I used the Select widget to add an id for javascript querySelector use self.fields['roomType'].widget = Select(attrs={ 'id': 'roomType', }) but as I added this, all the options on the form disappear. What do? -
How to filter queryset with one lookup field on mutiple fields in django-filter
Lets say I have 2 fields ["id", "name"]. I want to filter my queryset in my ModelViewSet by using django-filter. Here is my custom FilterSet: from django_filters import rest_framework as filters from store.models import Partner class PartnerFilter(filters.FilterSet): """ Custom Partner Filter Set """ name = filters.CharFilter(field_name="name", lookup_expr="icontains") class Meta: model = Partner fields = ["id", "name"] And This is my ModelViewSet: class PartnerViewSet(ModelViewSet): """ Partner View Set """ serializer_class = PartnerSerializer queryset = Partner.objects.select_related("user").all() permission_classes = [IsAuthenticated,] authentication_classes = [SessionAuthentication] filter_backends = [DjangoFilterBackend,] filterset_class = PartnerFilter What I need is to filter queryset by using only one query string. I don't want my url to be like .../?id=&name=string. I want something like that: .../?search=search_value and if it matches any id then it gets the object by id or if it matches with name then it gets object by name. How can I implement this in django-filter? Is there a way to do it without overriding get_queryset method in ModelViewSet? -
I want to redirect my tinyurl to original url. TinyUrl is generated and rendered successfully, But when i copy and search it on browser, it says Error
I am trying to create short urls for products. The short urls are generated and rendered successfully to the templates, But everytime, it doesnot generate unique short urls, its the same for each product and different for other products. After I got my short URL , i copied it and search it in the browser, It says Server Not Found. I want to redirect those short urls to original urls Below, I am posting functions and urls, please help me get with it. Views.py #Display individual product and render short links for all using pyshorteners def link_view(request, uid): results = AffProduct.objects.get(uid=uid) slink = request.get_full_path() shortener = pyshorteners.Shortener() short_link = shortener.tinyurl.short(slink) return render(request, 'link.html', {"results": results, "short_link": short_link}) Urls.py urlpatterns = [ path('link/', views.link, name='link'), path('link/<int:uid>/', views.link_view, name='link_view') ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Also the address bar in the browser shows: 'affiliation/link/10004/', the localhost has been missed out -
RFID scanner in HTML input field
I'm writing a project on Django and I have the registration template. There I have a field 'RFID' which now can only be filled manually. I need to make this field scan RFID tag automatically right inside that field. When I touch rfid to scanner field in HTML should be filled without typing RFID by hands. If it's possible to do, how I should do it? I've tried to find how to realize it but there is no helpful information across internet. This is my registration form — https://i.stack.imgur.com/17BIn.png -
Form variable for django CreateView
Heads-Up: I don't know if this is a duplicate, but all the questions that StackOverflow said to be similar are not mine. Hi, I have a django model called Post (I am doing the usual 'blog' website, since I am still learning). I am creating a CreateView for it (django.views.generic) to create more posts. My problem is that I want to pass in string as a context variable. This can be done with context_object_name or the function get_context_data. But, to create the form that CreateView automatically generates, it passes a context variable called form. Since I am passing my own context data, the CreateView's form context variable gets overwritten. So, what I am asking is, what is the name of that form variable (if there is) that I can pass into the context data dictionary like {'string': my_string, form: createView_form_variable}. Any help on this would be appreciated - Thanks in advance. P.S. Please comment if I have not made things clear -
Django - NOT NULL constraint failed
I'm currently working on a Django app that will parse the contents of an uploaded log file to the associated database in my Django project. I've managed to get it all running as expected except it won't associate my uploaded data with the model's ForeignKey. I can assign null=True which resolves the integrity error but then of course, it doesn't assign any of the uploaded data to that ForeignKey. Here's the code: models.py class Case(models.Model): case_ref = models.CharField(max_length=8) oic = models.CharField(max_length=50) subject = models.CharField(max_length=100) submitted_date = models.DateTimeField(default=datetime.now, blank=True) def get_absolute_url(self): return reverse('case_list', kwargs={'pk': self.pk}) def __str__(self): return self.case_ref + " " + self.subject class TeamviewerLogs(models.Model): case = models.ForeignKey(Case, on_delete=models.DO_NOTHING) teamviewer_id = models.IntegerField() teamviewer_name = models.TextField() connection_start = models.TextField() connection_end = models.TextField() local_user = models.TextField() connection_type = models.TextField() unique_id = models.TextField() def get_absolute_url(self): return reverse('case_list', kwargs={'pk': self.pk}) def __str__(self): return str(self.teamviewer_id) + " - " + str(self.teamviewer_id) forms.py class UploadLog(forms.ModelForm): file = forms.FileField() class Meta: model = TeamviewerLogs fields = [ 'file' ] views.py def add_logs(request, pk): case = get_object_or_404(Case, pk=pk) if request.method == 'POST': form = UploadLog(request.POST, request.FILES) if form.is_valid(): teamviewer = form.save(commit=False) teamviewer.case = case log_file = request.FILES['file'] log_file = filter(None, (line.rstrip() for line in log_file)) for lines in … -
Django[AJAX] build url from Django Model
Hello friends, I am building a website with Django, I decided to create a filter for my items, you can filter items like this: Item.objects.filter(type=item_type), so basically I created an url which takes a slug:item_type, and returns a JsonResponse with the items parsed as JSON. Then I created an Ajax call in my js file and when I wanted to call the url to filter by type I keep getting an error: function filterItemType(type) { $.ajax({ type: "GET", data: $(this).serialize(), url: "{% url 'boring:filter_items' type%}", ... The Error: Not Found: /boring/{% url 'boring:filter_items' type%} [21/Jun/2021 11:32:54] "GET /boring/%7B%%20url%20'boring:filter_items'%20type%%7D HTTP/1.1" 404 6103 So basically, for my understanding, JS is not parsing the Django {% url .... %}. I have no idea how to do it in order for JS to build the route...like I usually do it in the Templates... PS: I also tried to build the route with the type separated as -> url: "{% url 'boring:filter_items' %}" + "/"+ type; But it's not working either, same error. Github Issue for this matter... -
Redirect a POST request with all the data to a url
Is there a way to redirect on POST request to another URL with all the data. # views.py @verified_email_required def user_page(request, pk, username): if request.method == 'POST': if request.POST.get('_name', '') == 'toggle_pin': auth_profile = Profile.objects.filter(user=request.user).first() profile = Profile.objects.filter(pk=int(request.POST.get('profile', ''))).first() fav = Favourite.objects.filter(profile=auth_profile, pinned_profile=profile).first() if fav.pinned == True: fav.pinned = False else: fav.pinned = True fav.save() return JsonResponse(data={ 'status': fav.pinned, }) # page profile (Profile of the user who's page being is visited) # (also give 404 error if user does not exists) page_user = get_object_or_404(User, pk=pk) if (page_user.username != username): return redirect(f'/u/{page_user.pk}-{page_user.username}/') # page profile page_profile = Profile.objects.filter(user=page_user).first() context = { 'page_profile': page_profile, } return render(request, 'user/profile.html', context) @verified_email_required def redirect_profile_page(request, pk): if request.method == 'POST': # storing the POST data in session is not a good practice # Waht can we do else request.session['_old_post'] = request.POST return redirect(f'/u/{page_user.pk}-{page_user.username}/') page_user = get_object_or_404(User, pk=pk) return redirect(f'/u/{page_user.pk}-{page_user.username}/') In the redirect_profile_page view I redirect users to the user_page view on GET request. How do I do this in a POST request? Any help is highly appreciated! Thank you. -
Django not using updated urls.py - returning 404 on www.site.com/page with outdated list
I am very new to django and beginning to understand some of the framework however view-route binding is confusing me There is a persistent issue that when I try to visit any url except for the homepage and /admin I receive a 404, including routes I have declared in my project's urls.py file also i am following this mdn tutorial project urls.py """trends URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.views.generic import RedirectView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('articles/', include('articles.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) app named 'articles' urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] app named 'articles' views.py from django.shortcuts import render from django.http … -
After i write form media in html template, i cannot upload everything
I want to add ckeditor5 in my template ,so i add {{form.media}} to my template. After writing {{form.media}} code , i cannot upload everything. It seems input tag not fuction it. Please help me to figure out what happened!! THX~~ my code is down below: view def post(request): Form = PostForm() if request.method == 'POST': Form = PostForm(request.POST) Form.save() return render(request, "Upload_done.html") else: return render(request, "upload.html", {'Form': Form}) html <form action="" method="POST" enctype="multipart/form-data">{% csrf_token %} {{ Form.media }} {{ Form.as_p }} <input type="submit" value="Upload"> form class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content'] model class Post(models.Model): title = models.CharField(max_length=100) content = CKEditor5Field(config_name='extends') created_at = models.DateTimeField(auto_now_add=True) -
How to change form field label in Django using template language only?
I have tried using django-widget-tweaks to override default form field attributes, where you can set various form field attributes like this: {{ form.username|attr:"name:email"|as_crispy_field}} but when I inspect the element in the Chrome Dev Tools I can see that the element still has the default username name attribute. I was trying to change the name attribute so that the label for this field would display "Email" instead of "Username". So I was wondering if there is a way to change Django form field label using Django template language only? 3rd party tools are OK too. -
Group by specific attribute in Django using ORM
I have a model as below: class Revenue(BaseModel): revenue_type = models.ForeignKey(RevenueType, blank=True, null=True, max_length=256, on_delete=models.SET_NULL, related_name='revenue') external_account_id = models.CharField(blank=True, null=True, max_length=256) external_user_id = models.CharField(blank=True, null=True, max_length=256) Now I want to get all the revenues ids but grouped by similar external_account_id. Suppose the below are the model instances details: revenue1 = Revenue("external_account_id": 1, "external_user_id": 1) revenue2 = Revenue("external_account_id": 1, "external_user_id": 2) revenue3 = Revenue("external_account_id": 1, "external_user_id": 3) revenue4 = Revenue("external_account_id": 1, "external_user_id": 4) revenue5 = Revenue("external_account_id": 2, "external_user_id": 5) revenue6 = Revenue("external_account_id": 2, "external_user_id": 6) revenue7 = Revenue("external_account_id": 3, "external_user_id": 7) revenue8 = Revenue("external_account_id": 3, "external_user_id": 8) revenue9 = Revenue("external_account_id": 4, "external_user_id": 9) revenue10 = Revenue("external_account_id": 5, "external_user_id": 10) I want the queryset or dict like this: {1: [1, 2, 3, 4], 2: [5, 6], 3: [7, 8], 4: [9], 5: [10]} Where the keys are the external_account_id and the values are either external_user_id or ids of the model instances. How can I query for the same? -
How to add custom fields to Registration form in django
from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField from django.contrib.auth.models import User from django.forms.widgets import Widget from django.utils.translation import gettext, gettext_lazy as _ from .models import Post class SignUpForm(UserCreationForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class':'form-control'})) password2 = forms.CharField(label='Confirm Password (again)', widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email'] labels = {'first_name': 'First Name', 'last_name': 'Last Name', 'email': 'Email'} widgets = {'username':forms.TextInput(attrs={'class':'form-control'}), 'first_name':forms.TextInput(attrs={'class':'form-control'}), 'last_name':forms.TextInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), } class LoginForm(AuthenticationForm): username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True, 'class':'form-control'})) password = forms.CharField(label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'current-password', 'class':'form-control'})) class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'desc'] labels = {'title':'Title', 'desc':'Description'} widgets = {'title':forms.TextInput(attrs={'class':'form-control'}), 'desc':forms.Textarea(attrs={'class':'form-control'}), } This is my forms.py file from django.db import models # Create your models here. class Post(models.Model): title = models.CharField(max_length=150) desc = models.TextField() This is my models.py file Now I want to create a table for SignUpForm and add some extra fields to it like gender and standard and save it to database I try to and gender and std but it didn't save the values to database what should I do ? from django.shortcuts import render, HttpResponseRedirect from .forms import SignUpForm, LoginForm, PostForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from .models import Post … -
"Change password system" does not work in user authentication.(Django)
I'm trying to configure Django app with a user authentication model(django-allauth). It almost works well but when a user tries to change his password, a problem occurs. Let's say when a user want to change his password, he goes to Password reset page Example http://3.129.xx.xxx/accounts/password/reset/ He put his Email address on the form and submit, then he recieve a "Password Reset E-mail" with a link to reset the password. Example https://u22207100.ct.sendgrid.net/ls/click?upn=EGpFlOkd4a3JZnFjHjqKqsCiiinSf51vqFvV..... Cliking above link, the user redirected to http://3.129.xx.xxx/accounts/password/reset/key/1-set-password/ But that page has only links "Sign In" and "Sign Up". It does not have any form to put new password the user want to set. Change password page's image In this situation, the user can not change password. should I set something to allauth system?? I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
How to save a form and call an URL with one button in Django?
I created a form in my Django project. I want to save and call an URL with the same submit button. Firstly, I used action method in my form, when I click the send button it calls the URL but it do not save the form and when I remove the action, it saves the form. I do not know why. How can I call an URL after/when saving the form? ocr/views.py def approval_page(request, id): ... form_approval = LeadApprovalForm(request.POST) if request.method == 'POST': if form_approval.is_valid(): lead_approval = form_approval.save() lead_approval.user = request.user lead_approval.approval_id = approval lead_approval.rank = request.POST.get('rank_name', None) lead_approval.save() redirect('approvals:approve_pending', pk=approval.pk) else: form_approval = LeadApprovalForm() ... return render(request, 'approval_page.html', context) approval_page.html <form method="POST" enctype="multipart/form-data" class="lead_form" id="lead_form" action="{% url 'approvals:approve_pending' pk=approval.pk%}" > <!-- Very Important csrf Token --> {% csrf_token %} {{ form_approval.media }} {{ form_approval|crispy }} <input type="hidden" name="rank_name" value="{{ waiting.rank.rank_name }}" /> <button type="submit" class="btn btn-success btn-xs" onclick=" window.open('{% url 'approvals:approve_pending' pk=approval.pk%}', '_self');">Submit</button> <a href="{% url 'approvals:decline_pending' pk=approval.pk%}"> <button class="btn btn-danger btn-xs" id="approve-btn">Decline</button> </a> </form> approvals/views.py def approve_pending(request, pk): pending_approval = ApprovalProcess.objects.get(pk=pk) customer = pending_approval.doc_id.owner pdf = pending_approval.doc_id priority_number = 0 if request.user.rank.rank_name == 'Analyst': priority_number = 1 if request.user.rank.rank_name == 'Senior Analyst': priority_number = 2 if request.user.rank.rank_name == … -
Django on IIS WinServer 2012R2 with python 3.9 WSGI Handler error
I'm trying to setup an IIS website following this guide I'm getting the following error: Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\Python39\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\Python39\Lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\Python39\Lib\site-packages\wfastcgi.py", line 586, in get_wsgi_handler raise Exception('WSGI_HANDLER env var must be set') Exception: WSGI_HANDLER env var must be set StdOut: StdErr: I believe the error might be on the web.config, which is the following: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python39\python.exe|C:\Python39\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="django_project.wsgi.application" /> <!-- Your django path --> <add key="PYTHONPATH" value="C:\django_project" /> <!-- Your djangoname.settings --> <add key="DJANGO_SETTINGS_MODULE" value="django_project.settings" /> </appSettings> </configuration> my folder structure is the following: C:\Python39\python.exe C:\Python39\Lib\site-packages\wfastcgi.py C:\inetpub\wwwroot\web.config C:\django_project that has the following: and I have created the FastCGI settings with: and Handler Mapping with: (the request restriction has the invoce box unticked) I don't know what else could I be missing to set here. -
Paypal Integration Django Rest Api/ Android Client
i am trying to implement a Paypal payment system. I am working with a Django Server API and my client is an android Kotlin app. My question is, where is the best spot to implement the paypal integration. Is it secure to implement it on the client side, because hackers could change the amount of money for example. But on the other hand how could I implement it server-side logically and the customer could use it on his mobile device. Thanks for help. -
how to perform some expression in django project
I am New In This python and Django i want to make some expression quary in my project active expire or expire soon how can i do that please help me here is my mosel class > def status_active_dactive(self): > recived_date = self.received_date > user_rec_date = recived_date.strftime("%m/%d/%Y") > time_today = datetime.datetime.now().date() > one_month = time_today + datetime.timedelta(days=30) > five_day = time_today + datetime.timedelta(days=1) > day_five = five_day.strftime("%m/%d/%Y") > month = one_month.strftime("%m/%d/%Y") > expire = "Expire in" > Active = "Active" > expire_soon = "Expire Soon" > if day_five >= user_rec_date != month: > return Active > elif day_five == user_rec_date != month: > return expire_soon -
How do I change the CheckboxSelectMultiple in django admin as side to side instead of stacked on top of each other?
I had to convert the default representation of Many-to-many fields from being represented as HTML to CheckboxSelectMultiple using : from django.forms import CheckboxSelectMultiple # Register your models here. class UserPreferenceAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {"widget": CheckboxSelectMultiple}, } admin.site.register(UserPreference, UserPreferenceAdmin) However the checkboxes are places on top of each other and I would like to stack them side to side.