Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to perform inner join wirth on statment on django 1.11
how to make statement of join on in django 1.11, i want to create this statement : select name from table_1 as t1 join table_2 as t2 on t2.product_id = t1.id and t2.section_num = 2; i tried t1 = t1.select_related('t2') but where can i add the on statement ? -
Django taking another users stuff
I am adding sales order to my project and only authenticated users can create sales order with their stuffs like contacts customer, items etc but in the UI it is showing me another users options as well. For example I am going to create sales order and I have 1 customer contact and 1 item. in templates instead of showing 1 customer contact and 1 item, it is showing a number of stuffs of another users too. models.py here it is class SalesOrder(TimeModel): customer = models.ForeignKey(ClientContact, on_delete=models.CASCADE) so_date = models.DateField(default=datetime.date.today) so_items = models.ForeignKey(Item, on_delete=models.CASCADE) author = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE) class Meta: unique_together = ('so_items', 'author') I have added unique_together but it does not help. for views i am using CBV views.py class Sales(LoginRequiredMixin, CreateView): model = SalesOrder template_name = 'sales/sales_order.html' fields = ['customer', 'so_date', 'so_items',] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): so_order = self.get_object() if self.request.user == so_order.author: return True return False how can i solve this issue? any help? -
How to return variable from class based functions on click anchor tag?
I am creating an web application. When i click on anchor tag, it only return variables in the URL, I am not able to print the variables and data from MySQL database declared inside the class based function. Which functions do I need to call to return variables from class based functions to view page on click anchor tag? This is for MySQL Server. I have tried to fetch the data from MySQL database. <a href="{%url 'core:test_url' 'test_data' %}">Test header</a> path('test/<slug:title>', test_function.as_view(),name='test_name')` class deLiveTraining(View): template_name = 'appdev/appdevelopment.html' def post(self,request,*args,**kwargs): scrollTo = kwargs['title'] #tutorialDetails = tutorialInfo.objects.all() context = { 'scrollTo':scrollTo,#test_data in the URL 'tutorialDetails':tutorialDetails # database data } return render(request,self.template_name,context) I expected to return the output of data from MySQL database to be return into the view page appdevelopment.html -
how to iterate over a queryset in django as i get 'int' object is not iterable
I wan to get the object from a queryset accounts = group. get_external_accounts(include_sub_groups=True).values_list('id') try: account: StripeExternalAccount = accounts.get(account_id) except StripeExternalAccount.DoesNotExist: return Response(status=status.HTTP_400_BAD_REQUEST) I have tried this and it works fine but i want to do it through try except account: StripeExternalAccount = None for acc in accounts: if acc.id == int(account_id): account = acc break if not account: return Response(status=status.HTTP_400_BAD_REQUEST) -
outputting python scipt result into html template
i am creating web app where user will get train pnr status by entering his pnr number without reloading the page. i mean when user enter his pnr number his status will show below without reloading page. so i had setup everythin with django and have one html template with form as you can see this form getting the pnr and then python script running and output the json result now how can i get this result out on my index.html template without reloading the page. <header class="header-area overlay full-height relative v-center" id="home-page"> <div class="absolute anlge-bg"></div> <div class="container"> <div class="row v-center"> <div class="col-xs-12 col-md-7 header-text"> <h2>It’s all about Promoting your Business</h2> <form method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> </div> </div> </div> </div> </header> view.py: from django.shortcuts import redirect,render from django.http import HttpResponseRedirect from .forms import PnrForm import requests, json def index(request): if request.method == 'POST': form = PnrForm(request.POST) if form.is_valid(): pnr_numbers = form.cleaned_data['pnr_number'] api_key = "apikey" base_url = "https://api.railwayapi.com/v2/pnr-status/pnr/" # Enter valid pnr_number #pnr_number = "pnrnumber" # Stores complete url address complete_url = base_url + pnr_number + "/apikey/" + api_key + "/" # get method of requests module # return response object response_ob = requests.get(complete_url) … -
How to edit additional entities in TabularInline in django-admin
Sorry for my english. There is an admin page for entity cars. On the same page, you can add and edit the entity Sizes of machines. Here’s what it looks like in the admin.py file: class CarVolumeInline(admin.TabularInline): model = CarVolume template = "admin/vans/volumesTabularTemplate.html" min_num = 0 max_num = 20 extra = 1 def get_queryset(self, request): qs = super().get_queryset(request) qs.hello = "Hellooo" return qs class CarAdmin(TranslationAdmin): inlines = [CarVolumeInline] # таблица с размерами автомобиля list_display = ('full_title', 'seo_set', 'slug') ... The customer asked for each size to add a multiplying factor, unique not only for each size, but also for a separate entity - Material thickness. I created a separate template for TabularInline to display the header and forms for the coefficients, but I don’t have any idea how to save it in the database. Actually this is the question - how to save, edit and output already existing values in such a scheme. It should look like this: https://ibb.co/n1mqcY6 -
Why values are not storing in the table when i have clicked Submit button?
I have created a form for getting the value and placing it in the table. But whenever I click on Submit button, it doesn't store or give any error.It is simply staying in that page itself. Model.py class Employee(models.Model): ename=models.CharField(max_length=120) eaddress=models.CharField(max_length=120) eemail=models.CharField(max_length=120) ephone=models.CharField(max_length=120) emobile=models.CharField(max_length=120) eid=models.CharField(max_length=120) egender=models.CharField(max_length=120) ehire=models.DateTimeField() edob=models.DateTimeField() class Meta: db_table="employee" views.py def employee(request): emp=Employee.objects.all() return render(request,'employee.html',{'emp':emp}) def addemployee(request): if request.method == 'POST': emp = EmployeeForm(request.POST) if emp.is_valid(): try: form.save() return redirect(employee) except: pass else: emp = EmployeeForm() return render(request,'addemployee.html',{'emp':emp}) addemployee.html: <form method="POST" action="add_employee"> {% csrf_token %} {{emp.ename}} {{emp.eemail}} {{emp.emobile}} <button type="submit">Submit</button> </form> -
why every coder on youtube is using default db in django?
i want to know why every tutorial uses dbsqlite3 as database for tutoring ihave tried xampp database but with it tutorial codes don't work(source:https://www.youtube.com/watch?v=9Wbfk16jEOk) -
Filter - Checkbox enable text input (parameter)
First of all I would list all my necessary files here: footer.html: <br> <div>Filter: </div> <form> {% csrf_token %} <fieldset> <legend>Filtar - Thing that is being chosen</legend> {{ form.as_p }} <input type="submit" value="Submit"> </fieldset> </form> <br> <div>Copyright by </div> forms.py: class ChoiceForm(forms.Form): filter = forms.MultipleChoiceField(choices=(('Choice 1', 'Choice 1'), ('Choice 2', 'Choice 2')), widget=forms.CheckboxSelectMultiple) views.py: def filtar(request): form = ChoiceForm(request.GET or None) data = Clanak.objects.all() if form.is_valid(): if 'Choice 1' in form.cleaned_data['filter']: data = data.filter(naslov='NAME') if 'Choice 2' in form.cleaned_data['filter']: data = data.filter(datumObjave__year=2019) return render(request, 'filtar.html', {'data': data, 'form': form}) urls.py: urlpatterns = [ path('filtar/',views.filtar, name='filtar'), ] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) Screenshot: Now I have two filters (Choice 1, and Choice 2). I can pick one or both at the same time. One filter is on year of date (datumObjave) and another is on name (naslov). My problem is that those filters are currently on fixed values. I don't know how can I make that when checkbox is enabled it show me textbox where I enter text which will be parameter for filter. -
I want to redirect to url from a class method
I have Source_page and Target_Page apps. In Source_page app View, I am using forms to select Database, Schema and Table drop-downs and each of one appears after one selected. There is class TableStructure that need to be called after a table selected to do some processes. After completion of these processes, I want to redirect the URL "/targetSource/". can anybody help on it? Here are the code files Views.py class DBForm(forms.Form): database = forms.ChoiceField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['database'].choices = self._get_databases() def _get_databases(self): self.pgObj = Postgres(server="localhost",user="postgres",password="*****",port=5433) dbList = self.pgObj.connect() dbChoiceList = getChoiceList(dbList) return dbChoiceList class SchemaForm(DBForm): schema = forms.ChoiceField() def __init__(self, database, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['database'].initial = database # self.fields['database'].widget.attrs['disabled'] = True self.fields['schema'].choices = self._get_schemas(database) def _get_schemas(self, database): # TODO Do NOT forget to escape "database" here to prevent injections schemaList= self.pgObj.schemaList(database) schema = getChoiceList(schemaList) return schema class TableForm(SchemaForm): table = forms.ChoiceField() def __init__(self, database, schema, *args, **kwargs): super().__init__(database, *args, **kwargs) self.fields['schema'].initial = schema # self.fields['schema'].widget.attrs['disabled'] = True self.fields['table'].choices = self._get_tables(database, schema) def _get_tables(self, database, schema): # TODO Do NOT forget to escape "database" here to prevent injections tableList = self.pgObj.tableList(schema) table = getChoiceList(tableList) return table class TableStructure(TableForm): def __init__(self, database, schema, table, *args, **kwargs): super().__init__(database, schema, … -
Is there any way to set default value in CharField of django model?
How to set default value in: I want to send default value Individual everytime in Individua_type class Dispatcher(models.Model): individual_type = models.CharField(max_length=255, default=Individual) -
Django Template String Concatenation based on number of non-empty variables
I have two string variables that I want to display on a Django template. If variable a is empty, do not display it. Similar with b. But if a and b are both non-empty, then concatenate the two strings with a ' & '. Here's the logic in Python. res = '' if a != '': res = a if b != '': if res == '': res = b else: res = res + ' & ' + b print(res) How would I write this logic into a Django template? -
Using the JSON response from 3rd party api with geodjango
I am try to create a way to narrow down posts on a django app by location & radius. The way I am trying to do this is: Use 3rd party (OpenCage) API to convert location to lat / lng Gather the JSON response, filter for the most correct one (first response in US) Use the response lat & lng to filter listings via GIS What I have done is successfully connect to the API, and get a lat & lng back, however I am having to filter the response in my templates rather than in my models. I have also found the following which appears to be the solution needed for narrowing results in a radius: from django.contrib.gis.geos import Point from django.contrib.gis.measure import Distance lat = 52.5 lng = 1.0 radius = 10 point = Point(lng, lat) Place.objects.filter(location__distance_lt=(point, Distance(km=radius))) What I need to solve, and am hoping for your help with is how do I filter the api responses and only get what I need from them (components country, geometry lat, geometry lng) gather the lat & lng for use in the above code? views.py from posts import services def search(request): queryset_list = posts.objects.order_by('id') if 'location' in request.GET: q … -
Django get a list of parents each populated with their own children
I have a pair of parent/children relation models like: class Post(models.Model): title = models.TextField(null=True) content = models.TextField(null=True) author = models.TextField(null=True) created_time = models.DateTimeField(null=True) def __str__(self): return self.title class Comment(models.Model): content = models.TextField(null=True) created_time = models.DateTimeField(null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.content and the serializers are like: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' and finally views: class PostView(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer class CommentView(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer Now I want to created an API that returns a list of Posts, in which each Post will contain two additional fields, one be all_comments, and the other will be latest_comment. I understand this could be easily done in SQL using JOINs. I am new to Django. I wonder if there's any easy way to do it in Django. Thanks. -
Django Template Exception TemplateDoesNotExist
I am trying to make a home page for a project in a Python Coding Book. I am at a loss as to why I keep getting the error below. I have the index file in the proper location, however, the exception I keep receiving does that template does not exist. This is the error that I keep receiving. Traceback (most recent call last): File "C:\Users\foste\Documents\Programming\python_work\Pojects\Ch. 18 Getting Started with Django\meal_planner\meal_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\foste\Documents\Programming\python_work\Pojects\Ch. 18 Getting Started with Django\meal_planner\meal_env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\foste\Documents\Programming\python_work\Pojects\Ch. 18 Getting Started with Django\meal_planner\meal_env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\foste\Documents\Programming\python_work\Pojects\Ch. 18 Getting Started with Django\meal_planner\planner\views.py", line 5, in index return render(request, 'planner/index.html') File "C:\Users\foste\Documents\Programming\python_work\Pojects\Ch. 18 Getting Started with Django\meal_planner\meal_env\lib\site-packages\django\shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\foste\Documents\Programming\python_work\Pojects\Ch. 18 Getting Started with Django\meal_planner\meal_env\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\foste\Documents\Programming\python_work\Pojects\Ch. 18 Getting Started with Django\meal_planner\meal_env\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: planner/index.html [22/May/2019 22:01:46] "GET / HTTP/1.1" 500 79939 -
django.db.utils.ProgrammingError: operator does not exist: character varying >= integer
Traceback (most recent call last): File "F:\Evns\mxonline\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: operator does not exist: character varying >= integer HINT: No operator matches the given name and argument types. You might need to add explicit type casts. how can i change this i don't find the errors -
How to display a ModelChoiceField's Selected Value in Django
I need to display just the selected value from a forms.ModelChoiceField on a view page. How would I do that? I've looked at many different forums and couldn't get a clear answer on what I should do in my case. I am new at Python. form: class Manufacturer1Form(ReadOnlyFormMixin, ModelForm): manufacturer = forms.ModelChoiceField(queryset=Vendor.objects.filter(vendor_type='manufacturer').order_by('name')) class Meta: model = Manufacturer1Relationship exclude = ('part',) model: class Manufacturer1Relationship(models.Model): part = models.ForeignKey(Part, on_delete=models.CASCADE) manufacturer = models.ForeignKey(Vendor, on_delete=models.CASCADE, limit_choices_to={'vendor_type': 'manufacturer'},) partNumber = models.CharField(max_length=40, blank=True) class Meta: permissions = ( ('modify_admin_site', 'Can modify, add, view, or delete manufacturer relationships'), ) view: def PartView(request, type_id, id): partType = Type.objects.get(id=type_id) instance = get_object_or_404(Part, id=id) selection = None if request.method == 'POST': form = ViewPartForm(type_id, request.POST, request.FILES, instance=instance) manu1_formset = ManufacturerFormSet(request.POST, instance=instance) location1_formset = LocationFormSet(request.POST, instance=instance) if form.is_valid(): selection = form.cleaned_data['active_feed'] part = form.save(commit=False) part.partType_id = type_id if manu1_formset.is_valid() and location1_formset.is_valid(): part.save() manu1_formset.save() location1_formset.save() url = reverse('list_parts', args=[partType.pk]) return HttpResponseRedirect(url) else: form = ViewPartForm(type_id=type_id, instance=instance) manu1_formset = ManufacturerFormSet(instance=instance) location1_formset = LocationFormSet(instance=instance) return render(request, 'part_view.html', {'view_part_form': form, 'location_formset': location1_formset, 'manu_formset': manu1_formset, 'selection': selection, 'partType': partType, 'part': instance}) -
Favicon not found in Django in production
The favicon.ico is not found, 404 error, when a Django app is running in production. I set the icon in app/favicon.ico, so I put the icon in mysite/static/app/favicon.ico. In html, The icon is in myproject/static/app/favicon.ico as in the static folder in production. -
How can I save Json data in database
I using django, and i can save data in database but how can i save my javascript variable to django database? i use django, html, sqlite models.py from django.db import models from jsonfield import JSONField class jobPlan (models.Model) : name = models.CharField(max_length=100, blank=True, null=True) position = models.CharField(max_length=100, blank=True, null=True) graph = JSONField(default={}, dump_kwargs={'ensure_ascii': False}) def __str__(self): return self.name forms.py from django import forms from jobPlan.models import * class jobPlanForm(forms.ModelForm): class Meta: model = jobPlan fields = ('graph',) urls.py from django.conf.urls import url from django.conf.urls.static import static from django.conf import settings from jobPlan.views import * urlpatterns = [ #url('$', ModelingView_model.as_view()), url('', jobPlan_view.as_view()), ] views.py from django.views.generic.edit import FormView from jobPlan.forms import * from django.shortcuts import render, redirect class jobPlan_view(FormView): form_class =jobPlanForm model = jobPlan fields = '__all__' template_name = "jobPlan.html" def post(self, request, *args, **kwargs): form = jobPlanForm(request.POST, request.FILES, auto_id=False) if form.is_valid(): form.save() return redirect(self.success_url) else: return render(request, self.template_name, {'form': form}) jobPlan.html <script> temp=JSON.stringify(diagrambuilder.toJSON()) </script> When any event occurs, I want to save the temp variable in the Django database. -
TypeError: _add_items() got an unexpected keyword argument 'through_defaults'
I have just added the Photologue app to a new Django project. The installation appears to have worked except for.... ...when I try to add an initial Gallery get the following error TypeError: _add_items() got an unexpected keyword argument 'through_defaults All packages where installed using pip3 on MacOS 10.14 as per the photologue read-the-doc. Internal Server Error: /admin/photologue/gallery/add/ Traceback (most recent call last): File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/contrib/admin/options.py", line 606, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 223, in inner return view(request, *args, **kwargs) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1634, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/utils/decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1522, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1562, in _changeform_view self.save_related(request, form, formsets, not add) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/photologue/admin.py", line 57, in save_related super(GalleryAdmin, self).save_related(request, form, *args, **kwargs) File "/Users/myuser/Envs/env1/lib/python3.7/site-packages/django/contrib/admin/options.py", … -
Installation of mysqlclient fails on shared hosting server using pip
I want to connect the Django app to mysql database. The recommended solution is to install mysqlclient through pip. But the installation fails through the provided interface of the shared hosting service. I tried to install over ssh, and the error log is quite bug and there was a error about permissions. There is no access to sudo commands in the shared hosting service. -
Cannot make get/post requests to django server on elastic beanstalk
I want to make http requests to my django server which is hosted on elastic beanstalk. My static react site is hosted on s3 buckets. I made it so ALLOWED_HOSTS = ['*'] just to see what would happen, but this doesn't work either. I am able to log in perfectly fine with this url: http://mysite-env.randomletters.us-east-1.elasticbeanstalk.com/rest-auth/login/ but when I want to make get/post requests, it doesn't work. I am storing my token in local storage (bad I know but just for sake of testing/laziness, I am doing this just so I can make things work). Here is a sample axios get request: const config = { headers: { 'Authorization': 'Token ' + localStorage.getItem('token') } } const url = 'http://mysite-env.randomletters.us-east-1.elasticbeanstalk.com/api/inventory/ console.log("url",url) console.log("token",config) axios.get(url,config) .then(res=>{ this.setState({ items: res.data }) }) The console does indeed print out the token: headers: Authorization: "Token c1b7661c6ba3252fb3aea1ef9c79aa3412fee7cc" so I'm not sure what the error is. When I run it locally, and make api calls to 127.0.0.1:8000 with the same code, but just replace the url, it works fine. I am not using any reverse proxies or what not so that may be one of the causes? Here is the error from error logs: [Thu May 23 01:05:35.253810 2019] … -
Problema con pylatex y django
Tengo el problema de que estoy queriendo generar un documento pdf desde mi proyecto Django mediante Pylatex pero el problema que tengo es que al momento de activar la funcion que crea el documento pdf me muestra error Lo que pasa es que ya cuento con las 2 dependencias intaladas de latexmk y pdf latex pero no logro que compile el archivo creado ".tex" lo que me muestra el error de compilacion y ya no avanza mas y no se crea nada. doc = Document('somepdffile') doc.append("some text") doc.generate_pdf(compiler="pdflatex") print("Hola crayola") pylatex.errors.CompilerError: No LaTex compiler was found Either specify a LaTex compiler or make sure you have latexmk or pdfLaTex installed. -
how to assign Django-filter results to a verbose_name_plural variable?
how to assign django-filter results to a verbose_name_plural variable # in django? studied constructing dynamic query using user input in django and #accessing class variable in python -------------------------------------------------- from inventory.filters import InventoryFilter inventory = InventoriFilter() obj = { "inventory":[inventory.inventori], } inventoris = Inventory.objects.filter(*obj['inventory']) context={ 'inventoris': inventoris, } from inventory.filters file class InventoriFilter(django_filters.FilterSet): inventori = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Inventory fields = ['id', 'inventori', 'price', 'quantity',] from models.py class Inventori(models.Model): inventori = models.CharField(max_length=50) InventoriFilter has no attribute "inventori" -
Why does the original django object get changed when cloning?
I want to clone a django model/object. Here is my code with some debugging statements (method is inside my Item class) def duplicate_item(self): print("original",self.id) copy = self copy.id = uuid.uuid4() print("copy",copy.id) copy.save() print("What happened",self.id) This was the output: original 6a5a8d54-5b45-47fd-abf3-4357aa89dd0c copy 5b6bfb5f-36b2-4a74-968e-c1f007df9056 what happened 5b6bfb5f-36b2-4a74-968e-c1f007df9056 Why does this happen? I don't know enough about python shallow/deep copy logic so that probably has to do with it. Thank you