Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PostgreSQL HStore() field
I use multiple PostgreSQL HStore fields in my django model. Keys of HStore fields are big int numbers that are related to some other fields in application and are therefore random, not predefined. Values are decimal numbers. Like so: "10intNumber" => "DecNumber". All hstore fields have the same 10IntNumber keys in them, even if DecNumber is 0. The model also include a foreign key to user, and a status. Status is 1: only the hstore_field_1 is evaluated and summed. Status is 0: both hstore_field_1 and hstore_field_2 are evaluated and summed. I use a SQL Query like this, to sum all the DecNumber in values for predefined 10intNumber, where d.number is the 10IntNumber from before and is retrieved from another queryset.: query = f""" SELECT SUM(hstore_1::numeric) AS hstore_1_field, SUM(hstore_2::numeric) as hstore_2_field, FROM ( SELECT UNNEST(hstore_field_1-> ARRAY {[str(d.number) for d in queryset]}) AS hstore_1, UNNEST(CASE WHEN status = '0' THEN hstore_field_2-> ARRAY {[str(d.number) for d in queryset]} ELSE ARRAY ['0'] END) AS hstore_2, FROM public.app_model WHERE hstore_field_1?| ARRAY {[str(d.number) for d in queryset]} ) AS b; """ I also use a SQL query to group sums by related user_id and user__othemodel_id. But my knowledge of SQL comes short afterwards. I would like … -
tag inside bootstrap_button tag in django-bootstrap4
I have a question regarding the bootstrap_button template tag of django-bootstrap4 (https://django-bootstrap4.readthedocs.io/en/latest/templatetags.html#bootstrap-button) , could it be possible to include a tag from my tags in the href, something like this : {% bootstrap_button "Supprimer" button_type="link" href="../../delete/{{article.id}} " button_class="btn-danger" %} but {{article.id}} is not interpreted and it gives me a link to http://127.0.0.1:8000/delete/{{article.id}} I also tried : {% bootstrap_button "Supprimer" button_type="link" href="{% url 'delete' article.id %}" button_class="btn-danger" %} it returns TemplateSyntaxError at /edit/127/ Could not parse the remainder: '"{%' from '"{%' Request Method: GET Request URL: http://127.0.0.1:8000/edit/127/ Django Version: 3.0.5 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '"{%' from '"{%' but none of thos syntax is not working... Could you help me to make it work ? Man thanks -
Error while accessing CSS file Type scan linked CSS file
My code is not bad i think i have checked different websites and i have done what they did but for some reason my html code doesnt accept the css code in django {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> I have tried everything and honestly it is fustrating -
DJANGO PWA Install to home screen not working
I am trying to follow the instructions on this site (https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Add_to_home_screen) with my DJANGO app to make a PWA "Install to home screen' button. I have SSL installed on the site, and it seems to me that the service worker is installed properly, I got the "Service Worker Registered" message back. However when I click the button I nothing happens, the + sign does not appear in the URL bar as it should. I have no idea what is causing the error, as there is no clear sign of anything not working properly. My index.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>A2HS demo</title> <link href="{% static 'css/index.css' %}" rel="stylesheet"> <script src="{% static 'js/index.js' %}" defer></script> <link rel="manifest" href="{% static 'manifest.json' %}"> </head> <body> <button class="add-button">Add to home screen</button> </body> </html> My manifest.json: { "short_name": "Test site", "name": "Test site", "theme_color": "#062440", "background_color": "#F7F8F9", "display": "fullscreen", "icons": [ { "src": "assets/logo.png", "type": "image/png", "sizes": "192x192" } ], "start_url": "/index.html" } My index.js // Register service worker to control making site work offline if ('serviceWorker' in navigator) { navigator.serviceWorker .register('/static/js/service-worker.js') .then(() => { console.log('Service Worker Registered'); }); } // Code to handle install prompt on desktop let deferredPrompt; … -
In Django what does the request argument in a method do?
I have seen a few codes where sometimes the authenticate method have the request argument while other times it does not, e.g. see the below codes: Code 1: def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() # code for automatic login after singing up username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) return redirect('/') Code 2: def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) According to the official docs: request is an HttpRequest and maybe None if it wasn’t provided to authenticate() (which passes it on to the backend). What does this request argument actually do and when should I consider passing it in the authenticate or login method? Is there any specific reason for which request argument is present or absent in the above codes? -
how to solve static file error in my django app
Request Method: GET Request URL: http://127.0.0.1:8000/static/mytxt.txt 'mytxt.txt' could not be found -
Unable to follow django-quickbooks Documentation
I am working on Django web application and i want to push data in Quickbook Desktop. So i was following https://github.com/weltlink/django-quickbooks/ this link and in the third step where you have to create qwc file with manage.py command is not working. So, Is there any better way to integrate django and quickbook desktop? Or Is there any better Documentation? -
How do you access a ForeignKey's other attribute in Django?
I've been looking for a way to retrieve a model's attribute via ForeignKey(related_name). I'm going to paste the code below. Django version is 3.1, while Python version is 3.7. accounts.models.py class Company(models.Model): name = models.CharField(max_length=60) industry = models.CharField(max_length=20, choices = INDUSTRY_CHOICES, default="agriculture") partner.models.py class Partnership(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) creator = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="partnership_creator_set") partner = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="partner_set") So when a Company partners with another Company, 2 instances of Partnerships are created. How do i get get the number of existing partners for a specific company? I'm able to get a Company instance then use the related name to get the existing partnerships. If I try something like Company.partnership_creator_set.all(), I'm able to get the list of partnerships. What I want is to look for the current partners which is in the "partner" attribute in the Partnership model. -
Django creating radar chart with Json
I created a system with Django. I need some charts for my project and I am using chart.js library. I get data from an API address, I can get the data correctly with Json and display it in a table, but I can not display it in the radar chart. I think I cannot write Javascript code correctly because Radar chart does not show anything. views.py def Radar(request): response = requests.get('https://api.f-rayscoring.com/company/ADESE/radar') data = response.json() return render(request, 'radar.html', {'data': data}) radar.html <div class="content"> <div class="page-inner"> <h4 class="page-title">Radar Chart</h4> <div class="row"> <div class="col-md-6"> <div class="card"> <div class="card-header"> <div class="card-title">Radar Chart</div> </div> <div class="card-body"> <div class="chart-container"> <canvas id="radarChart"></canvas> </div> </div> </div> </div> </div> </div> </div> {% endblock content %} {% block javascripts %} <script src="/static/assets/js/setting-demo2.js"></script> <script> radarChart = document.getElementById('radarChart').getContext('2d') {% for dt in data %} var myRadarChart= new Chart(radarChart, { type: 'radar', data: { labels: [{{ dt.title }}], datasets: [{ data: [{{ dt.value }}], borderColor: '#1d7af3', backgroundColor : 'rgba(29, 122, 243, 0.25)', pointBackgroundColor: "#1d7af3", pointHoverRadius: 4, pointRadius: 3, label: 'Team 1' }, { data: [], borderColor: '#716aca', backgroundColor: 'rgba(113, 106, 202, 0.25)', pointBackgroundColor: "#716aca", pointHoverRadius: 4, pointRadius: 3, label: 'Team 2' }, ] }, options : { responsive: true, maintainAspectRatio: false, legend : … -
django-admin cannot create project due to - bad interpreter
% pip install django Collecting django Using cached Django-3.1.5-py3-none-any.whl (7.8 MB) Requirement already satisfied: pytz in ./virtualenvproj/lib/python3.8/site-packages (from django) (2020.5) Requirement already satisfied: asgiref<4,>=3.2.10 in ./virtualenvproj/lib/python3.8/site-packages (from django) (3.3.1) Requirement already satisfied: sqlparse>=0.2.2 in ./virtualenvproj/lib/python3.8/site-packages (from django) (0.4.1) Installing collected packages: django Successfully installed django-3.1.5 % pip freeze asgiref==3.3.1 Django==3.1.5 pytz==2020.5 sqlparse==0.4.1 % python -V Python 3.8.0 % django-admin startproject myproject zsh: /usr/local/bin/django-admin: bad interpreter: /usr/local/opt/python@2/bin/python2.7: no such file or directory After Big Sur Mac OS update, quite a lot of thing being messed up python and djangp. -
Django Queryset instead of for loops and if statements in views.py
I've got the following models: class Post(models.Model): description = models.TextField() post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_on = models.DateField(auto_now_add=True, verbose_name=_("created on")) liked_users = models.ManyToManyField(User, blank=True, related_name='liked_post') disliked_users = models.ManyToManyField(User, blank=True, related_name='disliked_post') class Image(models.Model): post = models.ForeignKey(Post, null=True, default=None, on_delete=models.CASCADE, related_name='parent_post') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) images = models.ImageField(upload_to = 'images/') class Tag(models.Model): name = models.CharField(max_length=100) weight = models.IntegerField(default=0) post = models.ForeignKey(Post, null=True, default=None, on_delete=models.CASCADE,related_name='post') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) and in accounts class User(AbstractUser): user_id = models.UUIDField( default=uuid.uuid4, editable=False, primary_key=True ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) liked_posts = models.ManyToManyField('post.Post', blank=True, related_name='user_liked') disliked_posts = models.ManyToManyField('post.Post', blank=True, related_name='user_disliked') liked_tags = models.ManyToManyField('post.Tag' , blank=True, related_name='user_liked') disliked_tags = models.ManyToManyField('post.Tag', blank=True, related_name='user_disliked') Here is my get_queryset method in views.py def get_queryset_post(self, user): liked_tags = user.liked_tags.all() disliked_tags = user.disliked_tags.all() posts = Post.objects.all() sorted_posts = [] liked_posts = [] disliked_posts = [] normal_posts = [] for post in posts: is_break = False is_added = False post_tags = Tag.objects.filter(post=post) for tag in post_tags: if is_break: break for liked_tag in liked_tags: if tag.name == liked_tag.name: liked_posts.append(post) is_break = True is_added = True break else: for disliked_tag in disliked_tags: if tag.name == disliked_tag.name: disliked_posts.append(post) is_added = True is_break = True break if is_added == False: normal_posts.append(post) continue for i in … -
HTTPConnectionPool: Max retries exceeded Caused by NewConnectionError: Failed to establish a new connection: [Errno 13] Permission denied
Hi I'm trying to get REST request from a certain URL and if I input the url directly in the browser it works ok and output is as show in the image below If I also try to query the url via native python, it works fine too. The problem is when i put the request in view.py in my django project I get a connection error as the the title of this question. import requests def my_method(request): response = requests.get('http://10.150.20.103:8000/se/se-seid') special_events_dashboard_events = response.json() for event in special_events_dashboard_events['events']: context['special_events'].append(event) return render(request, 'updates/updates_network.html', context) When I check the page in the browser, I get this error. The REST API url is of different IP Address from my django application. Is this a setting problem in my django application? How to work around this? I have been searching in the internet but I cant seem to find an answer to this. -
download file from s3 uisng django
I am able to read the uploaded file but not able to download it Here is my code from storages.backends.s3boto import S3BotoStorage from boto.s3.connection import S3Connection from boto.s3.key import Key import boto3 from boto3.session import Session import StringIO def download(request, opp_id, document_id): c = setup_context(request) client = request.user.client document = get_object_or_404(RecordDocument, record_id=opp_id, pk=document_id) bucket_name = 'mybucket' key = document.document.name ( when print key u'record/3/AASQIO4L67EU_test.csv') s3_client = boto3.client('s3') s3_response_object = s3_client.get_object(Bucket=bucket_name,Key=key) s3_response_object['Body'].read() s3 = boto3.resource('s3') string_io = StringIO.StringIO() s3.Object(bucket_name, key).download_fileobj(string_io) return redirect(reverse('record_view', kwargs={"pk": opp_id})) Here by file is getting read but not able to download the file -
Is there any way to install and import explainx library from explainX.ai (Artificial intelligence) in python or django
Is there a way to import explainx from explainX.ai the library in django framework , i am facing some problem in installing this library in python 3.7(32-bit), python 3.9.1(64-bit), but I have installed it into python 3.7.4(64-bit) but when i import explainx library from explainX.ai it gives me errorlike this :- ImportError: DLL load failed: The specified module could not be found. i will share whole it for reference ------------------------------------------------------------------------------ Microsoft Windows [Version 10.0.18363.1316] (c) 2019 Microsoft Corporation. All rights reserved. C:\Users\Ayush>pip show explainx Name: explainx Version: 2.406 Summary: Explain and debug any black-box Machine Learning model. Home-page: https://github.com/explainX/explainx Author: explainx.ai Author-email: muddassar@explainx.ai License: MIT Location: c:\users\ayush\appdata\local\programs\python\python37\lib\site-packages Requires: jupyter-dash, dash-bootstrap-components, dash, dash-core-components, dash-html-components, plotly, dash-table, pandas, numpy, dash-bootstrap-components, cvxopt, scikit-learn, scipy, pandasql, tqdm, dash-editor-components, shap, dash-daq, pytest, pyrebase Required-by: C:\Users\Ayush>python Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import explainx Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\Ayush\AppData\Local\Programs\Python\Python37\lib\site-packages\explainx\__init__.py", line 1, in <module> from explainx.explain import * File "C:\Users\Ayush\AppData\Local\Programs\Python\Python37\lib\site-packages\explainx\explain.py", line 16, in <module> from dashboard import * File "C:\Users\Ayush\AppData\Local\Programs\Python\Python37\lib\site-packages\explainx\lib\dashboard.py", line 3, in <module> from protodash import * File "C:\Users\Ayush\AppData\Local\Programs\Python\Python37\lib\site-packages\explainx\lib\protodash.py", line … -
How to structure models in Django?
I'm working on a project using Python(3.7) and Django(3) in which I have to create some models to store reports. There are 4 different models to represents each type of report with only 2 common fields(RequestId, InstCode) but the rest of the fields are different. In the end, I have to display the 10 recent reports (mixed from all models) on the home page. Here's how I have implemented my models at the moment: From models.py: class DistributionReport(models.Model): RequestId = models.CharField(max_length=256, blank=False, default=0) InstCode = models.CharField(max_length=3, blank=False) Currency = models.CharField(max_length=3, blank=False) Denomination = models.IntegerField(blank=False, default=0)decimal_places=2) date = models.DateField(default=datetime.date.today) class Meta: verbose_name = 'Distribution Report' def __str__(self): return self.RequestId class ExpenditureReport(models.Model): RequestId = models.CharField(max_length=256, blank=False, default=0) InstCode = models.CharField(max_length=3, blank=False) StaffExpenditure = models.DecimalField(max_digits=12, decimal_places=2) Month = models.IntegerField(blank=False, default=0) Quarter = models.IntegerField(blank=False, default=0) Year = models.IntegerField(blank=False, default=0) class Meta: verbose_name = 'Expenditure Report' def __str__(self): return self.RequestId class StorageReport(models.Model): RequestId = models.CharField(max_length=256, blank=False, default=0) InstCode = models.CharField(max_length=3, blank=False) Currency = models.CharField(max_length=5, blank=False) Denomination = models.IntegerField(blank=False, default=0) date = models.DateField(default=datetime.date.today) class Meta: verbose_name = 'Processing Report' def __str__(self): return self.RequestId class AssetsReport(models.Model): RequestId = models.CharField(max_length=256, blank=False, default=0) InstCode = models.CharField(max_length=3, blank=False) AssetClassificationId = models.IntegerField(blank=False, default=0) VaultCapacity = models.DecimalField(max_digits=10, decimal_places=2) Year = models.IntegerField(blank=False, default=0) … -
I have problem with AutoField in my model and seqence in oracle database
I use Legacy database oracle 11g and there are a seqences. If I remove number_mymodel field from my model i have an error: ORA-00904: "MYMODEL"."ID": invalid identifier if i try class MyModel(models.Model): number_mymodel = models.AutoField(primary_key=True ,auto_created=True) ... it's work, but if I want add in my django admin panel number_Mymodel is NULL so I can't add it. What should I do with my sequence in database or in my model? I want that, if I'm adding in django panel it will be autoincrement number_mymodelin my database. -
I want to edit SizeProductMapping model using Django forms but The form is not rendering - Django
I am trying to create a edit form to update the database using Django model Forms but the problem is that edit form part of the sizeProductMap.html page is not rendering when edit form (sizeProductMap_edit) request is made. My models are as shown below. models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", null=True) def __str__(self): return "{}-->{}".format(self.prod_ID, self.prod_Name) class Size(models.Model): size_id = models.AutoField("Size ID", primary_key=True, auto_created=True) prod_size = models.CharField("Product Size", max_length=20, null=False) def __str__(self): return "{size_id}-->{prod_size}".format(size_id=self.size_id, prod_size=self.prod_size) class SizeProductMapping(models.Model): size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True) size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID") prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id") def __str__(self): return ".`. {}_____{}".format(self.size_id, self.prod_id) This is the form I used to add and edit the model. forms.py from django import forms from user.models import SizeProductMapping class SizeProductMapForm(forms.ModelForm): class Meta: model = SizeProductMapping fields = ['size_id', 'prod_id'] Here is the view I created to add ,update and delete the record. views.py def sizeProductMap(request): form = SizeProductMapForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): form.save() return redirect("/admin1/sizeProductMap/") else: sizeProductMap_show = SizeProductMapping.objects.all() # start paginator logic paginator = … -
getaddrinfo: xxURL get result from proxy gai_error = 0
Im building a flutter application which uses django ad back-end. using signup api endpoint. the api shows error 200 from the logs but signup doesnt go through. the logs D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 I/flutter ( 8600): 200 D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 I/flutter ( 8600): 200 D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 I/flutter ( 8600): 200 I/flutter ( 8600): 200 D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 I/flutter ( 8600): 200 D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 I/flutter ( 8600): 200 sign up service Future<int> authUserSignup(String username, String password, String email) async { http.Response response = await http.post( signUpUrl, body: { "username": username, // "phone":phone, "password": password, "email": email, } ); print(response.statusCode); return response.statusCode; } on signup onClicK _pressCreateAccountButton(){ //TO DO: MOVE TO VERIFY PHONE SECTION var signMeUp = connectSigninApi.authUserSignup(editControllerName.text, editControllerEmail.text, editControllerPassword2.text); if(signMeUp == 200){ if(_globalformkey.currentState.validate() && matchesEmail.hasMatch(editControllerEmail.text)){ if(editControllerPassword1.text == editControllerPassword2.text){ print("User pressed \"CREATE ACCOUNT\" button"); print("Login: ${editControllerName.text}, E-mail: ${editControllerEmail.text}, " … -
What is the POST equivalent for requesting GET parameters?
I want to request the paths through the POST method because the request lines are too large in the url created by the GET method. Is there any alternatives for request.GET.getlist('paths') if the paths are very long, then it shows Bad Request, Request Line too large. I also know how to use Post in templates too. views.py def test_download(request): paths = request.GET.getlist('paths') context ={'paths': paths} response = HttpResponse(content_type='application/zip') zip_file = zipfile.ZipFile(response, 'w') for filename in paths: zip_file.write(filename) zip_file.close() response['Content-Disposition'] = 'attachment; filename='+'converted files' return response templates <a href ="{% url 'test_download' %}?{% for path in paths %}paths={{ path|urlencode }}&{% endfor %}">Converted Files</a> -
How to use list as queryset for select filed django
Is there any way that list value can be used as a query set? I want to show the SKU return shown at the bottom as the data of the select field. I'm really new to Django. Any help would be greatly appreciated. Model Form: class PurchaseOrderDetailsForm(forms.ModelForm): product = forms.ModelChoiceField(label=('Product'), required=True, queryset=Product.objects.all(), widget=Select2Widget()) product_attr = forms.CharField(label=('Attributes'), widget=Select2Widget()) order_qnty = forms.DecimalField(label=('Order Qnty'), required=True) class Meta: model = PurchaseOrder_detail exclude = () def __init__(self, *args, **kwargs): super(PurchaseOrderDetailsForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.fields['product'].widget.attrs.update({'class': 'setprice product', 'style': 'width:100%', 'required': 'true'}) self.fields['product_attr'].widget.attrs.update({'class': 'setprice product_attr', 'style': 'width:250px'}) self.fields['order_qnty'].widget.attrs.update({'class': 'setprice order_qnty', 'min': '0', 'required': 'true'}) self.fields['product_attr'].queryset = ProductAttributes.objects.none() if 'product' in self.data: product_id = int(self.data.get('product')) attrs = ProductAttributes.objects.filter(product=product_id).values('product', 'size__name', 'colour__name', 'cupsize__name') sku = [] for attr in attrs: att = {'id': '-'.join([str(attr['product']), str(attr['size__name']), str(attr['cupsize__name']), str(attr['colour__name'])]), 'text': '-'.join( [str(attr['size__name']), str(attr['cupsize__name']), str(attr['colour__name'])])} sku.append(att) try: self.fields['product_attr'].queryset = sku except (ValueError, TypeError): pass sku return: [{'id': '108-32-B-Grey', 'text': '32-B-Grey'}, {'id': '108-32-C-Grey', 'text': '32-C-Grey'}, {'id': '108-32-B-White', 'text': '32-B-White'}, {'id': '108-32-C-White', 'text': '32-C-White'}, {'id': '108-34-B-Grey', 'text': '34-B-Grey'}, {'id': '108-34-C-Grey', 'text' : '34-C-Grey'}, {'id': '108-34-B-White', 'text': '34-B-White'}, {'id': '108-34-C-White', 'text': '34-C-White'}] -
Django Error: ValueError at /new_bid/1 Cannot assign "1": "Bid.listingid" must be a "Listings" instance
I am getting the error: ValueError at /new_bid/1 Cannot assign "1": "Bid.listingid" must be a "Listings" instance." I am still learning about Foreign Keys so I may have used it wrong? I'm also using 'listingid' in both the models 'Listings' and 'Bid.' I'm wondering if this is part of the issue, but it makes sense to have both to me. I am just learning about how 'self' works also, so I think part of the problem is in the Listings model at the very bottom: In the Listings model if I do: return self.last_bid I get the error "'>' not supported between instances of 'int' and 'Bid'" and if I keep it as is now, I get the error in the title of this Stack Overflow post. Any help is appreciated, I'm having trouble understanding the error. views.py def new_bid(request, listingid): if request.method == "POST": listing = Listings.objects.get(pk=listingid) response = redirect("listingpage", listingid=listingid) try: bid = int(request.POST["bid"]) except ValueError: response.set_cookie( "message", "Please input something before submitting the bid", max_age=3 ) return response if bid > listing.current_price(): response.set_cookie("message", "Your bid was accepted", max_age=3) Bid.objects.create(bid=bid, listingid=listingid, user=request.user) else: response.set_cookie( "message", "Your bid should be higher than the current bid", max_age=3 ) return response … -
Serialize Django Model and return GET Response
I am trying to serialize the queryset objects I created when retrieving all jobs from my model. Basically I want an endpoint that lists all jobs that are currently created in the database. Anyone has permissions to view the jobs. However you need to be authenticated to POST, DELETE, or EDIT new jobs. My problems is just making the jobs viewable at the endpoint i created using APIView. I was getting an error before that says the object is not in JSON format. views.py class RetrieveJobsView(APIView): """Retrieves all job postings""" serializer_class = serializers.JobSerializer def get(self, request, format=None): """ Return a list of all jobs""" queryset = Job.objects.all() queryset = serializers.JobSerializer(queryset) return Response(queryset) serializers.py class JobSerializer(serializers.ModelSerializer): """Serializer for tag objects""" class Meta: model = Job fields = ('id', 'description', 'job_type', 'city', 'state', 'salary', 'position', 'employer', 'created_date', 'is_active') read_only_fields = ('id',) def create(self, validated_data): """Create a job posting with user and return it""" user = self.context['request'].user print(self.context['request']) if not user: msg = _('Unable to POST job request. A valid user must be logged in.') raise serializers.NotAuthenticated(msg, code=None) validated_data[user] = user return validated_data models.py class Job(models.Model): """A Job used to create a job posting""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) description = models.TextField() … -
Django API responding slow and not returning Images on Heroku
I'm trying to host my Django Rest API to heroku for free so that my flutter mobile app can communicate with it. But the server response is extremely slow. Besides, it doesn’t returns images for user profile. Moreover, I'm using Image recognition at API to check image objects and return the checked image to client end. But the API fails to return the result. What could be the possible solution. I've applied migrations to server's end. N.B: it’s my University final project which needs to be hosted, so that I can show it for getting jobs. -
Foreign key of models should refer to a particular filed in db - Django
class UserModel(AbstractUser): USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'password'] email = models.EmailField(unique=True) profile_image = models.ImageField(upload_to='user/profile_image', null=True, blank=True) phone = models.CharField(max_length=12, unique=True, blank=True, null=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) emp_id = models.CharField(max_length=20, unique=True, blank=True, null=True) class IndividualWorkAnalysis(models.Model): user_id = models.ForeignKey(UserModel, to_field="emp_id", on_delete=models.CASCADE, null=True, related_name="user_id") Here above I need to access 'emp_id' from 'UserModel'. All my migrations went correct, but not able to fetch the 'emp_id' on the admin panel of Django. There it just lists the usernames. -
How to write data to a Django temp file?
Hello Community! I have a small application that allows you to download certain multimedia content from an HTML template. To save resources, I want this file to be stored only on the PC of the users who visit the eventual website, which is why I will use a temporary file NamedTemporaryFile that the FrameWork Django provides. Part of the code consists of: HTML TEMPLATE: ... <input type = "button" value = "Download" onclick = "window.open('download')"> ... urls.py: from django.urls import path from ProjectApp import views urlpatterns = [ ... path('download', views.download), ... ] views.py: import os from django.http import StreamingHttpResponse from wsgiref.util import FileWrapper from django.http import HttpResponse from django.core.files.temp import NamedTemporaryFile def download(request): newfile = NamedTemporaryFile (suffix='.txt', mode='w+b') file_path = os.path.join(MEDIA_ROOT, 'test.txt') # MEDIA_ROOT = os.path.join(BASE_DIR, 'media') filename = os.path.basename('archive_test.txt') chunk_size = 8192 response = StreamingHttpResponse( FileWrapper(newfile, chunk_size), content_type="application/octet-stream") response['Content-Length'] = os.path.getsize(file_path) response['Content-Disposition'] = f'attachment; filename={filename}' return response It should be noted that as I show it, it works as I wish, since a download dialog appears in the browser with the archive_test.txt file in a "starting" state. What I want is that from that moment on, the information that it will contain begins to be written to said …