Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add manytomany field query in cet_or_create method
def create(self, validated_data): employer = User.objects.get(id=self.context.get('employer')) candidate = User.objects.get(id=self.context.get('candidate_id')) report_details_id = ReportDetails.objects.filter( id__in=self.context.get('report_details_id')) (report_candidate, created) = ReportCandidate.objects.get_or_create( reported_by=employer.id, candidate_id=candidate.id,report_details_id=report_details_id) return report_candidate Here the report_details_id is a manytomanyfield query. How will apply each of the data in it in the get_or_create method? The QuerySet value for an exact lookup must be limited to one result using slicing. I'm getting this error from the above code. Thanks in Advance. -
Django: How to download file generated by python script running in celery task after completion
I am building a Django web application, and I currently have the ability to upload a dataset (.csv file). When the 'upload' button is pressed, a celery task is started that manipulates the dataset. I want to display a page with a 'download result' button when the celery task is completed. There is currently a progress bar that displays the progress of the script using the celery-progress toolkit (it takes quite a while). I already have users built-in, if that helps. Question 1: Where should I store the output file generated by the python script running in the celery task so that the user can download it? Question 2: How do I display a page with the "download result" button when the celery task is complete? Question 3: How do I actually make this button download the file pertaining to the user's file? Here is my code so far: views.py from django.conf import settings from .models import Document from .forms import DocumentForm from django.views import View from .tasks import RunBlackLight import os from django.http import Http404, HttpResponse class RunView(View): form_class = DocumentForm initial = {'key': 'value'} template_name = 'runblacklight/progress.html' error_template_name = 'runblacklight/error.html' def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) … -
Django: How to return an inline formset with errors
I have created a form to sign up a user by having them create a User object and a UserProfile object as follows: class UserCreationForm(UserCreationForm): class Meta: model = User fields = ("email",) class UserProfileCreationForm(ModelForm): class Meta: model = UserProfile fields = ( "first_name", "last_name", ) RegisteredCustomerProfileCreationInlineFormset = inlineformset_factory( User, UserProfile, form=UserProfileCreationForm, extra=1, can_delete=False, can_order=False, ) In my view to display the sign up form, I do the following: class UserSignupView(CreateView): form_class = UserCreationForm template_name = "users/signup_form.html" def get_context_data(self, **kwargs): """Adds the inline formset to the context.""" context = super(UserSignupView, self).get_context_data(**kwargs) if self.request.POST: context[ "user_profile_inline" ] = UserProfileCreationInlineFormset( self.request.POST ) else: context[ "user_profile_inline" ] = UserProfileCreationInlineFormset() return context def form_invalid(self, request, form): # Note: I added request as an argument because I was getting an error that # says the method is expecting 2 arguments but got 3. return render(self.request, self.template_name, self.get_context_data( form=form ) ) def form_valid(self, form): context = self.get_context_data() user_profile_inline = context["user_profile_inline"] if ( form.is_valid() and user_profile_inline.is_valid() ): # Handle valid case ... else: self.form_invalid(self, form) My template is as simple as <form method="post"> {% csrf_token %} {{ form.as_p }} {{ user_profile_inline.as_p }} <button type="submit" value="Save">Sign Up</button> </form> When my form which is for creation of the User … -
geting user details in serializer djnago rest framework?
i am trying to get users details from django using rest framework. but there is error: module 'core.model' has no attribute 'Users' to do that i added this line in settings.py: REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER':'users.serializers.userSerializer' } because it is a model of django auth and in my models.py there is no model such Users it is from djnago auth model. and i dont know how to access the data from it. from rest_framework import serializers from core import models class userSerializer(serializers.ModelSerializer): class Meta: fields=( 'id', 'username') model=models.Users here is the screen shot of my django admin: [![you can see clearly Users table from djnago auth][1]][1] please help Thanks in advance<3 [1]: https://i.stack.imgur.com/EsGE8.png -
django rest frame work: model fields on Django Rest Frame write error
I have a django app with following sections models: class Report(models.Model): created_by_user=models.ForeignKey(User,on_delete=models.CASCADE) planet_name = models.CharField(max_length=100) outage_id = models.IntegerField(blank=True, default=0) unit_name = models.CharField(max_length=10, blank=True, null=True) responsible_group = models.CharField(max_length=50, blank=True) alarm_num = models.IntegerField(blank=True, default=0) raised_alarm = models.CharField(max_length=255, blank=True) start_time = models.DateTimeField(blank=True) end_time = models.DateTimeField(blank=True) event_desc = models.TextField(max_length=5000, blank=True) power_changes = models.FloatField(blank=True) rel_asset = models.CharField(max_length=255, blank=True) event_cause = models.TextField(max_length=1000, blank=True) maintenance_action = models.TextField(max_length=1000, blank=True) maintenance_cost = models.IntegerField(blank=True) maintenance_mh = models.IntegerField(blank=True) maintenance_dc = models.TextField(max_length=5000, blank=True) serializer: class ReportSerializer(serializers.ModelSerializer): created_by_user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model=Report fields='__all__' view: class ReportCreateView(APIView): def post(self,request, *args, **kwargs): received_data=ReportSerializer(data=request.data, context = {"request": request}) if received_data.is_valid(): received_data.save() return Response(received_data.data, status=status.HTTP_201_CREATED) return Response(received_data.errors,status.HTTP_400_BAD_REQUEST) but when I send a report by Post method this error rise: (1048, "Column 'start_time' cannot be null") How I can fix it?I set blank=True for all fields but why it raise errors? -
Cant send the data from the database to the client in real time without refreshing - DJANGO CHANNELS
I tried this approach stackoverflow but it didn't work consumer.py import json import asyncio from channels.consumer import AsyncConsumer from django.contrib.auth import get_user_model from channels.db import database_sync_to_async from .models import Analytics class AnalyticsConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) await self.send({ 'type': 'websocket.accept' }) analytics_obj = await self.getAnalytics() await self.send({ 'type': 'websocket.send', 'text': str(analytics_obj) }) async def websocket_receive(self, event): print('receive', event) async def websocket_disconnect(self, event): print('disconnected', event) @database_sync_to_async def getAnalytics(self): return list(Analytics.objects.all().values())[0]['number'] The console displays the message == analytics_obj but when I make changes in the database, it doesn't reflect in the console message. For that, I need to refresh the browser. What is the point in refreshing the browser when you are using WebSocket. -
Azure Virtual Machine (Ubuntu) how to deploy multiple Python websites
I am new to Python / Azure VM world. I have created Python/Django website using PyCharm IDE. Created Azure VM with Python/Django installed on Azure VM , I can run : Python manage.py runserver and i can access it using Azure URL from externally. Question: to run/deploy a python website on VM, do we have to run Python manage.py command or there is any other way ? in case I have to deploy multiple websites what i should do ? and python manage.py session also gets expired pretty soon and site is not accessible anymore , how to keep it running ? Regards Shakeel -
argument cannot be of 'NoneType' type, must be of text type in Django 3.0
When i am trying create a new cover letter i am getting this error Django = 3.0 Python = 3.7 Here is my cover_letters_list.django.html <tr> <td colspan="4"> <span class="form-tag {% if not name_form %} hidden {% endif %}"> <form class="form-inline" target="" method="POST" style="margin-top: 0px;"> {% csrf_token %} <input type="text" class="span6" name="name" value="{{name_form.name.value}}" placeholder="Cover letter name"> <button type="submit" class="btn btn-primary">Create</button> <button type="button" class="btn cancel-btn">Cancel</button> </form> </span> <span class="button-tag {% if name_form %} hidden {% endif %}"> {% trans "No data found." %} Click to <a class="new_cover" href="#"> add a new cover letter</a> </span> </td> </tr> here is my views.py class CoverLetterListView(View): def get(self, request): client = request.user.client cover_letters = CoverLetter.objects.filter(client=client, deleted=False, is_master=True) return render(request, 'quotes/covers/cover_letters_list.django.html', {'cover_letters': cover_letters}) def post(self, request): client = request.user.client name_form = forms.CoverLetterNameForm(request.POST) cover_letters = CoverLetter.objects.filter(client=client, deleted=False) if name_form.is_valid(): name_form.save_new(client=client) else: logger.warning(request, 'Invalid form') return render(request, 'quotes/covers/cover_letters_list.django.html', {'name_form': name_form, 'cover_letters': cover_letters}) here is my forms.py class CoverLetterNameForm(forms.ModelForm): class Meta: model = CoverLetter fields = ('name',) def save_new(self, client, master=True): instance = self.save(commit=False) instance.is_master = master instance.client = client return instance.save() How can i solve this error -
Should i run django commands outside a docker container or in the docker container cli
I just started dockerizing my Django apps so far all is going well but I need to know is it best practice to run the Django commands inside the container docker container exec -it con_name python manage.py startup app_name or I should just run it outside the container python manage.py startup app_name thank you -
count the null column in a row in django
I was interested to count the numbers of null culemns in a single row in django.can you please lead me on how to do it? example: model: Student fields: fname,lname, father_name Student("max",null,null) return lname and father_name or 2 -
Django fails to load javascript file but has no trouble server a css file in the same directory
I receive a Failed to load resource: the server responded with a status of 404 (Not Found) for the javascript file. The page loads fine but the javascript resource isn't obtained despite being in the same static folder as the css file which django has no trouble collecting. settings.py STATIC_URL = '/static/' BASE_DIR = os.path.dirname(os.path.dirname(__file__)) #STATIC_ROOT = os.path.abspath(os.path.join(os.path.dirname(BASE_DIR), 'static')) STATIC_ROOT = 'static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIR=[STATIC_DIR] html {% load static %} asdfs <link rel="stylesheet" type="text/css" href="{% static 'polls/styles.css' %}"> <body id='app'> <p>i'm testing again</p> <li><a href="www.google.com">google</a></li> <script type="text/javascript" src="{% static 'polls/reactfile.js' %}"></script> </body> </html> -
How to return jsonResponse for single object model filtered on Django?
I have single object filtered as below. backTest= BackTest.objects.first() I would like to return this object as jsonResponse. data = dumps(backTest) return JsonResponse(data) I got error message as below. Object of type BackTest is not JSON serializable Any advice or guidance on this would be greatly appreciated, Thanks. -
Django - Delete file associated with ImageField attribute of Model
So I have a model called User, which has an avatar field, which is just the user's avatar. I want to be able to delete the file whenever the user chooses to delete their avatar. As you can see below in my view.py I retrieve the current user object from the request(This is because I take the user uuid from the access token given to make the request then query the user object). Then I call delete on the avatar attribute, but I don't know if this actually deletes the file as well. My assumption is that it just deletes that attribute url. How do I delete the file associated with ImageField when I delete a ImageField attribute in a model? model.py class User(AbstractDatesModel): uuid = models.UUIDField(primary_key=True) username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[ MinLengthValidator(USERNAME_MIN_LEN)]) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) avatar = models.ImageField(upload_to=avatar_directory_path, blank=True, null=True) view.py @api_view(['POST', 'DELETE']) def multi_method_user_avatar(request): if request.method == 'POST': # Some POST code elif request.method == 'DELETE': try: request.user.avatar.delete() request.user.save() return Response(status=status.HTTP_204_NO_CONTENT) except Exception as e: return Response(dict(error=str(e), user_message=generic_error_user_msg), status=status.HTTP_400_BAD_REQUEST) -
Failed to load resources status: 404 javascript with django
i am running javascript frontend with django backend. Here is the structure -app --templates ---index.html --static ---index.js ---haarcascade_frontalface_alt.xml ---style.css --views.py --urls.py I can see css style in my index.html page. But the index.js file is unable to pick haarcascade_frontalface_alt.xml. The code is as follow const HAARCASCADE_URI = "haarcascade_frontalface_alt.xml" this.classifier = new cv.CascadeClassifier(); let faceCascadeFile = "haarcascade_frontalface_alt.xml"; if (!this.classifier.load(faceCascadeFile)) { await this.createFileFromUrl(faceCascadeFile, this.classifierPath); this.classifier.load(faceCascadeFile) } but it say Failed to load haarcascade_frontalface_alt.xml status: 404 -
How to connect social accounts to existing account with dj-rest-auth and react
I am creating a webiste with social accounts login and register buttons with dj-rest-auth for authentication and thisreact component for frontend of my website, login and register process with social accounts like twitter and facebook works perfectly but i also need to connect these social accounts to an existing account according to this documantion, i added these codes: class FacebookConnect(SocialConnectView): adapter_class = FacebookOAuth2Adapter class TwitterConnect(SocialConnectView): serializer_class = TwitterConnectSerializer adapter_class = TwitterOAuthAdapter and in urls.py : urlpatterns += [ ..., path('dj-rest-auth/facebook/connect/', FacebookConnect.as_view(), name='fb_connect') path('dj-rest-auth/twitter/connect/', TwitterConnect.as_view(), name='twitter_connect') ] if i try to connect a new facebook account it creates a new record in User model like this : and a new record in social account like this : as you can see the USER field is empty and the record is not connected to the existing logged ion account and if i try to connect an already registered facebook account i get the error :this username has already been registered i think if i add the current logged in user pkto USER filed in social account the problem would be solved but i have no idea how to import social account model in views.py and do the process -
How to return multiple response in Django
I'm trying to return the same response after the loop ends but I couldn't able to find a approach to implement it. Here, What I have tried and error which I get local variable 'TaskId' referenced before assignment views.py: def GetCurrentRunningActivity(UserID): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivity] @UserId=%s',(UserID,)) result_set = cursor.fetchall() cursor_set = cursor.fetchall() for row in result_set: TaskId=row[0] Number=row[1] Opened=row[2] Contacttype=row[3] Category1=row[4] State=row[5] Assignmentgroup=row[6] CountryLocation=row[7] Openedfor=row[8] Employeenumber=row[9] Shortdescription=row[10] Internaldescription=row[11] Additionalcomments=row[12] TaskName = row[1] print("Number", Number) return Response({ "TaskId": TaskId, "Number":Number,"Opened":Opened, "Contacttype":Contacttype, "Category1":Category1, "State":State, "Assignmentgroup":Assignmentgroup, "CountryLocation":CountryLocation, "Openedfor":Openedfor, "Employeenumber":Employeenumber , "Shortdescription":Shortdescription, "Internaldescription":Internaldescription, "Additionalcomments":Additionalcomments,"TaskName":TaskName},status=status.HTTP_200_OK) return Response({ "TaskId": TaskId, "Number":Number,"Opened":Opened, "Contacttype":Contacttype, "Category1":Category1, "State":State, "Assignmentgroup":Assignmentgroup, "CountryLocation":CountryLocation, "Openedfor":Openedfor, "Employeenumber":Employeenumber , "Shortdescription":Shortdescription, "Internaldescription":Internaldescription, "Additionalcomments":Additionalcomments,"TaskName":TaskName},status=status.HTTP_200_OK) -
Django pg-crypto - How do you migrate existing fields?
In my test environment I have installed pg-crypto by running "pip install django-pgcrypto". I logged into the database manually using "sudo -u postgres psql", then I connected to the database and installed the extension using "CREATE EXTENSION pgcrypto;". I then altered a field on one of my models from "models.EmailField" to "pgcrypto.EncryptedEmailField" and then ran makemigrations and migrate. I was able to successfully create a new account by making a call to the API view. I then went onto the database using the Postgres console and could see that it had encrypted the email field for that new user, but the previous entries are the same. Now when I log onto the Django admin console, I get the error "Corrupt ascii armour". I assume that this is because the table now has a mixture of unencrypted and encrypted email fields. If I start with a new database then all the fields are encrypted and I don't get the error in the admin console. Please can someone advise how I encrypt the exiting entries or if there is a way through Django migrations so I don't have to start with a new database? -
Need help in django ORM query to return response given below
I have the below model: publish_status = {'published': 'published', 'publishing': 'publishing', 'rejected': 'rejected', 'not-updated': 'not-updated', } publishToBridgeStatus = StringField(db_field="publishBridge", required=False, choices=publish_status.keys(), default="not-updated") Response needed count of each available status in DB: { "all": 0, "published": 0, "publishing": 0, "rejected": 0, "notUpdated": 0 } -
Djangorestframework > 3.11 Incompatible with Django 1.11, breaks build
akismet==1.1 amqp==1.4.9 anyjson==0.3.3 APScheduler==3.8.1 arabic-reshaper==2.1.3 asgi-redis==1.4.3 asgiref==1.1.2 attrs==21.4.0 autobahn==21.11.1 Automat==20.2.0 backcall==0.2.0 backports.functools-lru-cache==1.6.4 backports.shutil-get-terminal-size==1.0.0 backports.zoneinfo==0.2.1 beautifulsoup4==4.10.0 billiard==3.3.0.23 cached-property==1.5.2 caniusepython3==7.3.0 celery==3.1.17 certifi==2021.10.8 cffi==1.15.0 channels==1.1.2 chardet==4.0.0 charset-normalizer==2.0.10 click==8.0.3 click-didyoumean==0.3.0 click-plugins==1.1.1 click-repl==0.2.0 constantly==15.1.0 coreapi==2.3.3 coreschema==0.0.4 cryptography==36.0.1 cycler==0.11.0 daphne==1.4.2 decorator==4.3.0 defusedxml==0.7.1 Deprecated==1.2.13 distlib==0.3.4 Django==1.11.17 django-admin-honeypot==1.1.0 django-allauth==0.26.1 django-appconf==1.0.5 django-bootstrap-form==3.4 django-celery==3.1.17 django-compat==1.0.15 django-compressor==3.1 django-constance==2.8.0 django-extensions==2.1.6 django-filter==1.1.0 django-helpdesk==0.2.10 django-hijack==2.1.5 django-hijack-admin==2.1.10 django-js-asset==1.2.2 django-markdown-deux==1.0.5 django-modeladmin-reorder==0.3.1 django-mptt==0.13.4 django-otp==0.7.5 django-picklefield==2.0 django-pyodbc-azure==1.11.13.1 django-rest-swagger==2.2.0 django-richtextfield==1.6.1 django-simple-history==3.0.0 django-taggit==0.23.0 djangorestframework==3.8.2 email-reply-parser==0.5.12 enum34==1.1.10 et-xmlfile==1.1.0 fonttools==4.28.5 future==0.18.2 fuzzywuzzy==0.18.0 html5lib==1.1 httpagentparser==1.9.1 hyperlink==21.0.0 idna==3.3 imageio==2.13.5 imageio-ffmpeg==0.4.5 imgkit==1.2.2 importlib-metadata==4.10.0 incremental==21.3.0 install==1.3.5 ipython==7.31.0 ipython-genutils==0.2.0 itypes==1.2.0 jedi==0.18.1 Jinja2==3.0.3 joblib==1.1.0 jsonfield==2.0.2 kiwisolver==1.3.2 kombu==3.0.37 logzero==1.7.0 Louie==2.0 lxml==4.7.1 Markdown==3.3.6 markdown2==2.4.2 MarkupSafe==2.0.1 matplotlib==3.5.1 matplotlib-inline==0.1.3 moviepy==1.0.3 msgpack-python==0.5.6 nltk==3.6.7 numpy==1.21.5 oauthlib==3.1.1 openapi-codec==1.3.2 openpyxl==3.0.9 packaging==21.3 pandas==1.3.5 parso==0.8.3 pathlib==1.0.1 pathlib2==2.3.6 pexpect==4.8.0 pickleshare==0.7.5 Pillow==9.0.0 pretty-cron==1.2.0 proglog==0.1.9 prompt-toolkit==3.0.24 ptyprocess==0.7.0 pur==5.4.0 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.21 pycrypto==2.6.1 pycryptodome==3.12.0 Pygments==2.11.1 PyJWT==2.3.0 pymssql==2.2.3 pyodbc==4.0.23 pyOpenSSL==21.0.0 pyparsing==3.0.6 PyPDF2==1.26.0 python-bidi==0.4.2 python-crontab==2.6.0 python-dateutil==2.8.2 python-keyczar==0.716 python-openid==2.2.5 python-slugify==5.0.2 python3-openid==3.2.0 pytz==2021.3 pytz-deprecation-shim==0.1.0.post0 PyYAML==6.0 pyzmq==22.3.0 rcssmin==1.1.0 redis==2.10.6 regex==2021.11.10 reportlab==3.6.5 requests==2.27.1 requests-oauthlib==1.3.0 rjsmin==1.2.0 scandir==1.10.0 scikit-learn==1.0.2 scipy==1.7.3 service-identity==21.1.0 simplegeneric==0.8.1 simplejson==3.17.6 six==1.16.0 sklearn==0.0 soupsieve==2.3.1 sqlparams==3.0.0 sqlparse==0.4.2 text-unidecode==1.3 textblob==0.17.1 threadpoolctl==3.0.0 tqdm==4.62.3 traitlets==5.1.1 twilio==7.4.0 Twisted==21.7.0 txaio==21.2.1 typing_extensions==4.0.1 tzdata==2021.5 tzlocal==4.1 uritemplate==4.1.1 urllib3==1.26.7 vaderSentiment==3.3.2 vine==5.0.0 wcwidth==0.2.5 webencodings==0.5.1 wrapt==1.13.3 xhtml2pdf==0.2.5 xlrd==2.0.1 XlsxWriter==3.0.2 zipcodes==1.2.0 zipp==3.7.0 zope.interface==5.4.0 I am trying to migrate my project from python 2.7 to 3.7 I have installed Django =1.11.17 and … -
jQuery import causing my webpage to become unresponsive
I have the following html page: <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <title>Message wall</title> <style> #messages { overflow-y: scroll; border: black; height: 20em; width: max-content; } #back { position: fixed; top: 0; right: 0; margin-right: 5px; background-color: gainsboro; } #message-sender { position: fixed; bottom: 0; } form { margin-bottom: 5px; } #message-input { padding-right: 10em; } </style> </head> <body> <div id="messages"></div> <div id="back"> <h3 style="margin: 0;"><a href='http://localhost'>Main Page</a></h3> </div> <div id="message-sender"> <form> <h3>Input message: </h3> <input id="message-input" type="text"> <input id="message-send-btn" type="button" value="Send"> </form> </div> <script> function usernameExists() { user = localStorage.getItem('user') return !(user == null || user == "null" || user == '') } function promptUsername() { let input = prompt('Please enter a username: ') if (input.length <= 20 && !(input.includes(' '))) { localStorage.setItem('user', input) } else if (input.length > 20) { alert('Username must be less than 21 characters!') } else /* if (input.includes(' ')) */ { alert('Spaces are not allowed in usernames!') } } if (!usernameExists()) { promptUsername() } else { console.log(localStorage.getItem('user')) } function updateMsgs() { $.ajax({ url: "http://localhost/testing/getmsgs", success: function (response) { document.getElementById('messages').innerHTML = response } }) } updateMsgs() document.getElementById('message-send-btn').addEventListener('click', () => { while (!usernameExists()) { promptUsername() } let msg = document.getElementById('message-input').value if (msg == null) { return … -
Implement Recursive function to check whether a model has child or not
I'm trying to implement a recursive function that will check if an object has child with the parent id. If has than it will add the child to the list and will recursively call the function to check if newly added child has further children. My Current Code that works fine as expected: def get_nav_items(self, instance): childs = [] items = Content.objects.filter(parent_id=instance) for item in items: childs.append(item) for item in items: ch = Content.objects.filter(parent_id=item) if ch.count() > 0: for c in ch: childs.append(c) menu_objecs = [] for item in childs: menu_objecs.append(ContentNevItemSerializer(item).data) return menu_objecs The method that isn't returning any result now: def extract_item(self, nav_obj, nav_list = []): cont = Content.objects.filter(parent_id=nav_obj) if len(cont) == 0: return nav_list else: for ct in cont: self.extract_item(ct, nav_list) # nav_list.append(cont) return nav_list -
Django uploading large files: takes time to reach till the first line of view
I have simple view which get a file def upload_file(request): print("first line") .... Here when i upload a file of 800 MB, the printing of first line itself takes 5-10 sec or more Definitely I am expecting it to take time, when i try to access it like upload_file = request.data['file'] because it has to create a copy of the file in /tmp. But here even before that it takes lot of time. I hope its taking time to build the request object itself. Or is it time time taken from the browser to the django I just wanted to know whats taking the time -
How to edit select option values in Django Forms
models.py class Product(models.Model): product = models.CharField(max_length=50, blank=True, null=True) price = models.IntegerField(blank=True,null=True) def __str__(self): return self.product class Meta: db_table = "product" class price_list(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True) price = models.IntegerField(blank=True,null=True) value = models.IntegerField(null=True) class Meta: db_table = "pricelist" Note: the value for each option is the prduct id. I want to change that value to price(that's related to the product). forms.py class CourseCreateForm(forms.ModelForm): class Meta: model = price_list fields = ['product', 'price', 'value' ] views.py def index(request): result = Product.objects.all() form = CourseCreateForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, 'Successfully saved') return redirect('/') context = { 'form':form, 'title': "Add Course", 'col':result } return render(request,'index.html', context) index.html I want to edit select option value like(value={{result.price}}) i have no idea how can write. <div class="bg-light p-5 rounded"> <h1>{{title}}</h1> <div class="row"> <div class="col-sm-5"> <div class="display_table"> <form action="" method="POST"> {% csrf_token %} {% comment %} {{form.as_p}} {% endcomment %} {{form|crispy}} <br> <input type="submit" value="Save" class = "btn btn-primary" onclick="demo()"> <b style="color:green;" id="colordisplay"></b> <label for="msg"></label> </form> </div> </div> </div> -
UnboundLocalError: local variable 'mtotal_cost_price' referenced before assignment in Django 3.0
Here is my code Django = 3.0 Python = 3.7 def get_quote_margin(self): # get all items quote_item = self.quote_estimate_item.filter(quote_items__isnull=False) total_cost_price = 0 total_sell_price = 0 if quote_item: for item in quote_item: cost_price = self._convert(item.cost_currency, self.currency, item.cost_price) mtotal_cost_price += cost_price * float(item.quantity) sell_price = self._convert(item.currency, self.currency, item.unit_price) total_sell_price += sell_price * float(item.quantity) if total_sell_price: return ((total_sell_price - total_cost_price)/total_sell_price)*100 I am getting this error how could i solve it mtotal_cost_price += cost_price * float(item.quantity) UnboundLocalError: local variable 'mtotal_cost_price' referenced before assignment -
Django, Nextjs | set-cookie is not set in the browser even though the value is set
I am creating a JWT authentication with Django and Nextjs. I can implement the signup and login functionality, I can get the accessToken by logging in. However, the response header is Set-Cookie is set in the browser(chrome, safari,firefox) even though there is a cookie. What are the possible causes? response header Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: https://localhost:3000 Allow: POST, OPTIONS Content-Length: 715 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Tue, 11 Jan 2022 04:34:59 GMT Referrer-Policy: same-origin Server: Werkzeug/2.0.2 Python/3.9.7 Set-Cookie: jwt-auth=〇〇; expires=Tue, 11 Jan 2022 05:34:59 GMT; HttpOnly; Max-Age=3600; Path=/; SameSite=None; Secure Set-Cookie: csrftoken=〇〇; expires=Tue, 10 Jan 2023 04:34:59 GMT; Max-Age=31449600; Path=/; SameSite=None; Secure Set-Cookie: sessionid=〇〇; expires=Tue, 25 Jan 2022 04:34:59 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=None; Secure Vary: Accept, Cookie, Origin X-Content-Type-Options: nosniff X-Frame-Options: DENY Environment Django==4.0.1 Nextjs Server Domain https://127.0.0.1:8000 Front Domain https://localhost:3000 settings.py | Django CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:3000', 'http://localhost:3000', 'https://127.0.0.1:3000', 'https://localhost:3000', ] index.js | Next const login = async (data) => { const res = await axios.post("https://127.0.0.1:8000/api/auth/login/", data, {withCredentials: true}) };