Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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}) }; -
How do I create an object of a Model that has a foreign key to another Model in Django?
I am pretty new to Python and Django and I am kinda struggling with a project. I am trying to build a Etsy-like website, where people can sell their things (not really like a shop, people can post everything they want to sell). I am now trying to add the "Add Item" functionality for the User, where he can post its own sale. But the problem I have stummbled upon is the following: my model Product has a foreign key to the model Customer and I don't know how to create a new product in the database because it keeps saying NOT NULL constraint failed: app_product.added_by_id. I tried something like this, but it is not working and I have no idea what I should do. https://i.stack.imgur.com/MaykE.png My classes looks like this: https://i.stack.imgur.com/LF9R6.png https://i.stack.imgur.com/f5Te7.png Anoyone has any idea what I should try? Or if I can make it automatically in the HTML part or something -
UNIt Test- How to test Viewsets create Function in DRF
I want to test create function which is inside viewsets. I have tried I got 400 error. views.py class PersonalInfoAPI(viewsets.ViewSet): permission_classes = [IsOwnerPermission] def get_object(self, pk): obj = get_object_or_404(Employee.objects.all(), pk=pk) self.check_object_permissions(self.request, obj) return obj def create(self, request): print("im in create") personal_info = JSONParser().parse(request) data = personal_info['data']['personal_info'] data['appraisal_master_id'] = personal_info['data']['appraisal_master_id'] employee = self.get_object(pk=data['employee_id']) appraisal = get_object_or_404(Appraisal, pk=data['appraisal_master_id']) employee_appraisal = EmployeeAppraisal.objects.filter(appraisal=appraisal, employee=employee).first() if employee_appraisal: personal_info_serializer = PersonalInfoSerializer(employee_appraisal, data=data) if personal_info_serializer.is_valid(): personal_info_serializer.save() return Response(employee_appraisal.appraisal_info(user=self.request.user), status=status.HTTP_200_OK) else: personal_info_serializer = PersonalInfoSerializer(data=data) if personal_info_serializer.is_valid(): employee_appraisal = personal_info_serializer.save() return Response(employee_appraisal.appraisal_info(user=self.request.user), status=status.HTTP_201_CREATED) return Response(personal_info_serializer.errors, status=status.HTTP_400_BAD_REQUEST) test.py def test_personal_info_api(self): url = reverse('employee1-list') self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key) resp1 = self.client.post(url, data={'employee_id': 1, 'appraisal_master_id': 1}, format='json') print(resp1) self.assertEqual(resp1.status_code, 200) I am newbie for django and testing as well. Any help appreciable,. -
Not able to submit data from model form with multiple files django
I am trying to add multiple files through use of two models and forms. Have tried to update but not able to make it work. On submission of form, there are no errors, but nothing is posted to database. Please help. Also, how do I define users as full name in drop downs in forms? Tried formfields approach but not working. Also, form not showing empty label models.py class Case(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name= 'caseclients' ) statute = models.ForeignKey(Statute, on_delete=models.CASCADE) financial_year = models.ForeignKey(Financialyear, on_delete=models.CASCADE) proceeding = models.ForeignKey(Proceeding, on_delete=models.CASCADE) case_title = models.CharField(max_length=200) initiated_on = models.DateField(auto_now=False, auto_now_add=False) communication_received_on = models.DateField(auto_now=False, auto_now_add=False) first_date_of_hearing = models.DateField(auto_now=False, auto_now_add=False) limitation_period = models.CharField(max_length=500, blank=True) amount_involved = models.IntegerField(null=True,blank=True) person_responsible = models.ForeignKey(User, on_delete=CASCADE, related_name = 'person_responsible') assisted_by = models.ManyToManyField(User, related_name = 'assisted_by', blank=True) brief_of_case = models.TextField(max_length=1000) status = models.CharField(choices=[('Open','Open'),('Close','Close')],default='Open', max_length=100) def __str__(self): return self.case_title class CaseFiles(models.Model): attachment = models.FileField(upload_to='casefiles/') case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name= 'casefiles') forms.py class CaseFilesCreationForm(ModelForm): class Meta: model = CaseFiles fields = ['attachment'] attachment = forms.FileField, widgets= { 'attachment': forms.ClearableFileInput(attrs={'multiple': True, 'class': 'form-control form-control-light','type': 'file',}), } class CaseCreationForm(ModelForm): class Meta: model = Case fields = '__all__' client = forms.ModelChoiceField(queryset=Client.objects.all(), to_field_name="name_of_client", empty_label="Select Client",), statute = forms.ModelChoiceField(queryset=Statute.objects.all(), to_field_name="statute", empty_label="Select Statute",), financial_year = forms.ModelChoiceField(queryset=Financialyear.objects.all(), to_field_name="financialyear", empty_label="Select Financial Year",), … -
call the function response in another function in Django RestFramework
I tried calling the another function inside the function which will return the response.I have tried this approach but couldn't able to achieve it. I'm just getting error as AssertionError at /api/Data/CurrentRunningActivity2/54 Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` views.py: @api_view(['GET']) def CurrentRunningActivityView2(request, UserID): if request.method == 'GET': CurrentRunningActivity(UserID) def CurrentRunningActivity(UserID): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivity] @UserId=%s',(UserID,)) result_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) -
How to launch Django project / run server, with an exe
I have written the following .bat file: start chrome http://127.0.0.1:8000/ venv\Scripts\activate python manage.py runserver 8000 When I perform these steps myself, one by one, in prompt, it runs the server and opens the site perfectly. However, when I use iexpress to convert this file to an .exe and run it, the site just displays the "unavailable" message, as if no server were running. I'm not sure, but I think this is because the exe closes as soon as it's executed the commands, instead of keeping the server running. How do I fix this? -
Django logger is not shown that runs on Docker
logger.debug() and print() are not shown on a Django project that runs on Docker. Any other operations are correct. Is my recognition correct that the logs show up on the terminal window that runs docker-compose up? I tried outputting resolution, but it not work for me. My settings are below. directory Project ├── Service_ID │ ├── root │ ├──settings.py | ├── docker-compose.yml └── docker ├── mysql │ ├── Dockerfile │ └── my.cnf ├── nginx │ ├── default.conf │ └── uwsgi_params └── python ├── Dockerfile └── requirements.txt docker-compose.yml version: "3.8" services: ... web: image: nginx:1.21.3-alpine ports: - 8000:8000 volumes: - ./Service_ID:/workspace - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf - ./docker/nginx/uwsgi_params:/etc/nginx/uwsgi_params working_dir: /workspace depends_on: - root root: build: ./docker/python command: uwsgi --socket :8001 --module root.wsgi --py-autoreload 1 --logto /tmp/tmp.log volumes: - ./Service_ID:/workspace expose: - "8001" depends_on: - db volumes: db-store: python/Dockerfile FROM python:3.8.3 ENV PYTHONUNBUFFERED 1 RUN mkdir /workspace WORKDIR /workspace ADD requirements.txt /workspace/ RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt ADD . /workspace/ Service_ID/root/settings.py IS_ON_LOG_FILE = True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'file': { 'format': '\t'.join([ "[%(levelname)s]", "%(message)s", ]) }, 'console': { 'format': '\t'.join([ "[%(levelname)s]", "%(message)s", ]) }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, … -
I get mime type error when I connect my react app(via vite.js) with django framework
recently I'm starting to make a web application with React and Django. I installed react with vite.js(because it seems so fast in the development environment). and I connected it to Django web framework and ran it. and I thought It would show basic react page(you know, dark page and favicon is revolving ) However, contrary to my expectations, It only shows blank and I checked the console.log. the error message was this : Refused to apply style from 'http://127.0.0.1:8000/assets/index.cd9c0392.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. so I googled it and figure out that is a problem with the path in most cases. but when I check the my index.html in build file, path seems fine. below is my build folder structure and index.html, can you tell me what is wrong with my code or logic or both? thx for reading , your help will be appreciated. frontend -dist => this is build folder --assets ---index.cd9c0392.css ---favicon.21sd12.js . . . --index.html -node_modules -src -index.html . . . index.html(in dist) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/assets/favicon.17e50649.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite App</title> … -
How to set up Docker image of Celery with Django using a separate container
I would like to separate my Celery Docker container from my backend (Django) Docker container. I would like the Celery container to be built without relying on the backend container. Currently, all the tutorials I am finding online are set up so that the Celery image is built using the Backend container's context like such: backend: build: context: ./backend celery: build: context: ./backend I feel that Celery relying on the backend context to build the image is not the proper way to do this as there are a lot of resources not needed from the backend context in the celery container. Currently my project docker-compose looks as such: backend: build: context: ./backend celery: build: context: ./backend dockerfile: Dockerfile.celery Project dir tree: ├── backend │ ├── Dockerfile │ ├── Dockerfile.celery │ ├── Dockerfile.prod │ ├── entrypoint.dev.sh │ ├── entrypoint.prod.sh │ ├── requirements.txt │ └── venv ├── docker-compose.ci.yml ├── docker-compose.prod.yml ├── docker-compose.yml ├── frontend │ ├── Dockerfile │ ├── Dockerfile.prod ├── nginx │ ├── Dockerfile │ ├── Dockerfile.prod │ ├── certbot │ └── conf The Dockerfile.celery: FROM python:3.9.5-alpine WORKDIR /backend ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add … -
How to use a value from a query into another query in django
I have the following code in my view: # default group view for group admins def adminGroupView(request): # get group id => group data and messages group_id = GroupUser.objects.get(username_id=request.user.id) groupdata = Group.objects.get(group_id=group_id) groupmessages = MessageBoard.objects.filter(group_id=group_id) groupmembers = GroupUser.objects.filter(group_id=group_id) form = SendMessageForm() context = { "groupdata":groupdata, "groupmessages":groupmessages, "groupmembers":groupmembers, "form":form } return render(request, 'base/group-admin.html', context) I keep getting a typeerror TypeError at /group/ Field 'group_id' expected a number but got <GroupUser: 9>. when i replace the group_id with a number, the code works just fine. How do i use the value from the other query.