Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I tried to use FileSystemStorage in django. I have a folder named "media". I am able to get single file url with typing name. help to get all files
from django.core.files.storage import FileSystemStorage #myCode def testHome(request): fs = FileSystemStorage() fileurl = fs.url('SnagItDebug.log') print(fileurl) context = { 'filelink':fileurl } return render(request, 'home.html', context) -
Django exported csv rows values changed with commas
I have a website that has some radio buttons that depending on which one you click it downloads one database table or another. I have made a Django view and then an Ajax function in Javascript. For some reason when I select one of the radio buttons and hit the download button, all the values of the csv are changed with something like ",,,,,". Does anyone know why this happens? My views.py: def download_db(request, mode): #data = JSONParser().parse(request) #serializer = WordsTableSerializer(data=data) response = HttpResponse(content_type='text/csv') writer = csv.writer(response) if mode == 1: writer.writerow(['session_id', 'word1', 'word2', 'word3','distance_to_word12','distance_to_word13', 'distance_to_word23']) for word in WordDifferentTable.objects.all().values_list('session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23'): writer.writerow(word) response['Content-Disposition'] = 'attachment; filename="WordsDifferent.csv"' return response elif mode == 2: writer.writerow(['session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23']) for word in LogicAnaloguiesTable.objects.all().values_list('session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23'): writer.writerow(word) response['Content-Disposition'] = 'attachment; filename="ForLogicAnalogies.csv"' return response elif mode == 3: writer.writerow(['session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23']) for word in SimilarWInContextTable.objects.all().values_list('session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23'): writer.writerow(word) response['Content-Disposition'] = 'attachment; filename="ForSimilarWordInContext.csv"' return response elif mode == 0: writer.writerow(['session_id', 'word1', 'word2', 'word3']) for word in WordsTable.objects.all().values_list('session_id', 'word1', 'word2', 'word3'): writer.writerow(word) response['Content-Disposition'] = 'attachment; filename="WordsTable.csv"' return response return JsonResponse({}, status=304) The Ajax function: $( "#downloadbtn" ).click(function() … -
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process (Python/Django)
I know this question has been asked quite a bit on here, however after trying a number of solutions I am unable to figure out how to fix this issue. I am downloading images from the Google Maps API to generate maps with and without markers. I am using django-cleanup to remove files when deleted from database however the old versions wont delete. Weirdly, django-cleanup works correctly and deletes the associated image when deleting from the Django Admin page but not when deleting the file directly i.e. in file explorer and says it is open in Python. It also deletes correctly when my local server is terminated as you would expect. Traceback is as follows: Traceback (most recent call last): File "C:\Users\Ricki.Demmery\Desktop\dev\acl_acousticapp\env\lib\site-packages\django_cleanup\handlers.py", line 97, in run_on_commit file_.delete(save=False) File "C:\Users\Ricki.Demmery\Desktop\dev\acl_acousticapp\env\lib\site-packages\django\db\models\fields\files.py", line 373, in delete super().delete(save) File "C:\Users\Ricki.Demmery\Desktop\dev\acl_acousticapp\env\lib\site-packages\django\db\models\fields\files.py", line 105, in delete self.storage.delete(self.name) File "C:\Users\Ricki.Demmery\Desktop\dev\acl_acousticapp\env\lib\site-packages\django\core\files\storage.py", line 304, in delete os.remove(name) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\Ricki.Demmery\\Desktop\\dev\\acl_acousticapp\\src\\acl_ac ousticapp\\media\\projects\\9335\\gmaps_markers_5xDqMnc.png' The call in views.py is as follows: gmaps = GoogleMapsAPI() gmaps.location_img(prjID) My Google Maps class def create_styled_marker(style_options={},mkr_lat=0,mkr_lng=0): opts = ["%s:%s" % (k, v) for k, v in style_options.items()] return '|'.join(opts) + '|{mkr_lat},{mkr_lng}|'.format(mkr_lat=mkr_lat, mkr_lng=mkr_lng) … -
Django app on Google App Engine slows down after 15 requests
I deployed a Django app on Google App Engine Standard with a F4 machine. The API is doing some machine learning and the processing has a duration of around 4s in local (between 3.5 and 4s). For my use case, it would be ok to have also 4-5s delays with the deployed app. However, when I test the deployed app doing the same request multiple times, I saw that the first requests take 3-4 seconds, but after 10-15 iterations, they take around 8s. Here is the code I used to test my app: session = requests.Session() all_times = [] for i in range(50): try: t0 = time.time() resp = session.post(url_api, headers=headers, json=data) t1 = time.time() print(t1 - t0) all_times.append(t1 - t0) except Exception as e: print("Err", e) The results of the request durations are as follows: I wonder why there is this gap after 15 requests and why some points are way above the average 7-8s (e.g. 10s). I get the same pattern looking at the latency in the Google Cloud Console: What I tried I tried to change the autoscaling parameters, thinking that it could be because of the creation of instances. But I got the same pattern when … -
Python virtual environment interpreter not working on VPS
I have Django project migrated using git migration. I managed to push my work to a VPS project directory (Ubuntu 20.04) following this guide: user@host:/var/www/project.com I have installed the database, up and running, and established a NGINX server block. Now the only thing is to start to run the manage.py Now I can't figure out why python command isn't working: (env) user@host:/var/www/project.com$ python manage.py runserver Error: -bash: env/bin/python: No such file or directory -bash: env/bin/python3: No such file or directory which python returns: /usr/bin/python which python3 returns: /usr/bin/python3 using ls -l env/bin shows: python -> python3.10 python3 -> python3.10 python3.10 -> /Library/Frameworks/Python.framework/Versions/3.10/bin/python3.10 -
django copy selected data from one table to another table
Can anybody help me. I want to know if there is a good solution to moving a large amount of data filtered from one table in an oracle db to another in a mysql db. I know that you can run a query and loop over the results of it and insert it to the other database but the problem is that it may run out of memory and i'm looking for a good solution like running jobs or some asynchronous tasks. -
Django : How i can logged in by email instead of username
I want to make the email be set in the frontend of the django application 1/I have go and create this class to make the authentification based on the email class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None 2/then I have go and define the path of this class in the settings.py 3/ everything is good without error and I logged in by typing the email, But in the frontend still the label "Username" , How i can modify it please. enter image description here Here it's the Html code form login page: <form method="POST"> {% csrf_token %} <!--this protect our form against certeain attacks ,added security django rquires--> <fieldset class="form-group"> {{ form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> <small class="test-muted ml-2"> <a class="ml-2" href="{% url 'password_reset' %}">Forgot Password?</a> </small> </div> <!--- put div for a link if he is already have account---> <div class="border-top pt-3"> <small class="test-muted">Need an account? <a class="ml-2" href="{% url 'register' %}">Sign Up</a></small> <!--it a bootstrap --> </div> </form> Thanks in advance. -
how to make my trigger function to perform asyncronously to update tsvector field?
I am new to postgres. Suppose i have two models AnimalType and Animal. And i have search_vector field of type tsvector in Animal model. i created trigger that whenever i update a AnimalType row, the searchvector should update itself for every Animal related to that AnimalType. CREATE OR REPLACE FUNCTION update_animal_type() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN UPDATE animal SET search_vector = NULL WHERE animal_type_id = NEW.id; RETURN NEW; END; $$; CREATE TRIGGER animal_type_update_trigger AFTER UPDATE OF animal_type_name ON animal_type FOR EACH ROW EXECUTE PROCEDURE update_animal_type(); It takes a lot of time to update a single animal type row when we have large number of animals related to that particular animal type. Is this behaviour is synchronous or asynchronous? If it is synchronous how can i make it to behave asynchronous? -
Original exception text was: 'int' object has no attribute 'name'. in django rest framework
I am trying to call a get api but it gives me this error everytime. The error: AttributeError: Got AttributeError when attempting to get a value for field name on serializer NestedSerializer. The serializer field might be named incorrectly and not match any attribute or key on the int instance. Original exception text was: 'int' object has no attribute 'name'. My models: class Destination(models.Model): Continent_Name = ( ('Europe', 'Europe',), ('Asia', 'Asia',), ('North America', 'North America',), ('South America', 'South America',), ('Africa', 'Africa',), ('Oceania', 'Oceania',), ('Polar', 'Polar',), ('Regions', 'Regions',), ) name = models.CharField(max_length=255, unique=True) continent = models.CharField(max_length=255, choices=Continent_Name, default='Europe') top = models.BooleanField(default=False) dest_image = models.ImageField(blank=True) def __str__(self): return self.name class Package(models.Model): TOUR_TYPE = ( ('Custom-made trip with guide and/or driver', 'Custom-made trip with guide and/or driver',), ('Custom-made trip without guide and driver', 'Custom-made trip without guide and driver',), ('Group Tour', 'Group Tour',), ('Cruise Tour', 'Cruise Tour',), ) operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE) destination = models.ForeignKey(Destination, on_delete=models.CASCADE) package_name = models.CharField(max_length=255) city = models.CharField(max_length=255) featured = models.BooleanField(default=False) price = models.IntegerField(verbose_name="Price in Nrs") price_2 = models.IntegerField(verbose_name="Price in $") duration = models.IntegerField(default=5) duration_hours = models.PositiveIntegerField(blank=True,null=True,verbose_name="Hours If One day Tour") discount = models.IntegerField(verbose_name="Discount %", default=15) #discounted_price = models.IntegerField(default=230) #savings = models.IntegerField(default=230) tour_type = models.CharField(max_length=100, choices=TOUR_TYPE, default='Group Tour') new_activity … -
How to get Substr when annotate Django
I'm try to sort by order_number had many kind Input: ADC123 ADC14 ADC23 ERD324 ERD12 Sort default just sort by alphabet Expected results (Sort only by number): ERD12 ADC14 ADC23 ADC123 ERD324 Code example: Person.objects.annotate( order_only_number=AddField(Substr("order_number", 1)) ).order_by("order_only_number") -
Cropper JS zooms image on mobile when disabled
I am trying to use cropper JS to allow users to crop images on upload. However I want to disable zooming on mobile as I don't believe it is very user friendly. I have attempted to disable everything to do with zoom, moving and scaling but every time I try resize the cropper on my mobile it zooms. Any ideas on how to disable? <div class="img-container image-container" id="id_image_container"> <img class="profile-image" id="id_image_btn_display" src=""> <div class="img-btn" id="id_middle_container"> <div class="btn btn-primary" id="id_text">Upload Picture<br><small>(Max size: 10MB)</small></div> </div> <div class="p-5"> <input class="d-none" type="file" name="profile_image" id="id_image_btn" onchange="readURL(this)"> </div> </div> <script type="module" src="{% static 'cropperjs/dist/cropper.min.js' %}"></script> <script> // start cropperjs var cropper; var imageFile; var base64ImageString; var cropX; var cropY; var cropWidth; var cropHeight; const minCroppedWidth = 300; function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { disableImageOverlay() var image = e.target.result var imageField = document.getElementById('id_image_btn_display') imageField.src = image cropper = new Cropper(imageField, { // attempted to disable all zooming features zoomable: false, zoomOnTouch: false, zoomOnWheel: false, toggleDragModeOnDblclick: false, scaleable: false, movable: false, crop(event) { var cropWidth = event.detail.width // Stop crop box at minCroppedWidth if (cropWidth < minCroppedWidth) { cropper.setData({ width: Math.max(minCroppedWidth, cropWidth)}) }; setImageCropProperties( image, event.detail.x, … -
constrains on django model with ForeignKey
Suppose we have this django models: from django.db import models # Create your models here. class Artist(models.Model): name = models.CharField(max_length=10) class Album(models.Model): name = models.CharField(max_length=10) date = models.DateField() artist = models.ForeignKey(Artist, on_delete=models.CASCADE) So I can write: artist_one = models.Artist.objects.create(name='Santana') album_one = models.Album.objects.create(name='Abraxas', date = datetime.date.today(), artist=artist_one) album_two = models.Album.objects.create(name='Supernatural', date = datetime.date.today(), artist=artist_one) How can I add a constrain to the Album class as to say an artist cannot publish two albums the same year? -
django form queryset filter using request user
I want to filter queryset using current user data but it's return only a Nonetype Suppose When I remove None its shows the error user can't recognize In Forms.py class oldenquiryForm(forms.ModelForm): class Meta: model=enquiry fields=['product','type','created_at'] widgets={ 'created_at':forms.DateInput(attrs={'type':'date'}), } def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) user = kwargs.pop('user', None) super(oldenquiryForm, self).__init__(*args, **kwargs) employee = emp.objects.filter(branch=user.admin.branch_name).values_list('firstname',flat=True) print (employee) self.fields['created_by'].queryset=emp.objects.filter(branch=user.admin.branch_name).values_list('firstname',flat=True) -
Django HttpResponseRedirect wont redirect when message sent
I want my page to reload and show the django messages sent to the page when a POST call is made (by another user). From api I am calling the method like that: def create(self, request, pk=None): json_data = json.loads(request.body) sample_path = json_data['sample_path'] try: sample = BloodSample.objects.get(sample_path = sample_path) if json_data['status'] == 201: BloodSampleAdmin(sample, BloodSample).display_messages(request, sample) return Response(json_data['body'], status = status.HTTP_201_CREATED) and the method in BloodSampleAdmin is: def display_messages(self, request, sample): messages.success(request, ("hurray")) return HttpResponseRedirect(reverse( "admin:backend_bloodsample_change", args=[sample.id] )) I am 100% sure that the method is called (debug). But message wont pop anyway. I am using Postman to send the POST request. Any ideas on what is going wrong? -
Python, django sessions, how update django session by key
i try to update my session data my code: try: s = Session.objects.get(session_key=token) except ObjectDoesNotExist: return 400, {"error": "Token invalid."} newObject = {'user_pk': 3, 'company_id': 55} s['user_login_info'] = newObject s.save() but i get error TypeError: 'Session' object does not support item assignment how correctly update session data? -
How to pass two or more parameters in Django URL
How can I able to pass two or more parameters in Django URL in this way api/Data/GetAuditChecklistDataForEdit/HRR6627687%7C458%7CRegular It is a get method so I can't get the values of the two parameter (SID, Type) so I'm trying to pass it through the URL Is it possible to pass two or more parameter in this way views.py: @api_view(['GET']) def GetAuditChecklistDataForEdit(request, ticket, SID, Type): if request.method =='GET': cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetAuditChecklistDataForEdit] @ticket=%s, @setid=%s, @Type=%s', (ticket, SID, Type)) result_set = cursor.fetchall() data =[] for row in result_set: print("GetAuditChecklistDataForEdit",row[0]) data.append({ 'QId':row[0], 'Question':row[1], 'AnsOption':row[2], 'Choice':row[3], 'Agents':row[4], 'StreamId':row[5], 'Supervisor':row[6], 'Action':row[7], 'subfunction':row[8], 'region':row[9], 'Comments':row[10], 'TicketType':row[11], }) return Response(data) urls.py: path('Data/GetAuditChecklistDataForEdit/<str:ticket>', GetAuditChecklistDataForEdit, name='GetAuditChecklistDataForEdit'), -
Need to take two fields from one model and use it as foreign key for a new model using django
Model 1 class Users(models.Model): employee_name = models.CharField(max_length=210) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=100,default=None) aadhar=models.CharField(max_length=100,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) emergency_contact_no=models.IntegerField(default=None) name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) joining_role=models.CharField(max_length=250,choices=JOINING_ROLES_CHOICES,null=True) billable_and_non_billable=models.CharField(max_length=250,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') joining_date=models.DateField(max_length=15,null=True) relieving_date=models.DateField(max_length=15,null=True) def __str__(self): return self.employee_name Model 2 class Consolidated(models.Model): emp_name=models.ManyToManyField(Users,related_name="employee_name+") proj_name=models.ManyToManyField(Project) custom_name=models.ManyToManyField(Client) Cons_date=models.ManyToManyField(Add_Timelog) bill_no_bill=models.ManyToManyField(Users,related_name="billable_and_non_billable+") hour_spent = models.ManyToManyField(Add_Timelog,related_name="hour_spent") def __str__(self): return str(self.emp_name) I need to take the value updated on the "employee_name" and "billable_and_non_billable" field in the "User" model to "emp_name" and "bill_no_bill" field in "Consolidated" model. Will it be possible to take two fields as foreign key from one model to another. I'm new this django kindly help me if there is any possible ways. -
gunicorn.service: Failed to determine user credentials: No such process - django, gunicorn, and nginx
When I run sudo systemctl status gunicorn, I get the following error: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2022-02-08 07:29:18 UTC; 17min ago Main PID: 21841 (code=exited, status=217/USER) Feb 08 07:29:18 ip-172-31-37-113 systemd[1]: Started gunicorn daemon. Feb 08 07:29:18 ip-172-31-37-113 systemd[21841]: gunicorn.service: Failed to determine user credentials: No such process Feb 08 07:29:18 ip-172-31-37-113 systemd[21841]: gunicorn.service: Failed at step USER spawning /home/ubuntu/bookclub/venv/bin/gun Feb 08 07:29:18 ip-172-31-37-113 systemd[1]: gunicorn.service: Main process exited, code=exited, status=217/USER Feb 08 07:29:18 ip-172-31-37-113 systemd[1]: gunicorn.service: Failed with result 'exit-code'. I'm following this tutorial from DigitalOcean to get my Django website onto my EC2 instance. I'm using Nginx and Gunicorn with Django to accomplish this. This is my gunicorn.service file at /etc/systemd/system/gunicorn.service: [Unit] Description=gunicorn daemon After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/ubuntu/bookclub ExecStart=/home/ubuntu/bookclub/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/bookclub/books.sock books.wsgi:application [Install] WantedBy=multi-user.target I checked for books.sock in my project folder with ls and I saw that books.sock does not exist. -
Django Session Variable Is Accessible Even After Deletion
I tried to delete the session after the work is complete. But, it still shows a different value when checking if the session variable exists. if 'order_id' in request.session: # here the value of session variable is 28 del request.session['order_id'] request.session.modified = True When I checked again it returned True even though I deleted the variable, if 'order_id' in request.session: # here the value of session variable is 5118 print('yes') -
After dropping database, I am getting this ModuleNotFoundError: No module named 'myproject' error
I ran into a database out of sync error and so I dropped one database in development mode and synced my settings to a newly created postgresql database. I removed my pycache and migrations prior to creating a new database and then ran the "python3 manage.py makemigrations" and "python3 manage.py migrate". Here is a link to the prior error and code if that's necessary to know. django.db.utils.ProgrammingError: column accounts_account.username does not exist However, when I ran "python3 manage.py createsuperuser" it gave me this ModuleNotFoundError: No module named 'myproject' error. I don't quite understand this error because I never named my project 'myproject'. Perhaps, I am not understanding something when dropping one database and setting up a new database. Traceback (most recent call last): File "/Users/taniryla/ecommerce/manage.py", line 22, in <module> main() File "/Users/taniryla/ecommerce/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/anaconda3/envs/skincareryland/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/anaconda3/envs/skincareryland/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/anaconda3/envs/skincareryland/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/anaconda3/envs/skincareryland/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/opt/anaconda3/envs/skincareryland/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/opt/anaconda3/envs/skincareryland/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/Users/taniryla/ecommerce/accounts/models.py", line 27, in create_superuser user = self.create_user( File "/Users/taniryla/ecommerce/accounts/models.py", line 22, in create_user … -
Alternative for StringRelatedField
I am trying to get following user with their names instead of PrimaryKey, I tried to use StringRelatedField. It worked for GET request, but it does not allow to write. Could not find any alternatives for this. I want to get json result as this: { "id": 1, "user": "admin", "following": "user_1" } I assume instead of using StringRelatedField I should redefine create in serializers, am I right? model.py class Follow(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='follower' ) following = models.ForeignKey( User, on_delete=models.CASCADE, related_name='following' ) class Meta: constraints = [ models.UniqueConstraint( fields=['user', 'following'], name='unique_user_following' ) ] def __str__(self) -> str: return self.following serializer.py class FollowSerializer(serializers.ModelSerializer): user = serializers.SlugField( read_only=True, default=serializers.CurrentUserDefault() ) # following = serializers.StringRelatedField() class Meta: model = Follow fields = ('id', 'user', 'following',) validators = [ serializers.UniqueTogetherValidator( queryset=Follow.objects.all(), fields=('user', 'following',) ) ] def validate_following(self, value): if value == self.context.get('request').user: raise serializers.ValidationError( 'You can not follow yourslef!' ) return value views.py class FollowViewSet(viewsets.ModelViewSet): serializer_class = FollowSerializer def get_queryset(self): new_queryset = Follow.objects.filter(user=self.request.user) return new_queryset def perform_create(self, serializer): serializer.save(user=self.request.user) -
How to position content beside sidebar?
I am not very well versed in HTML and CSS. I am currently building a web application using Django and I integrated a sidebar into my web application using Bootstrap, but it has messed my layouts, and I can't seem to figure out how to move the content in a block to the left of side of my sidebar. As seen in the pictures above, my sidebar is located at the top and my content is located at the bottom. Below are my codes for my sidebar and the base template. sidebar_template.html <div class="d-flex flex-column vh-100 flex-shrink-0 p-3 text-white bg-dark sidebar-height" style="width: 250px;"> <a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none"> <svg class="bi me-2" width="40" height="32"> </svg> <span class="fs-4">CPRS Admin</span> </a> <hr> <ul class="nav nav-pills flex-column mb-auto"> <li class="nav-item"> <a href="#" class="nav-link active" aria-current="page"> <i class="fa fa-home"></i><span class="ms-2">Home</span> </a> </li> <li> <a href="{% url 'coordinator_dashboard' %}" class="nav-link text-white"> <i class="fa fa-dashboard"></i><span class="ms-2">Dashboard</span> </a> </li> <li> <a href="{% url 'coordinator_view_students' %}" class="nav-link text-white"> <i class="fa fa-first-order"></i><span class="ms-2">Students</span> </a> </li> <li> <a href="#" class="nav-link text-white"> <i class="fa fa-cog"></i><span class="ms-2">Settings</span> </a> </li> <li> <a href="#" class="nav-link text-white"> <i class="fa fa-bookmark"></i><span class="ms-2">Bookmarks</span> </a> </li> </ul> <hr> <div class="dropdown"> <a href="#" class="d-flex align-items-center text-white … -
Dockerized kong not able to redirect the request to django which is inside docker
am new to kong and i installed kong and django inside my docker.from kong am able to forward the request to other servers but it is giving "received an invalid response from upstream server " when am trying to test the django api please help, Thanks -
Make django parent model accessible to formset without displaying it in html
I have page1 with two links (‘A’ and ‘B’) on it the specific link that is clicked determines a query parameter /page2/?q=A or /page2/?q=B. On page 2 the user completes an inline formset, the parent form of which has been set to a value of ‘A’ or ‘B’ depending on the link clicked on the previous page. I do not want to display the parent form but if this is not displayed then I am unable to successfully save the formset and parent form. The views.py for page 2 is: class CaseView(TemplateView): model = Case template_name = “page2/page2.html” def get(self, *args, **kwargs): # parent form case_form = CaseForm # child formset sideeffect_formset = SideeffectFormSet(queryset=SideEffect.objects.none()) return self.render_to_response( { "case_form": case_form, "sideeffect_formset": sideeffect_formset, "sideeffect_formsethelper": SideEffectFormSetSetHelper, } ) def post(self, *args, **kwargs): form = CaseForm(data=self.request.POST) sideeffect_formset = SideeffectFormSet(data=self.request.POST) if form.is_valid(): case_instance = form.save(commit=False) if self.request.user.is_authenticated: case_instance.user = self.request.user case_instance.save() if sideeffect_formset.is_valid(): sideeffect_name = sideeffect_formset.save(commit=False) for sideeffect in sideeffect_name: sideeffect.case = case_instance sideeffect.save() return redirect( reverse( "results", kwargs={"case_id": case_instance.case_id}, ) ) I want to be able to save CaseForm and have it available for the childformset without actually displaying CaseForm in the html -
How to save python class object / instance in django models Fields
I am trying to authenticate with some proxies with requests.Session(). after authenticated I want to save the session object for future use. Is there any method that can help me to save request class object in Django fields. What I want is in My model want too create an field class Proxy(models.Model): name = models.CharField(max_length=300) username = models.CharField(max_length=60, blank=True, default="") password = models.CharField(max_length=20, blank=True, default="") ip = models.GenericIPAddressField(protocol='IPv4',unique=True) session=models.**ObjectofRequests**(requests.Session,on_delete=models.CASCADE)<-- like this def __str__(self): return self.name save this after getting session s = requests.Session() proxies = { "http": "http://user:pass@Ip:port", "https": "http://user:pass@Ip:port" } s.proxies = proxies obj = Proxy(name='Any',username=user,password=pass,session=s) obj.save()