Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serve different CSS file when user change language in Django i18n translation
I am using Django i18n translation system and there are two languages: LANGUAGES = ( ('fa', _('Persian')), ('en', _('English')), ) Persian is Right-To-Left and I want to serve another CSS file when user change language to persian. Or maybe there is a better way to change LTR to RTL when user change the language? I am using nginx with wsgi on a Ubuntu vps. -
How to make Django url template with variable find the correct url
In my urls.py I have: path('experiments/charts/<str:part_tag>/', ExpViews.bokehChart, name='part_tag') I'd like to pass a string argument "part_tag" to the function bokehChart. and I'm trying to give the "path_tag" string variable some values as follows: {% for part in parts %} <ul class="list=group"> {% for datapoint in part.datapoints %} <a href="{% url 'part_tag' part.tag %}" class="list-group-item list-group-item-success"> {{datapoint}} </a> {% endfor %} </ul> {% endfor %} I get the following error on my webpage: Reverse for 'part_tag' not found. 'part_tag' is not a valid view function or pattern name. I know similar questions have been asked, but I can't get it to work in my case. -
How to delete a row and create new one with updated info in pre_save signal to avoid already exists error?
I want to edit existing row with pre_save signal and update quantity. here is my models class RFIDItem(models.Model): rfid = models.ForeignKey(RFIDInfo, on_delete=models.CASCADE, null=True, blank=True, related_name='rfid_item_rfid', help_text="Select RFID") product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=True, blank=True, related_name='rfid_item_pr_type', help_text="Select Product Type") quantity = models.PositiveIntegerField(_("Quantity"), default=0) expire_date = models.DateTimeField(default=datetime.now()) created_date = models.DateField(auto_now=False, auto_now_add=True) updated_date = models.DateField(auto_now=True, auto_now_add=False) If i add duplicate RFIDItems then my signal will edit/create new one with new quantity. I tried to do this i signal's pre_save method. Any Idea How can i do this. Thank You. and here is my signals. @receiver(pre_save, sender=RFIDItem) def create_related_models(sender, instance=None, *args, **kwargs): rfid = instance.rfid product_type = instance.product_type expire_date = instance.expire_date if RFIDItem.objects.filter(rfid=rfid, product_type=product_type, credit_type=credit_type,expire_date=expire_date).exist(): rfid_item = RFIDItem.objects.filter(rfid=rfid, product_type=product_type, credit_type=credit_type,expire_date=expire_date).last() rfid_item.delete() new_rfid = RFIDItem.objects.filter(rfid=rfid, product_type=product_type, credit_type=credit_type,expire_date=expire_date) new_rfid.quantity += instance.quantity new_rfid.save() -
I'm trying to get the environmental conditions of a city but this schema error keeps popping up
im trying to find the weather for a city and this error pops up. what does it mean ? my views def index (request) : url='api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=abb1576248c3805529abb4a8bd6a2b61' city='Las Vegas' r=requests.get(url.format(city)) print(r.text) return render(request,'weather/weather.html') mu urls urlpatterns = [ path('', views.index) ]``` -
How are Django custom widget assets retrieved by the browser?
I have been reading this part of the django documentation : https://docs.djangoproject.com/en/3.0/topics/forms/media/#assets-as-a-static-definition and this raised a question for me. I think in order for the animations and actions js files to be used by the browser they have to be referenced in a script html tag. As defining js assets in the form widget, like shown in the documentation, does not add any tag in the html template I do not understand how these files will be retrieved by the browser. -
Call a separate Python script in Django Views present at same location
I have a Django project name 'myproject' & app name 'dbapp' like this - myproject | |----dbapp | |----model.py | : |----views.py | |----start.py I want to run a Python script name 'start.py' through Django Views. I am using this syntax - @api_view(['GET', 'POST']) def page(request, uuid): if request.method == 'GET': call(["python3", "start.py"]) return Response('dbname') Python Script - 'start.py' call 2 other python scripts like this - call(["python3", "create_host.py"]) call(["python3", "create_main.py"]) If I run start.py, it works as expected running both the called python files. But Django Views is giving error when it call start.py script using given syntax. Error - python3: can't open file 'start.py': [Errno 2] No such file or directory How can I call a separate python file through Django views. I even tried this syntax - call(["python3", "urldbapp/start.py"]) This gives error like this - python3: can't open file 'start.py': [Errno 2] No such file or directory What syntax should I use? P.S. - 'start.py' is a small Python script but it further calls 2 Python scripts. -
How to display "permission_denied_message" in custom 403.html page in Django
How do we correctly display exception message in custom 403 error in Django? In my signup view I am using: class SignUpView(LoginRequiredMixin, PermissionRequiredMixin, CreateView): login_url = 'error_403' # .... # ... permission_denied_message = 'You are not allowed this transaction!! Ha Ha!!' # raise PermissionDenied() # ('permission_denied_message') raise_exception = True Now how do I display the message ("permission_denied_message"?) in my custom 403.html? This is my function to render the error page: def error_403(request, exception): data = {} add_user = 'add_user' data = {'perm': add_user} return render(request, '403.html', data) I have been through a lot of matter on the subject (including those on SO) but could not succeed in displaying the error message (except the static message that I have put in my "403.html"). I have used {{ exception}} in the template but nothing gets displayed (execpt the static message that I already have). 1. How do I display the permission_denied_message in custom 403 page? 2. Presently I am manually updating some raw data in dict data{} in function error_403, which gets rendered on the 403 error page. What is the correct usage of the dict? -
How to prevent extra query for this field in Django?
I have models like this: class City(models.Model): some_field = models.ForeignKey('self') name = models.CharField(max_length=100) class Author(models.Model): city = models.ForeignKey(City) # other fields def get_some_field(self): return self.city.some_field some_field = cached_property(get_some_field, name='some_field') I fetch Author queryset something like this: author_qs = Author.objects.filter(**some_filter).select_related('city') Now after fetching the queryset, I do something like this: city_name = author_qs.some_field.name But this line is querying the database again for City model. How can I prevent this extra query, and get city_name with previous query only. P.S. I cannot directly get author_qs.city.name. I require it to call from some_field only -
Subtraction in Django using many to many relationship
I have two models Order and Supplement, The Order model has many to many relationship with the Supplement model. I'm using celery to run a task that subtracts the quantity of a selected supplement. The problem I'm facing is that I'm only able to subtract from 1 supplement even if I have selected more than 1 supplement in my order.supplement field. class Order(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=100) status = models.CharField(max_length = 100) box = models.IntegerField(max_length = 100) supplement = models.ManyToManyField('Supplement') class Supplement(models.Model): stockId = models.AutoField(primary_key=True) brand_name = models.CharField(max_length=100) supplement_name = models.CharField(max_length=100) supplement_type = models.CharField(max_length=100) quantity = models.IntegerField(default='0', blank=True, null=True) def __str__(self): return self.supplement_name tasks.py def deduct_inventory(): orders = Order.objects.all() for order in orders: if order.status == 'Shipped': for supplement in order.supplement.all(): Supplement.objects.filter(supplement_name=supplement.supplement_name).update(quantity=F('quantity') - order.box*30) Material.objects.filter(material_name='Packs').update(quantity=F('quantity')-order.box) Material.objects.filter(material_name='Dispenser').update(quantity=F('quantity')-order.box) Material.objects.filter(material_name='Cargo Box').update(quantity=F('quantity')-order.box) order.status='Delivered' order.save() return None -
ValueError: Missing staticfiles manifest entry for 'favicon.png'
I'm trying to deploy my django web app to heroku for the first time, but I keep getting a 500 server error. This is what I see when I check the logs: 2020-07-30T05:03:27.965070+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 423, in stored_name 2020-07-30T05:03:27.965070+00:00 app[web.1]: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) 2020-07-30T05:03:27.965070+00:00 app[web.1]: ValueError: Missing staticfiles manifest entry for 'favicon.png' 2020-07-30T05:03:27.965366+00:00 heroku[router]: at=info method=GET path="/" host=programatic-learning.herokuapp.com request_id=1332a937-88d1-48f0-8aac-0847852e467d fwd="67.70.149.199" dyno=web.1 connect=1ms service=72ms status=500 bytes=380 protocol=https 2020-07-30T05:03:27.965534+00:00 app[web.1]: 10.63.123.248 - - [30/Jul/2020:05:03:27 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36" 2020-07-30T05:33:17.000000+00:00 app[api]: Build started by user stephenlang91@gmail.com 2020-07-30T05:34:28.791656+00:00 app[api]: Deploy 599627a3 by user stephenlang91@gmail.com 2020-07-30T05:34:28.791656+00:00 app[api]: Release v8 created by user stephenlang91@gmail.com 2020-07-30T05:34:28.961452+00:00 heroku[web.1]: Restarting 2020-07-30T05:34:28.976045+00:00 heroku[web.1]: State changed from up to starting 2020-07-30T05:34:30.150144+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2020-07-30T05:34:30.184774+00:00 app[web.1]: [2020-07-30 05:34:30 +0000] [9] [INFO] Worker exiting (pid: 9) 2020-07-30T05:34:30.184787+00:00 app[web.1]: [2020-07-30 05:34:30 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-07-30T05:34:30.185022+00:00 app[web.1]: [2020-07-30 05:34:30 +0000] [4] [INFO] Handling signal: term 2020-07-30T05:34:30.385825+00:00 app[web.1]: [2020-07-30 05:34:30 +0000] [4] [INFO] Shutting down: Master 2020-07-30T05:34:30.461780+00:00 heroku[web.1]: Process exited with status 0 2020-07-30T05:34:35.278873+00:00 heroku[web.1]: Starting process with command `gunicorn blog.wsgi --log-file -` 2020-07-30T05:34:37.599742+00:00 … -
how can i controll static entry in django?
I want call django static files. i use django_debug_toolbar anddrf_yasg. my stage is local and dev (deploy docker container, DEBUG=True). and Staticfile in AWS S3 django_storages when i access swagger page in local stage, chrome development tool Source like this. - top - 127.0.0.1:8000 - swagger - index - static - debug_toolbar - drf_yasg and dev stage, chrome development tool Source like this. - top - 127.0.0.1:8000 - swagger - index - blarblar.s3.amazonaws.com - static/drf_yasg can u see that? i dont understatnd this. i want static both debug toolbar and drf yasg. my settings base.py STATIC_URL = '/static/' local.py STATIC_ROOT = os.path.join(ROOT_DIR, 'static') dev.py AWS_S3_REGION_NAME = os.environ.get('AWS_REGION', 'ap-northeast-2') AWS_STORAGE_BUCKET_NAME = S3_Storange_name STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storage.StaticStorage' what can i do? i don't know what i should do. -
Django-silver package pip installer error
First time trying to ask question here. I was trying to install django-silver (a Django package for invoice). However I encountered the following error in my Windows command line. I have made sure my python, pip, django versions are all up-to-date. I am using virtual environment to install django-silver package. Error here (I can't insert all due to character limit): C:\Users\bigfa\PycharmProjects\silver_test\venv\silver_test\Scripts>pip install django-silver Processing c:\users\bigfa\appdata\local\pip\cache\wheels\96\1a\a5\28dd03757aa4e0922a390c62c65bf74a95011c6cb9af20432f\django_silver-0.10.0-py3-none-any.whl Requirement already satisfied: django-livefield<3.3,>=2.8 in c:\python38\lib\site-packages (from django-silver) (3.2.1) Requirement already satisfied: django-autocomplete-light<3.3,>=3.2 in c:\python38\lib\site-packages (from django-silver) (3.2.10) Requirement already satisfied: python-dateutil<2.8,>=2.6 in c:\python38\lib\site-packages (from django-silver) (2.7.5) Processing c:\users\bigfa\appdata\local\pip\cache\wheels\ea\13\5b\39f00fc59997caaaa0031e791afc8a2618f35c4eb92f646461\furl-1.2.1-py3-none-any.whl Requirement already satisfied: sqlparse<0.3,>=0.2 in c:\python38\lib\site-packages (from django-silver) (0.2.4) Processing c:\users\bigfa\appdata\local\pip\cache\wheels\b1\1a\8f\a4c34be976825a2f7948d0fa40907598d69834f8ab5889de11\pypdf2-1.26.0-py3-none-any.whl Requirement already satisfied: django-annoying<0.11,>=0.10 in c:\python38\lib\site-packages (from django-silver) (0.10.6) Requirement already satisfied: django-filter<2.1,>=1.1 in c:\python38\lib\site-packages (from django-silver) (2.0.0) *various requirement satified* Requirement already satisfied: cffi!=1.11.3,>=1.7 in c:\python38\lib\site-packages (from cryptography<2.4,>=1.9->django-silver) (1.14.0) Requirement already satisfied: setuptools in c:\users\bigfa\pycharmprojects\silver_test\venv\silver_test\lib\site-packages (from djangorestframework-bulk<0.3->django-silver) (49.2.0) Requirement already satisfied: pytz in c:\python38\lib\site-packages (from Django<2.3,>=1.11->django-silver) (2020.1) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\python38\lib\site-packages (from requests<3.0,>=1.0.0->pyvat<1.4,>=1.3->django-silver) (1.25.10) Requirement already satisfied: certifi>=2017.4.17 in c:\python38\lib\site-packages (from requests<3.0,>=1.0.0->pyvat<1.4,>=1.3->django-silver) (2020.6.20) Requirement already satisfied: chardet<4,>=3.0.2 in c:\python38\lib\site-packages (from requests<3.0,>=1.0.0->pyvat<1.4,>=1.3->django-silver) (3.0.4) Collecting webencodings Using cached webencodings-0.5.1-py2.py3-none-any.whl (11 kB) Requirement already satisfied: pycparser in c:\python38\lib\site-packages (from cffi!=1.11.3,>=1.7->cryptography<2.4,>=1.9->django-silver) (2.20) Building wheels for collected … -
Error 'expected string or bytes-like object' in Django
I'm trying to create a new record in my Django model but I just can't. Here is the Sell class model: class Sell(models.Model): item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE) date = models.DateField(default=timezone.now) discount = models.DecimalField(max_digits=6, decimal_places=2) total_paid = models.DecimalField(max_digits=6, decimal_places=2) buyer = models.ForeignKey(User, related_name='sell', on_delete=models.CASCADE) Here is the code in my view.py: Sell.objects.create(item=item, date=timezone.now, discount=Decimal(0.00), total_paid=cart.get_total_price(), buyer=request.user, ) If I print all of this variables, the result is: print(item) 266 print(type(item)) <class 'dma.models.Buy'> print(timezone.now) <function datetime.date at 0x03D3F460> print(type(timezone.now)) <class 'function'> print(type(Decimal(0.00))) <class 'decimal.Decimal'> print(cart.get_total_price()) 68.00 print(type(cart.get_total_price())) <class 'decimal.Decimal'> print(request.user) Felipe print(type(request.user)) <class 'django.utils.functional.SimpleLazyObject'> Error: Exception Type: TypeError Exception Value: expected string or bytes-like object -
Django AttributeError: <Object> needs to have a hvalue for field "id" before this many-to-many relationship can be used
My issue: I'm trying to add some models to my database through the admin path on my django project, but this error keeps popping up when I try to create an instance of my model. The clean function exists to ensure that each Pokemon model can only have up to 2 types selected from a list of all possible types. My code: from django.db import models from django.core.validators import MinValueValidator as min, MaxValueValidator as max from django.core.exceptions import ValidationError class PokeType(models.Model): poke_type = models.CharField(max_length=15) def __str__(self): return self.poke_type #Current generation of games for gen_added field gen = 8 class Pokemon(models.Model): poke_name = models.CharField(max_length=30) poke_type = models.ManyToManyField(PokeType, blank=True, null=True) evolves_from = False evolves_into = False gen_added = models.PositiveIntegerField(validators=[min(1), max(gen)]) def clean(self): #Allow max of 2 poke_types to be selected if self.poke_type.count() > 2: raise ValidationError('A Pokemon has a maximum of two types.') class Meta: verbose_name_plural = 'Pokemon' abstract = True class CustomPokemon(Pokemon): name = models.CharField(max_length=30) level = models.PositiveIntegerField(blank=True, null=True) def __str__(self): return self.name What I (kind of) know: Based on what I've seen from other people asking this question, I need to save the instance of my model before I can use the many-to-many relationship in the clean function. Also, I … -
Dockerized Django Project on Heroku -- User Account App Gives HTTP 500 Error
I have just deployed a Dockerized Django project to a Heroku Hobby Dyno, and there seems to be some issues with users logging in and accessing the account portion of the website. The homepage app works perfectly, but that's about all that works. Even as a superuser, I can access the main screen of the admin page, but when I click on one of the model names, a 500 error code is thrown. The only model I can access is the default user model Django provides. This is also the case for any users trying to access accounts. I can get new users registered and added to the User model, but they are unable to reach any portion of the website that requires being logged in--not even their profile page. Here is my project directory: project-root >account #this is the app causing the issues >env #env directory >homescreen #this app works fine >media #user-upload directory >mementos -.dockerignore -.gitignore -db.sqlite3 -Dockerfile -manage.py -Pipfile -requirements.txt The Heroku logs are pretty vague. Here's what I get when a user tries to access their account: 2020-07-30T04:04:14.923403+00:00 heroku[router]: at=info method=GET path="/account/" host=**********.herokuapp.com request_id=c9cbe319-7ff0-4dc8-8105-0b16e10d74ae fwd="35.25.10.57" dyno=web.1 connect=0ms service=68ms status=500 bytes=413 protocol=http Same thing happens when I … -
Javascript function doesn't wait until the end of promises
I have got a function that invokes when a button is clicked, and I am trying to fetch data through API upon clicking. and below is the function that gets triggered onclick. I have to fetch data through API once and then based on a field from the fetched data, I need to fetch another data from another data table. so, I have designed my coding as below, and my console looks like this: And the console looks like this: All done []length: 0__proto__: Array(0) 1466 (customer_id logged during for loop) 1663 (customer_id logged during for loop) I thought based on the promise logic, all done should have been read in the end, am I missing anything here? so Ideally, Alldone console should have invoked at the end containing data fetched based on customer_ids 1466, 1663. I am not sure what I am missing, I am new to javascript as well as stack overflow, so detailed answer would be so much appreciated. function test(pmt_id, crm_supplier_id) { const url = 'http://127.0.0.1:8000/creditor-detail/'+pmt_id+'/supplier/'+crm_supplier_id+'/' let promises = []; const results = fetch(url) .then(resp => resp.json()) .then(function (item) { var list = item; for (var i in list) { promises.push(getCustomer(list[i].customer_id)); console.log(list[i].customer_id) } }) Promise.all(promises) .then((results) … -
How to solve 302 Issue in Django?
I have a form in django, which is working for rating. if a user will submit that form then it will save procuct_id and user_id in database, so that i can calculate the ratings which is given by users after login. But when i submit this form, it's showing 302 found. so i checked after HttpResponse and it's printing Hi, please check my code and let me know where i am mistaking. Here is my models.py file... class Comment(models.Model): STATUS=( ('New', 'New'), ('True', 'True'), ('False', 'False') ) product=models.ForeignKey(Product, on_delete=models.CASCADE) user=models.ForeignKey(User, on_delete=models.CASCADE) subject=models.CharField(max_length=250, blank=True) comment=models.CharField(max_length=50, blank=True) rate=models.IntegerField(default=1) ip=models.CharField(max_length=250, blank=True) status=models.CharField(max_length=10, choices=STATUS) created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) def __str__(self): return self.subject class CommentForm(ModelForm): class Meta: model=Comment fields=['subject', 'comment', 'rate'] here is my views.py file... def addcomment(request,id): url = request.META.get('HTTP_REFERER') #get last url #return HttpResponse(url) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): data = Comment() #create relation with model #data.name = form.cleaned_data['name'] #get form input data data.subject = form.cleaned_data['subject'] data.comment = form.cleaned_data['comment'] data.ip = request.META.get('REMOTE_ADDR') data.product_id=id current_user=request.user data.user_id=current_user.id data.save() #save data to table messages.success(request, "Your Review has been Send. Thank you for your interest") return HttpResponse("Hello") return HttpResponse("Hi") here is my urls.py file... urlpatterns = [ path('product/addcomment/<int:id>', views.addcomment, name='addcomment'), ] here is my product.html … -
Can't access self.request.user when overriding FilterSet.qs
I have written code for a filter that takes into account some fields of a given patient (name, age and id). The users of the website will be doctors, and I want only patients of the current logged in doctor to come up in the search. After reading the docs and trying to do so in many different ways, I have accomplished nothing. It seems the best method is to override the FilterSet.qs function and so I did, similarly to what is present in the documentation. However, when I try to access self.request.user it comes back as none, even though there is a user currently logged in. I am new to Django and still trying to figure things out. Any help is highly appreciated. I believe I have pasted in all that is relevant, but I am sorry in advance if something is missing. # filters.py import django_filters from .models import Patient, Teams from django import forms from django.contrib.auth.models import User class PatientFilter(django_filters.FilterSet): id = django_filters.NumberFilter(widget=forms.NumberInput(attrs={ 'min': '1'})) age = django_filters.NumberFilter(widget=forms.NumberInput(attrs={ 'min': '0'})) class Meta: model = Patient fields = { 'first_name' : ['icontains'], 'age' : ['exact'], 'id' : ['exact'] } @property def qs(self): parent = super().qs author = getattr(self.request, … -
how to get the default user details (username, email, first_name, last_name) along with token (in created login API) via Django Rest framework?
I am trying to get the user details (username, email, first_name, last_name) along with token via API, but just getting token, I am a beginner in Django REST framework, Please help me regarding this, here is my code. settings.py INSTALLED_APPS = [ ... 'rest_framework', 'knox', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'knox.auth.TokenAuthentication', ], } views.py from django.contrib.auth import login from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user,)[enter image description here][1] return super(LoginAPI, self).post(request, format=None) urls.py from knox import views as knox_views from .views import LoginAPI from django.urls import path urlpatterns = [ path('api/login/', LoginAPI.as_view(), name='login'), ] http://127.0.0.1:8000/api/login/ { "username": "admin123", "password": "Password@123" } and response is { "expiry": "2020-07-30T13:34:14.041631Z", "token": "f4767171f1017d2bd772fd3bae43489659e8e63649361845bedc5ebabff09c15" } -
Select widget value appearing in POST but not cleaned_data
One of my forms has a Select widget that is not working properly. Using the VS Code debugger, I found that the data is showing up in POST but not cleaned_data. Here is my code: views.py def index(request): if request.method == 'GET': return render(request, 'quotes/index.html', { 'form': QuoteRequestForm(), }) elif request.method == 'POST': form = QuoteRequestForm(request.POST) g_recaptcha_response = request.POST.get('g-recaptcha-response') ip = get_client_ip(request) api_response = verify(g_recaptcha_response, ip) api_response_content = json.loads(str(api_response.content, encoding='utf-8')) if not api_response_content['success'] or api_response.status_code != 200: messages.error(request, 'There was an error submitting the form.') messages.error(request, 'Please prove you are human by clicking the last checkbox and possibly completing a security challenge.') return render(request, 'quotes/index.html', {'form': form}) if form.is_valid(): quote_request = form.save() messages.success(request, 'Thank you for submitting a quote request. We will contact you via phone or email within 1-3 business days.') return redirect('quotes:index') messages.error(request, 'There was an error submitting the form.') return render(request, 'quotes/index.html', { 'form': form, }) return HttpResponseBadRequest() forms.py class QuoteRequestForm(forms.ModelForm): title = forms.MultipleChoiceField( label='', choices=Contact.title_choices, widget=forms.Select( attrs={ 'class': 'form-control', 'data-label': 'Title', }, ), ) first_name = forms.CharField( label='', max_length=35, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'First Name', }), ) last_name = forms.CharField( label='', max_length=70, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Last Name', }), ) family_first = forms.BooleanField( required=False, label='Family Name … -
Render many to many relationship in django
I have two models Order and Supplement. The order model is connected to the Supplement model with many to many relationship.In my template, I want to display supplements selected in the Order model in an HTML page. In an order object I have selected two kinds of supplements , but in my HTML page when I try to render them I'm getting " accounts.Supplement.None" as the output. class Order(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=100) status = models.CharField(max_length = 100) supplement = models.ManyToManyField('Supplement') class Supplement(models.Model): stockId = models.AutoField(primary_key=True) brand_name = models.CharField(max_length=100) supplement_name = models.CharField(max_length=100) supplement_type = models.CharField(max_length=100) quantity = models.IntegerField(default='0', blank=True, null=True) def __str__(self): return self.supplement_name HTML page {% for Order in order %} <h1>{{supplement.supplement}}</h1> {% endfor %} -
Remove the last char for the last item of a django template loop
I have this django template: <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [ {% for q_a_ins in q_a_set %} { "@type": "Question", "name": "{{ q_a_ins.question }}", "acceptedAnswer": { "@type": "Answer", "text": "{{ q_a_ins.answer }}" } }, {% endfor %} ] } </script> The result is: <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [ { "@type": "Question", "name": "q1", "acceptedAnswer": { "@type": "Answer", "text": "a1" } }, { "@type": "Question", "name": "q2", "acceptedAnswer": { "@type": "Answer", "text": "a2" } }, ] } </script> The result is exactly what I want except one tiny little character!! The last comma in the list causing me trouble and I am getthing error in structured data testing tool. How can I remove comma from the last }, ] ? The result I need is this : <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [ { "@type": "Question", "name": "q1", "acceptedAnswer": { "@type": "Answer", "text": "a1" } }, { "@type": "Question", "name": "q2", "acceptedAnswer": { "@type": "Answer", "text": "a2" } } ] } </script> How can I remove that comma? -
What are the Challenges in Migrating Core-PHP without OOP to a framework? How we'll manage DB for both apps?
What are the Challenges in Migrating Core-PHP without OOP to a framework? DB also needs to be optimized. I'm planning it features by feature. Should I use same DB for both or create a new optimized DB? Also If the Old app needs new data which is entered by new app (dependency), How will manage it? Switching to Laravel or Django which is better? -
Linking Different List Views of 2 models together who share the same User
I am trying to add a Post to a list view, the class DesignerPostListView(ListView) has already an Item context. In my project, a user can add a post and add an item each is a different app with different models. So In my DesignerPostListView(ListView), I have my items related to a specific user looped. What I am trying to do is check if this item.user has a post existing related to the user and if it does exist a button show appears in the page linking to another page with these posts related to the very same user. There is another list view called class UserPostListView(ListView): with the same idea looping posts filtered to a specific user. In order words if there are no posts related to the user the button should not appear but if there is 1 or more the button should appear. I have tried to add a condition to the template but it is not working correctly and I think there might be another easier way to do it through the views. here is the item models.py class Item(models.Model): designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) here is the designer list views.py class DesignerPostListView(ListView): model … -
how to send image base64 to django server from flutter
Can anyone help me in this? I am sending image from flutter to django (python) server . here i am successfully take the image from mobile camera/gallery and successfully converted(encoded) the image to base64. flutter code Future classifyImage() async{ if(imageFile==null) return; String base64Image = base64Encode(imageFile.readAsBytesSync()); String fileName = imageFile.path.split("/").last; http.post(phpEndPoint, body: { "image" : base64Image, //"name" : fileName, }).then((res) { print(res.body); }).catchError((err) { print(err); //print(base64Image); //print(fileName); }); } here is the converted string in flutter by base64 /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQICAQEBAQMCAgICAwMEBAMDAwMEBAYFBAQFBAMDBQcFBQYGBgYGBAUHBwcGBwYGBgb/2wBDAQEBAQEBAQMCAgMGBAMEBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgb/wAARCAPXAy0DASIAAhEBAxEB/8QAHwAAAgICAwEBAQAAAAAAAAAABgcEBQMIAAIJAQoL/8QAaBAAAQMDAwIEAwQFBwQJEAITAQIDEQAEIQUSMQZBEyJRYQcycRRCgZEICSNSoRUzYnKxtMEWN3bRCiRDZHSChJLwFyY2U1ZjZWZzhZSipbO14Sc0NUR1g5WkGEWTJSg4RkdXWHej8f/EABcBAQEBAQAAAAAAAAAAAAAAAAACAQP/xAAaEQEAAwEBAQAAAAAAAAAAAAAAAgMyATER/9oADAMBAAIRAxEAPwDzr/2W4wXv0yf0cSCRH6MDY/8Abuo1+SpOmqUoJEyTzX66/wDZZbC3v0x/0dClBUB+jG3JA/8ADmo1+U6ysFF9uWiM+lXZvqY5DbfTDy07hvIA4FW+n9E3Nw4ghLme4px6ZpqC2NyEkd5FMbp/SrfcgKQ2M+lQomrHogtIAcSQoeoq7Z6SS2UmAY4pwa1Zhq6CGmgRnKRUZixddKR4RAjPloAS20YNH5AcZxV41aBsD9mD6YpgWnTy3YBQoe8VeNdIKWAYI9hQK9Ol/avOGgkTkRU9jQCCP2ZwKbNv019nSEFAk8kirVnQgIGz+FAqWNBOPJ/CrRvQDM7DEelNpnQhjyfhFWzegDEJ+hIoF7pekFpopKYxgRVujTck7e1HrOjBsQUYqa1pSceWgB2dLKgPKffFWKNJMfIaOmdMAgBP8KsEaanAKe1AGWmn7EREGPSpYssj/VRWLMIJAQRHEiu6bOe0fhQDKbPvH8KzC0BE8fhRKizjEc94rKLIA8A+o20 but the problem is the string which is received in django server is different from the string which is converted in flutter. here is the string which is received in django server python code @csrf_exempt def android_predict(request): try : print('Request method is : ' + request.method) if request.method == 'POST' : print('method is POST') print('Body is : ' + str(request.body)) decoded = request.body.decode("UTF-8") print(decoded) name_image = decoded.split('&')[1].split('=')[1] print('name is : ' + name_image) b64_image = decoded.split('&')[0].split('=')[1] print('Base64 image is : ' + b64_image) missing_padding = len(b64_image)%4 print('Length is : ' + str(len(b64_image))) if missing_padding : b64_image += '='*(4-missing_padding) print('Modified Base64 image is : ' + b64_image) print('New length is : ' + str(len(b64_image))) image = PIL.Image.open(io.BytesIO(base64.b64decode(b64_image))) target_image = image.resize((500,500),PIL.Image.ANTIALIAS) print(type(target_image)) image_array = …