Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Filter value of model Field based on other model field value in django?
I have a model: class Employee(models.Model): name = models.CharField(max_length=128) nic = models.CharField(max_length=25, unique=True) def __str__(self) -> str: return self.name class Team(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField("Employee") def __str__(self) -> str: return self.name class Standup(models.Model): team = models.ForeignKey("Team", on_delete=models.CASCADE) employee = models.ForeignKey("Employee", on_delete=models.CASCADE) work_done = models.DateTimeField(auto_now=True) This is the ViewSet: class StandupViewSet(ModelViewSet): serializer_class = serializers.StandupSerializer queryset = Standup.objects.all() Now when I hit the API to post the data of standup, Standup.employee should display only those employees which are in a particular meeting, it should not display all the employees. Information about a particular team will be retrieved from Standup.team, and Standup.employee should display these employees: Standup.team.members. We will select one employee from the subset of employee list, instead of selecting employee from all the employees. It can be changed dynamically based on the value of Standup.team. Please guide. -
Got an error creating the test database: duplicate key value violates unique constraint "pg_database_datname_index"
Complete Error: Creating test database for alias 'default'... Got an error creating the test database: duplicate key value violates unique constraint "pg_database_datname_index" DETAIL: Key (datname)=(test_chat_app) already exists. I added the pre commit hook in Python-Django to run testcases before commit. It is working fine on my side, but when my collegues trying to commit, the above error occurs. Test cases run successfully but this error doesn't let the commit to complete. I have tried dropping and then recreating database, but in vain. Can anyone help me with this, I am attaching screenshot for setting up pre commit hook. just setup this hook. Working fine on my side, but not on my collegues side I have tried dropping and then recreating database, but in vain. -
I am not getting capture in variables of a form made with django, to put them in a python script
The full stack it's already done, django is running in a server, the views are done,all done, that from is linked in a db, i just uploaded the script.py that will use the variables from that form.I have tried the similar solutions that I found here and nothing worked. the project repository: https://github.com/Mayri1/djangoPrimerProyecto.git My failed attempt: from django import usuarios import paramiko import time HOST = '' PORT ='22' USER = 'xxxxx' PASS= '' datos =dict(hostname=HOST, port=PORT, username=USER)"""if __name__ == '__main__':*# try:*client = paramiko.SSHClient() client.connect(HOST, PORT, USER, PASS, banner_timeout=200) stdin, stdout, stderr = client.exec_command("ppp secret add name=\"" + {{ usuarios.nombre }} +"\" password=\"" + {{ usuarios.contraseña }} +"\" profile=OVPN service=ovpn") time.sleep(1) result = stdout.read().decode()# except paramiko.ssh_exception.AuthenticationException as e:# print('Autenticacion fallida')#export file=flash/prueba_export.backup to=C:\rmikrotikprint(result) Another failed attempt: #views def testing(request): mydata1 = Usuario.objects.filter(nombre='usuario.nombre').values() mydata2 = Usuario.objects.filter(contraseña='usuario.contraseña').values() template = loader.get_template('paginas/usuarios.html') context = { 'usuario': mydata1, 'contraseña': mydata2 } return HttpResponse(template.render(context, request)) In urls: path('testing',views.testing, name='testing'), Another:in views "create" if formulario.is_valid(): formulario.save() mk.recibir(formulario) return redirect('usuarios') in mk.py: def recibir(request): formulario = UsuarioForm(request.POST or None, request.FILES or None) for x, y in formulario.items(): user = x passw = y print(user, passw) return (recibir) -
File upload using Django Post method
I'm trying to post a file from remote server to client server. This can be a large file sometime upto 20k lines. And then store it in the client server for further processing using pandas. Example file.txt: A*B*C* D*E*F* G*H*I* I was able to do the file transfer using the below snippet in my views.py class FileUploadView(APIView): parser_classes = (FileUploadParser, ) def post(self, request, format=None): up_file = request.FILES['file'] destination = open('/home/xxx/' + up_file.name, 'wb+') for row in up_file.chunks(): destination.write(row) destination.close() return Response(up_file.name, status.HTTP_201_CREATED) But then again, the file seems to be in binary format for the obvious reasons that the file open mode was binary.. and at the same time when i open the file all the line from the file seem to be in a single line instead of being separated by a new line. output.txt A*B*C*D*E*F*G*H*I* Any pointer on how this can be avoided and is there a way i can do the pandas processing for each line efficiently without impacting performance within the post block itslef? -
Problem with sso-login in Django, Error GET /authorize/?token= HTTP/1.1"404 250
I am trying to run simple Django application. I have already installed simple-sso module in my local app. I tried but not solved. Following images tell us that error is occured when i run localserver. enter image description here enter image description here Following code is some of "settings.py": INSTALLED_APPS = [ 'ssoLogin.apps.ssoLoginConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'simple_sso.sso_server', ] ROOT_URLCONF = 'ssoLogin.urls' # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] SSO_PRIVATE_KEY='ttVCo7bewsATjEPS7CNHd4tIk1ayyBKb1qbPk5DxWZiK4pvyLZQtnpinjPh6fWr3' SSO_PUBLIC_KEY='hGtAakAg7Sh3SffSs2obwAAflMuzbbLBUJUHpk6WrFnxhA9b78EHNoTOr0DsDho3' SSO_SERVER='http://127.0.0.1:8000/server' I used "simple-sso" module correctly according to documentation. I think everything of config(settings.py) is ok but i don't know urls and views are correct. Anyway this is my configuration in urls.py. Following code: from django.contrib import admin from django.urls import path, include, re_path from simple_sso.sso_server.server import Server from simple_sso.sso_client.client import Client from django.conf import settings test_client = Client(settings.SSO_SERVER, settings.SSO_PUBLIC_KEY, settings.SSO_PRIVATE_KEY) test_server = Server() urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), re_path(r'^server/', include(test_server.get_urls())), re_path(r'^client/', include(test_client.get_urls())), ] Server and Client object imported correctly. I think client is working good but I dont know Server works. Maybe Server doesn't work correctly. Need to solve this. -
how to install pipfile packages with pipenv?
I use mac m1. i install the latest version of python(3.11) also i install pipenv with this command: brew install pipenv. also i install rosetta. but when i enter this commands: pipenv shell pipenv install I got this error meesage: Installing dependencies from Pipfile.lock (1fd85c)... An error occurred while installing asgiref==3.5.2 ; python_version >= '3.7' --hash=sha256:4a29362a6acebe09bf1d6640db38c1dc3d9217c68e6f9f6204d72667fc19a424 --hash=sha256:1d2880b792ae8757289136f1db2b7b99100ce959b2aa57fd69dab783d05afac4! Will try again. An error occurred while installing asttokens==2.0.8 --hash=sha256:e3305297c744ae53ffa032c45dc347286165e4ffce6875dc662b205db0623d86 --hash=sha256:c61e16246ecfb2cde2958406b4c8ebc043c9e6d73aaa83c941673b35e5d3a76b! Will try again. An error occurred while installing crispy-tailwind==0.5.0 --hash=sha256:65cfcdf8dce96be37c99578e2688ed2d0067e6ff633baaf657358b3b3be052c7 --hash=sha256:0041c85b73b0a197e312ab969bd505aa1f96752a6a50324377287c2b6be3c0cb! Will try again. An error occurred while installing decorator==5.1.1 ; python_version >= '3.5' --hash=sha256:637996211036b6385ef91435e4fae22989472f9d571faba8927ba8253acbc330 --hash=sha256:b8c3f85900b9dc423225913c5aace94729fe1fa9763b38939a95226f02d37186! Will try again. An error occurred while installing dj-database-url==1.0.0 --hash=sha256:cd354a3b7a9136d78d64c17b2aec369e2ae5616fbca6bfbe435ef15bb372ce39 --hash=sha256:ccf3e8718f75ddd147a1e212fca88eecdaa721759ee48e38b485481c77bca3dc! Will try again. An error occurred while installing django==4.1 --hash=sha256:032f8a6fc7cf05ccd1214e4a2e21dfcd6a23b9d575c6573cacc8c67828dbe642 --hash=sha256:031ccb717782f6af83a0063a1957686e87cb4581ea61b47b3e9addf60687989a! Will try again. An error occurred while installing django-appconf==1.0.5 ; python_version >= '3.1' --hash=sha256:be3db0be6c81fa84742000b89a81c016d70ae66a7ccb620cdef592b1f1a6aaa4 --hash=sha256:ae9f864ee1958c815a965ed63b3fba4874eec13de10236ba063a788f9a17389d! Will try again. An error occurred while installing django-crispy-forms==1.14.0 --hash=sha256:35887b8851a931374dd697207a8f56c57a9c5cb9dbf0b9fa54314da5666cea5b --hash=sha256:bc4d2037f6de602d39c0bc452ac3029d1f5d65e88458872cc4dbc01c3a400604! Will try again. An error occurred while installing django-extensions==3.2.0 --hash=sha256:4c234a7236e9e41c17d9036f6dae7a3a9b212527105b8a0d24b2459b267825f0 --hash=sha256:7dc7cd1da50d83b76447a58f5d7e5c8e6cd83f21e9b7e5f97e6b644f4d4e21a6! Will try again. An error occurred while installing django-jalali-date==1.0.1 --hash=sha256:bb872f58c2b956fb49e26abec5d13753179bc30a7304424adb102672473c1f74! Will try again. An error occurred while installing django-quill-editor==0.1.40 --hash=sha256:276bf3e344531c923b82012f04cec8373c3239d9f7124d4f2bce5f8c5f2b5749 --hash=sha256:26b42aef27168517898c25207d22202402e2816d4a1fa9e3fcc083ae1da0a70c! Will try again. An error occurred while installing django-widget-tweaks==1.4.12 --hash=sha256:fe6b17d5d595c63331f300917980db2afcf71f240ab9341b954aea8f45d25b9a --hash=sha256:9bfc5c705684754a83cc81da328b39ad1b80f32bd0f4340e2a810cbab4b0c00e! Will try again. An error occurred while installing djangorestframework==3.13.1 ; python_version >= '3.6' --hash=sha256:24c4bf58ed7e85d1fe4ba250ab2da926d263cd57d64b03e8dcef0ac683f8b1aa --hash=sha256:0c33407ce23acc68eca2a6e46424b008c9c02eceb8cf18581921d0092bc1f2ee! … -
Django api giving Invalid Padding error for multi api
In my project, multiple apis have started giving Invalid padding errors at the same time I don't know if this error is coming can anyone help or guide me through this problem -
How to get the last record with a condition in Django
I am trying to get the last record of the table in Django with a condition. Model: Rooms id room staff_id 1 103 1000 2 105 1000 3 107 1555 the staff (number 1000) has two records, but I want to get just the last record of him. getStaffRecords = Rooms.objects.get(staff_id=1000) staffRoom = getStaffRecords.room and here I get an error, because I have more than one record. Error: get() returned more than one Rooms-- it returned 2! Anybody has a solution? I tried to use the methode like this: getStaffRecords = Rooms.objects.get(staff_id=1000).last() staffRoom = getStaffRecords.room but it didn't work, bcause in this case, "get" isn't recognized by Django. -
How to insert a value from a dict in a django annotation using each id from queryset
I have a simple dict containing ids with values associated like: {1:True, 2:False} I also have a queryset that have the same ids listed above in an atribute named user_id, but I need to add a new field to my objects on queryset with the values from my dict. Lets suppose the field I want to add is called is_admin, so I need to create a field on the object with id 1 on my queryset with the value True. What I tried to do is: my_dict= {1:True, 2:False} queryset = queryset.annotate( is_admin=Value(my_dict.get(F("user_id")), output_field=BooleanField()) ) But what happen is that I'm receiving null on is_admin. I tried to do the code below and it works: queryset = queryset.annotate( is_admin=Value(my_dict.get(1), output_field=BooleanField()) ) So I think is something wrong with my use of F expression. I will appreciate any help. -
how to have a TimeField with auto increment of 5 minutes (django)
I have a model in django that consists of these fields: device = models.CharField(max_length=150, null=True) time_received = models.TimeField(auto_now_add=True, null=True) display_time = [ i want it to have same hour as time_received , minute to be started at 00 and then have interval of 5 and finally second to be 00 ] the reason i want to do this , is to display time in an orderly manner. for example: device A is received at 8:01:20 ---> device A is shown as 8:00:00 device A is received at 8:07:22 ---> device A is shown as 8:05:00 one final note: I need to store both display time and received time in postgresql thanks for helping -
Centralised Django Web application ideas
I have a djnago web server for webservices (Djnago+Gunocrn+Nginx) which connects to one client URL and provide servers. My requirement is, I have multiple clients on different environment. So we are planning to setup a centralised Django server with (Djnago+Supervisor+Gunocrn+Nginx) setup. Please share some idea on what shoule be considred and best practices. Ideas and Suggestions -
My access to Google Sheets API is being blocked to a URI Redirect Mismatch
I am unable to access my Google sheet, here is the error I get: Error 400: redirect_uri_mismatch You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy. If you're the app developer, register the redirect URI in the Google Cloud Console. Request details: redirect_uri=http://localhost:57592/ Below I'll share my code, relevant parts of the credentails file as well as my Google Cloud console configurations I have in place. Just to note, From my inexperienced eyes (as far as python and google console is concerned), it seems as if I've checked the right boxes based on what I've found on StackOverflow. PYTHON: from __future__ import print_function from datetime import datetime import pickle import os.path import pyodbc from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # connecting to the database connection_string = 'DRIVER={driver};PORT=1433;SERVER={server};DATABASE={database};UID={username};PWD={password}; MARS_Connection={con}'.format(driver= 'ODBC Driver 17 for SQL Server', server= server, database= database, username=username, password=password, con='Yes') conn = pyodbc.connect(connection_string) print("Connected to the database successfully") # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] # The ID and range of a sample spreadsheet. # https://docs.google.com/spreadsheets/d/spreadsheetId/edit#gid=0 SPREADSHEET_ID = spreadSheetID RANGE_NAME = 'CAPS!A2:K' #def dataUpload(): def dataUpload(): creds = None # The … -
Wagtail: Limit choice dynamically based on current object
How can I limit the choices for the districtobject field in wagtail admin? class DistrictPage(Page): districtobject = models.ForeignKey(DistrictTranslated, on_delete=models.SET_NULL, null=True, blank=True) I know that I can use "limit_choices_to" for basic limitations with Q. But I want to use a more dynamic approach which allows me to use the "content" of the current object. (Like self.attribute ... etc) For example: def my_limit_function(self): 1. get parent page 2. read date from parent page and extract this information for a filter query -
Sorting QuerySet by a key of a JSONField is super slow
Let's say my model is: class MyModel(models.Model): code = CharField(...) dynamic_columns = JSONField(null=False, default=dict, encoder=DjangoJSONEncoder) This : MyModel.objects.all().order_by("dynamic_columns__some_key") goes a loooot slower than MyModel.objects.all().order_by("code") I know it's not a surprising result, however are there tricks to optimize the first operation ? Like would defining the schema of dynamic_columns somehow help ? Thanks in advance ! -
Django app with pandas processing not loading specific page on railway.app but runs fine locally, How to troubleshoot?
I am facing an issue where my Django application, that uses pandas processing code, is not loading a specific page when deployed on https://railway.app service and keeps giving an application server error, whereas it runs fine on a local server but takes more than 10-11 seconds for loading the specific page. I would like to know the possible causes of this issue and how can I troubleshoot it. Note: I am using an API build with Django Rest framework. View that renders the pandas processed data: def nsebse(request): if request.user.is_authenticated: endpoint1 = rq.get('https://stockindex.up.railway.app/api/bse/').json() endpoint2 = rq.get('https://stockindex.up.railway.app/api/nse/').json() bseData = helperForBSENSE(endpoint1) nseData = helperForBSENSE(endpoint2) return render(request,'nsebse.html',{'bseData':bseData,'nseData':nseData}) else: return render(request,'notauth.html') Helper function used in above segment: def helperForBSENSE(data): df = pd.DataFrame(columns = ['id','date','open','high','low','close','adj_close','volume']) for i in range(len(data)): item = data[i] df.loc[i] = [item['id'],item['date'],item['open'],item['high'],item['low'],item['close'],item['adj_close'],item['volume']] df['date']= pd.to_datetime(df['date']) today, req_day = datetime(2023,1,12), datetime(2022,1,12) one_year_df = df[(df['date'] <= today) & (df['date'] > req_day)] fifty_two_week_high = max(one_year_df['high']) fifty_two_week_low = min(one_year_df['low']) day_high = df[df['date']==today]['high'] day_low = df[df['date']==today]['low'] previous_day = today - pd.Timedelta(days=1) today_close = float(df[df['date']==today]['close']) prev_close = float(df[df['date']==previous_day]['close']) today_open = float(df[df['date']==today]['open']) today_gain_or_loss = float(today_close - prev_close) data = { 'today_open':today_open, 'today_close':today_close, 'prev_close': prev_close, 'today_gain_or_loss' : today_gain_or_loss, 'day_high':float(day_high), 'day_low':float(day_low), 'fifty_two_week_high':fifty_two_week_high, 'fifty_two_week_low':fifty_two_week_low, 'xAxis':list(df['date']), 'yAxis':list(df['close']), } return data here is a live … -
Response Data isn't even showing in console. I have tried everything. But not getting a proper solution for that
I am sending request from react to django to know if we've this user or not. django is sending response back but it's not even showing in console in react. here is my React Code: const BASE_URL = 'http://127.0.0.1:8000/writter-login/' function TeacherLogin() { const[writterLoginData, setWritterLoginData] = useState({ 'writter_email' : '', 'writter_password': '' }); const handleChange = (event) => { setWritterLoginData({ ...writterLoginData, [event.target.name]:event.target.value }) } const submitForm = () => { const writterLoginFormData = new FormData(); writterLoginFormData.append('writter_email',writterLoginData.writter_email) writterLoginFormData.append('writter_password',writterLoginData.writter_password) try { axios.post(BASE_URL,writterLoginFormData).then((res) => { console.log('Found') console.log(res.data) if(res.data === true) { localStorage.setItem('writterLoginStatus',true) window.Location.href="/writter-dashboard"; } }) } catch (error) { console.log(error) } } const writterLoginStatus = localStorage.getItem('writterLoginStatus') if(writterLoginStatus === 'true'){ window.Location.href="/writter-dashboard"; } return ( <div className='App'> <Form.Label>Email address</Form.Label> <Form.Control value={writterLoginData.writter_name} onChange={handleChange} name ="writter_email" type="email" placeholder="Enter email" /> <Form.Text className="text-muted"> We'll never share your email with anyone else. </Form.Text> </Form.Group> <Form.Label>Password</Form.Label> <Form.Control value={writterLoginData.writter_password} onChange={handleChange} name ="writter_password" type="password" placeholder="Password" /> <Button onClick={submitForm} variant="success me-5" type="submit">Login </Button> ); } export default TeacherLogin; here is my django code: @csrf_exempt def WritterLoginDetails(request): writter_email = request.POST['writter_email'] writter_password = request.POST['writter_password'] writterData = models.Writter.objects.get(writter_email = writter_email, writter_password = writter_password) if writterData: print('data found') return JsonResponse({'bool':True}) else: print('no data found') return JsonResponse({'bool':False}) i have tried to console it in browser and even in network … -
Django equivalent of rails schema annotation
I moved from Rails to Django and was trying to find a library similar to https://github.com/ctran/annotate_models that annotates models using comments in Rails. Does such a library exist? It's a little hard to find due to the inbuilt annotate method in django if it does -
Django Static doesn't work on production even after collectstatic
I'm facing a problem and cannot resolve it. Looking for some advices ! Ok so locally everything works fine, i already run collect static and i collected statics files under a folder named 'static' on my django app folder : app | |- app |- app n°2 |- static So running locally, not a single error and admin have css While i push on production, my app run , proxy (nginx) run ... However, while connectinf to example.com/admin/, css not running my logs from proxy give me this ... "GET /app/static/admin/css/responsive.css HTTP/1.1" 404 179 "https://example.com/admin/login/?next=/admin/" An error 404 occur ? Here is what's my setting.py looks like STATIC_URL = '/app/static/' STATIC_ROOT = '/app/static' Any help will be welcome, i would like to understand the error ! Thank a lot Cheers -
DjangoModelPermissions not working with DRF
I am trying to use Django Rest Framework and face a problem. The problem is when i try to use DjangoModelPermissions it doesn't follow the permission from Django admin panel. What I excepted, is that when I set permission Projects|projects|can view projects then user can see the output. Here are my codes: Views.py from rest_framework import viewsets from rest_framework.permissions import IsAdminUser, IsAuthenticated, DjangoModelPermissions from django.shortcuts import get_object_or_404 from rest_framework.response import Response from .models import Projects from .serializers import ProjectSerializer class ProjectsViewSet(viewsets.ViewSet): permission_classes_by_action = {'list': [DjangoModelPermissions]} queryset = Projects.objects.none() serializer_class = ProjectSerializer def list(self, request): queryset = Projects.objects.all() serializer = ProjectSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Projects.objects.all() project = get_object_or_404(queryset, pk=pk) serializer = ProjectSerializer(project) return Response(serializer.data) def get_permissions(self): try: return [permission() for permission in self.permission_classes_by_action[self]] except KeyError: return [permission() for permission in self.permission_classes] serializers.py from rest_framework import serializers from .models import Projects class ProjectSerializer(serializers.ModelSerializer): def create(self, validated_data): pass def update(self, instance, validated_data): pass class Meta: model = Projects fields = ('id','name') Django admin site permission for the user: [] Output HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "name": "proj 1" }, { "id": 2, "name": "proj 222" } ] … -
Reverse Inlines in Django Admin for Many to Many
Apologies if this has been asked before and my searches have not uncovered the solution. I'm looking to include admin inlines for two models. Django version is 4.1.4 class Book(models.Model): title = models.CharField(max_length=100) author_series = models.CharField(max_length=100, blank=True, null=True) series = models.ManyToManyField(Series) class Series(models.Model): name = models.CharField(max_length=100, blank=True, null=True) category = models.CharField(max_length=50) publisher = models.CharField(max_length=100,blank=True, null=True) I'm able to complete the forward relationship successfully using Model.field.through format: class SeriesInline(admin.TabularInline): model = Book.series.through class BookAdmin(admin.ModelAdmin): inlines = [SeriesInline,] but would like the reverse as well. class InlineSeriesBooks(admin.TabularInline): model = Series.book_set ... class SeriesAdmin(admin.ModelAdmin): ... inlines = [InlineSeriesBooks] I know model = Series.book_set is wrong but all the links seem to be suggesting the former through solution such as Django Admin, accessing reverse many to many. So far I have tried: Series.book_set = The value of 'biblio.admin.InlineSeriesBooks.model' must be a Model. Series.book_set.though = AttributeError: 'ManyToManyDescriptor' object has no attribute 'though' Book.series_set.though = AttributeError: type object 'Book' has no attribute 'series_set' Thanks in advance. -
How To fix django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'localhost'")
I have tried too mch but cannot solve it i have also run the query to identified the user but still getting the error. i am stucked need some help to get out of this will be grateful i have search every where but cannot come to the specific solution -
Django-Paypal - Trying to create an instance of my order and handle payments
I've been trying to use Paypal for my e-commerce project and have not got very far over the last few days. The issue I am having is that I have the Paypal SDK script in my checkout.html, which works fine and processes the payments as expected. What I want however, is to save the details of the order(and my shipping details in checkout.html) and create a new instance in my order model. I'm getting lost with this and not sure how to proceed, so any help would be much appreciated. Views.py: from django.shortcuts import render, redirect, reverse from django.contrib import messages from django.urls import reverse from profiles.models import UserProfile from django.views.decorators.csrf import csrf_exempt from .forms import OrderForm def checkout(request): bag = request.session.get('bag', {}) if not bag: messages.error(request, "There's nothing in your bag at the moment") return redirect(reverse('products:products_list')) order_form = OrderForm() # Attempt to prefill the form with any info the user maintains in # their profile if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) order_form = OrderForm(initial={ 'first_name': profile.default_first_name, 'last_name': profile.default_last_name, 'email': profile.default_email, 'phone_number': profile.default_phone_number, 'country': profile.default_country, 'postcode': profile.default_postcode, 'city': profile.default_city, 'street_address_1': profile.default_street_address_1, 'street_address_2': profile.default_street_address_2, 'county': profile.default_county, }) template = 'checkout/checkout.html' success_url = 'https://8000-bend2525-therescuersp5-77ck14x21o2.ws-eu82.gitpod.io/checkout/thankyou' context = { 'order_form': order_form, 'success_url': success_url } return … -
Use of Django login_required decorator, how can I resume my paused view after the login succeeded?
As the title mentioned and please refer to code below. When the user is going to my_view_1 page, he will firstly be redirected to /login for a page of (user/password) input. The view function loginSub will get the user's submit and check. I didn't know how to go back to my_view_1 view after the authentication is met. @login_required(login_url='/login') def my_view_1(request ): #do sth return displaySomething(request) def login(request): context = {} #input username and password return render(request, "logpage.html", context) def loginSub(request): #check password return my_view_1(request) -
"Connection reset by peer" in python gRPC
We are sending multiple requests to a gRPC server. But every once in a while we come across "Connection reset by peer" error with UNAVAILABLE status. GRPC server: NestJS Client: Python Python version: 3.8 gRPCio version: 1.50.0 Code: # Connect to server from client: def connect_to_user_manager_server() -> AuthorizationControllerStub: channel = grpc.insecure_channel(envs.USER_MANAGER_GRPC_URL, options=( ('grpc.keepalive_time_ms', 120000), ('grpc.keepalive_permit_without_calls', True), )) stub = AuthorizationControllerStub(channel) return stub client = connect_to_user_manager_server() user_response = client.CheckAuthorization(authorizationData(authorization=token, requiredRoles=roles)) -
Dynamic Sidebar - How to add data from database to my sidebar automatically
This is my first project with Django. I am working on a scholarship system whereby the admin has the power to add new countries, which offer scholarships, to the system. Everything works well at the level of the database. I am able to add a new country and save it. However, it is automatically supposed to be added to the sidebar of the admin dashboard (templates). But this does not happen. Here is my views.py code for adding and saving a new country def add_country(request): user = request.user if request.method == 'POST': form = CountryForm(request.POST) if form.is_valid(): form.save() print(form.cleaned_data) return redirect('dashboard.html') #redirect to be changed else: form = CountryForm() return render(request, 'add-country.html', { "form":form }) class CountryListView(ListView): template_name = "base.html" models = Country context_object_name = "countrys" HTML CODE <li><a href="#" class="ttr-material-button"> <span class="ttr-icon"><i class="ti-email"></i></span> <span class="ttr-label">Countries</span> <span class="ttr-arrow-icon"><i class="fa fa-angle-down"></i></span> </a> <ul> {% for country in countrys %} <li><a href="#" class="ttr-material-button"><span class="ttr-label">{{ countrys.name }}</span></a </li> {% endfor %}