Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Recommended way to show balance in bank account in django template
In Django I have a model where I log transaction (date, amount, description fields). In my view I would like to show a running balance, something like so: Date | Description | Amount | Balance ---------------------------------------------- 2019-01-01 | Item 1 | $100 | $100 2019-01-02 | Item 2 | -$10 | $90 2019-01-03 | Item 3 | $200 | $290 2019-01-04 | Item 4 | $10 | $300 Now, the problem is that BALANCE should of course be calculated by summing the previous balance and the current transaction. To me, it seems to make most sense to do this calculation inside the view. I wouldn't know any other sensible way to put it anywhere else. Is this correct? If so, what is the best way of doing this? If not, what is the right way of handling this? class Transaction(models.Model): date = models.DateField() amount = models.DecimalField(max_digits=15, decimal_places=2) account = models.ForeignKey(BankAccount, on_delete=models.CASCADE) description = models.TextField(null=True, blank=True) In my view: transactions = Transaction.objects.all().order_by("date") -
Django: storing currently logged in user in database on form submission
What I am trying to do is on submission of a form store the currently authenticated username in an object so that I can write code in my template that will check the currently authenticated user against the value stored in the database and only present certain options if the logged in user matches the user value stored in the database. I would also like to be able to create an object without a user logged in and check an object instance within the database for an empty value and present options to an unauthenticated user. I am using from django.contrib.auth.models import User for authentication and it is working fine, I have all other aspects of the code working. I just can't seem to find a way to extract the value from auth.models and store it. I've tried all of the different methods I could find on stack overflow for extracting the value within the .view and storing it, but none have worked. This may have to do with the specifics of my code. Here is the model: class Job(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField() requirements = models.TextField(blank=True, default="") location = models.CharField(max_length=80) type = models.CharField(choices=JOB_TYPE, … -
Card Layout Bootstrap overlaps my other card items | Django, Bootstrap
I've been using Django to build an E-Commmerce WebApp. I've implemented the Card Layout from Bootstrap. The issue is that in some cases my Card items are overlapping each other. Not only that, but my images and the text (item description) are also not properly aligned inside the card. Can anybody tell me what's wrong in my code and suggest improvements? I've pushed my entire project to GitHub. Click Here. Any kind of help is hugely appreciated! -
Django + GeoDjango and Postrgresql (postGis extension): Wrong distance returned from the database
So we're having a seemingly straight forward problem with Django, GeoDjango and Postgis. There's a lot of mention online that you need to include the SRID both on the point you're trying to query and on the database field. The problem is we do have the SRID on the database field and yet the distance returned is incorrect. Normally I wouldn't care so much and just do the calculation in python for the returned rows, but in this case we need to filter on distance and without it being accurate I'm not comfortable moving forward. Model: class LocationStore(BaseLocation, LocationStoreFunctions): street = models.CharField(max_length=64) extras = models.CharField(max_length=64, blank=True, null=True) town = models.CharField(max_length=64) zip_postal = models.CharField(max_length=32) region = models.ForeignKey(Region) country = models.ForeignKey(Country) coordinates = PointField(srid=4326, db_index=True) timezone = TimeZoneField(default='US/Eastern', blank=True) phone_number = models.CharField(max_length=32) is_closed = models.BooleanField(default=False) features = MultiSelectField(choices=LOCATION_FEATURE_CHOICES, default=[]) Query Set: locations = LocationStore.objects.filter(coordinates__distance_lte=(self.client_point, D(m=distance))).annotate(distance=Distance('coordinates', self.client_point, sphereoid=True)).order_by('distance') Resulting Query: SELECT "retailers_baselocation"."id", "retailers_baselocation"."polymorphic_ctype_id", "retailers_baselocation"."retailer_id", "retailers_baselocation"."identifier", "retailers_baselocation"."name", "retailers_baselocation"."date_created", "retailers_baselocation"."date_updated", "retailers_baselocation"."rating", "retailers_locationstore"."baselocation_ptr_id", "retailers_locationstore"."street", "retailers_locationstore"."extras", "retailers_locationstore"."town", "retailers_locationstore"."zip_postal", "retailers_locationstore"."region_id", "retailers_locationstore"."country_id", "retailers_locationstore"."coordinates", "retailers_locationstore"."timezone", "retailers_locationstore"."phone_number", "retailers_locationstore"."is_closed", "retailers_locationstore"."features", ST_DistanceSphere("retailers_locationstore"."coordinates", ST_GeomFromEWKB('\001\001\000\000 \346\020\000\000s\242]\205\224\037F@\353\016s\223\342!S\300'::bytea)) AS "distance" FROM "retailers_locationstore" INNER JOIN "retailers_baselocation" ON ("retailers_locationstore"."baselocation_ptr_id" = "retailers_baselocation"."id") WHERE ST_DistanceSphere("retailers_locationstore"."coordinates", ST_GeomFromEWKB('\001\001\000\000 \346\020\000\000s\242]\205\224\037F@\353\016s\223\342!S\300'::bytea)) <= 10000.0 ORDER BY "distance" ASC; Resulting Results: **NOTICE: Coordinate values were coerced into … -
Django select2, show subcategories when parent category name searched
I used django-select2 to show parent categories and sub categories. When I search the name of parent category using 'Select2MultipleWidget' (Pacific Time Zone, for example), it does not show its sub categories. Is it possible to show belonging sub categories when parent categories are searched? I was reading select2 documentation but I couldn't find relevant options. #models.py class Category(models.Model): name = models.CharField(max_length=200) class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=180) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user") title = models.CharField(max_length=200) category = models.ManyToManyField(SubCategory) desc = models.TextField() #forms.py class PostForm(forms.ModelForm): def categories_as_choices(): categories = [] for category in Category.objects.all(): new_category = [] sub_categories = [] for sub_category in category.subcategory_set.all(): sub_categories.append([sub_category.id, sub_category.name]) new_category = [category.name, sub_categories] categories.append(new_category) return categories category = forms.ChoiceField( choices=categories_as_choices(), widget = Select2MultipleWidget( attrs={'class': 'form-control col-4'} ), ) class Meta: model = Post fields = ['title', 'desc', 'category'] I tried to use select2's example of timezone and state name (Pacific Time Zone as a parent category with California as a sub category). When I type 'Pacific Time Zone', it won't show 'California', sub category. -
Python Django getting 3 inputs instead of one as an array on condition
Trying to build a form in django as a newcomer, What I am trying to achieve is to build a form where the first input is an option from a list returned by a script, have a checkbox for whether the second input is a list of 3 numbers when the value is false or something from the choice list other than first input when the value is true what I tried was from . import script from django import forms class PostForm(forms.ModelForm): players = script.script() p1 = forms.ChoiceField(choices=enumerate(players)) choice = forms.BooleanField(label=choice,initial=False) p2 = forms.ChoiceField(choices=enumerate(players)) if choice else ... what i cant figure out is a method to take a 3 valued list as a form or if the above is a correct way to do it. My ultimate goal is to use the form data to fire script.run(p1,p2,choice) and not store the data. -
Problem with running my django vagrant project on another machine
I bought new laptop and wanted to run my desktop project on my new machine, I ran "git clone" on my project: https://github.com/MateuszKijewski/to-do-api and then once it cloned, I ran "vagrant up" and "vagrant ssh" # -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. # Every Vagrant development environment requires a box. You can search for # boxes at https://vagrantcloud.com/search. config.vm.box = "ubuntu/bionic64" config.vm.box_version = "~> 20190314.0.0" config.vm.network "forwarded_port", guest: 8000, host: 8000 config.vm.provision "shell", inline: <<-SHELL systemctl disable apt-daily.service systemctl disable apt-daily.timer sudo apt-get update sudo apt-get install -y python3-venv zip touch /home/vagrant/.bash_aliases if ! grep -q PYTHON_ALIAS_ADDED /home/vagrant/.bash_aliases; then echo "# PYTHON_ALIAS_ADDED" >> /home/vagrant/.bash_aliases echo "alias python='python3'" >> /home/vagrant/.bash_aliases fi SHELL end At first I thought it works fine, but then I saw that i can't run "pip" nor enable virtual environment. I don't think … -
Django JSONField, how can i get the count of occurences for values stored in a list
Database is postgres 9.4 In my table i'm using a JSONField class Item(models.Model): item = models.CharField(max_length=200) data = JSONField() Example data JSONField of 3 records: {"color": ["yellow", "blue", "red"], "size": ["S", "L"], "material": "cotton"} {"color": ["white", "blue", "gray"], "size": ["XL", "L"], "material": "cotton"} {"color": ["yellow", "gray", "red"], "size": ["L", "XL"], "material": "cotton"} My goal is to create a list which contains the count of each occuring color and size: color: yellow 2 blue 2 red 2 gray 2 white 1 size: L 3 XL 2 S 1 Is this possible ? What would be the best solution in terms of performance. So far i managed te produce a list containing all occuring lists with: Item.objects.values_list('data__color').distinct().annotate(num=Count('data_color')) color: ["yellow", "blue", "red"], 1 ["white", "blue", "gray"], 1 ["yellow", "gray", "red"], 1 -
How to convert integer value from python to smallint postgresql?
I have a function written in the Postgresql database and have to call it from the Django view in Python. The function has parameters of smallint type. In Python, it looks like str = "02" plist = [int(str)] cursor = connection.cursor() cursor.execute("select * from some_func(%s);", plist) for row in cursor.fetchall(): ... Calling this code in my HTML template I see the following message: function some_function(integer) does not exist That's because the type of parameter is smallint How should I convert my string in order to deliver it as smallint to the Postgresql database? -
How to pass a <select> in a View using Django
I was trying to make a cart system in Django and wanted to pass Size and the Quantity of product as <Select> input in View. My Template have : <ul class="list-unstyled"> Select Size: <select name="sizes"> {% for size in product.sizes.all %} <li class="list-item list-inline-item"><option value="{{size.nameSize}}">{{size.nameSize}}</option> </li> {% endfor %} </select> </ul> This is how it looks : But when i Submit it using the Add to Cart Button i get error: This is the code in the view: def add_item(request,pk): product = get_object_or_404(Product,pk=pk) size = request.POST['sizes'] selectsize = Size.objects.get(nameSize=size) user = request.user usercart = Cart.objects.get(owner=user) newitem = CartItems.objects.create(cart = usercart,product=product,size=selectsize) items = usercart.cartitems return render(request,'cart.html',{'cartitems':items}) I am trying to use the name of the size from the Template and compare the size name i have in the database for that product Using: selectsize = Size.objects.get(nameSize=size) I was able to get size with name 36 so i wanted to pass the value 36 from the template to the variable size using post. But i get the error mentioned which i believe is because name for the is common in all the options. If i can either get an alternate way to do that or solve this error both type of solutions … -
How to add web requests to queue using celery?
I have integrated django-celery-beat which is working fine that means i can register and execute task after some interval of time. But what my client want is to queue up web requests. That means, for example if two users come on the website and both wants to generate a report then second user request will go into queue and wait for the completion of first request. I am not sure whether this is possible with celery. I have tried to find solution but no success. Can anyone help me regarding this. I just need idea or some sample script. Thanks -
Confirmation mail with activation link is not apearing in console
I have writen the code for signup in which after entering the name and password it will redirect us to email sent page as well as it suppose to send mail in console but it is not appearing. views.py def signup(request): if request.method == 'POST': form = SinupForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('user/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: form = SinupForm() return render(request, 'user/register.html', {'form': form}) -
Is there any free project is available for integrate number in python using sympy
Is there any free project is available for integrate number in python using sympy. I want to create a small project that integrate the user number in python and send the output using python and sympy lib.. If any link or any project is available then please help me. -
Internal Server Error 500 on AWS after deploying Django app - following the AWS tutorial
I am trying to learn how to deploy Django/Python to AWS. I have been using the AWS documentation https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-deploy I have followed it (I believe) pretty much to the letter except that I am using pipenv shell as the virtual environment. Here is the django.config file option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango/wsgi.py I updated the ALLOWED HOSTS file: ALLOWED_HOSTS = ['django-env.kdkep9ewpv.eu-west-2.elasticbeanstalk.com'] Here is the wsgi filw: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ebdjango.settings') application = get_wsgi_application() And the error logs are below this. Please can anyone advise where I'm going wrong?? ============== [Sat Oct 12 10:23:29.570668 2019] [suexec:notice] [pid 3119] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Sat Oct 12 10:23:29.586082 2019] [http2:warn] [pid 3119] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Sat Oct 12 10:23:29.586092 2019] [http2:warn] [pid 3119] AH02951: mod_ssl does not seem to be enabled [Sat Oct 12 10:23:29.586517 2019] [lbmethod_heartbeat:notice] [pid 3119] AH02282: No slotmem from mod_heartmonitor [Sat Oct 12 10:23:29.586560 … -
Process and pass data submitted via Ajax in Django to HTML
I have a form that I submitted via Ajax and would like to pass it to HTML after processing. Below works well for the POST function Below code works fine, but when I tried to further process the data with results function, I got error NameError: name 'Elasticsearch' is not defined. The script works well on its own. Should I process the data outside the cat_select function? def cat_select(request): cat_result=[] cat_selected=[] cat_name=['l2','l3'] cat_selected=list(map(lambda x:request.POST.get(x, '').split(','), cat_name))#if POST failed, assign '' #cat_result=c_result(["US"],cat_selected) print(cat_selected) print(cat_result) return JsonResponse({'cat':cat_selected},safe=False) This is the results function which works fine when I run it in a single def c_result(country=[],cat=[]): client = Elasticsearch([{'host':host,'port':9200}]) response = client.search( \ index="indexA", \ body={ #queries } ) print(response) response3=process_result(response) return response3 I am also not quite sure how to GET the data back from the url. Below Ajax GET prints Error! in the console. <form id="cat_select">{% csrf_token %} <input class="site" name="site" type="text"> <input class="l2" name="l2" id="l2" type="text" style="width:30%"> <input class="l3" name="l3" id="l3" type="text" style="width:50%"> <br> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="cat_submit">Submit</button> </form> <script type="text/javascript"> $(document).on('submit','#cat_select',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/cat_select', data:{ l2:$('#l2').val(), l3:$('#l3').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(){ alert ("selected!") } }); $.ajax({ method:'GET', url:'/cat_select', success:function(data){ console.log(data); }, error:function(data){ console.log('Error!'); } }); … -
django user login with custom authentication for double layer protection
I need to save user login information to sessions for login. I am creating double layer protection for user login. need help to create a custom authentication system in Django. I have tried with the following code: def user_login(request): CaptchaForm = CaptchaTestForm() if request.method=='POST': CaptchaForm = CaptchaTestForm(request.POST) user_name = request.POST['username'] raw_password = request.POST['password'] try: user_detail = User.objects.get(username=user_name) except User.DoesNotExist: user = None user = authenticate(username=user_name, password=raw_password) if user==None: return render(request,'registration/login.html',{'invalid':'Invalid Username/Password. Please Try Again','CaptchaForm':CaptchaForm}) else: if user_detail.email_verify==True: if CaptchaForm.is_valid(): human = True request.session['login'] = request, user return redirect('login_2fa',secret_key=user_detail.google_2fa_key) else: CaptchaForm = CaptchaTestForm() return render(request,'registration/login.html',{'invalid':'Please Verify Captcha Again','CaptchaForm':CaptchaForm}) else: return render(request,'registration/login.html',{'invalid':'Please Verify your account in your e-mail','CaptchaForm':CaptchaForm}) return redirect('dashboard') return render(request,'registration/login.html',{'CaptchaForm':CaptchaForm}) Code for authentication login def login_2fa(request,secret_key): totp = pyotp.TOTP(secret_key) user = get_object_or_404(User, google_2fa_key=secret_key) if request.method=='POST': input_otp = request.POST['otp_code'] otp_now = totp.now() if input_otp != otp_now: messages.warning(request,'INAVLID AUTHENTICATION CODE') return redirect('login_2fa',secret_key=secret_key) elif input_otp == otp_now: user_login = request.session.get['login'] login(request, user) return render(request,'registration/login_2fa.html') need help to create the session for storing info of the user. -
How to create a table using Django-Tables2 using fields from multiple models
i'm trying to create a table with Django-Tables2, that consists of fields from multiple forms. I've had a look at the Django-Tables2 documentation and numerous online posts, however I am still struggling to implement this. I've also ensured that I've run makemigrations and migrate, and have tried used fake migrations as well. models.py: class ExpressionOfInterest(models.Model): firstname = models.CharField("Participant First Name", max_length=50) lastname = models.CharField("Last Name"), max_length=50) dob = models.CharField("Date of Birth"), max_length=50) class EntryAssessment(models.Model): client_id = models.ForeignKey(ExpressionOfInterest, models.DO_NOTHING, blank = True, null=True, default=0) name = models.CharField("Last Name"), max_length=50) dob = models.CharField("Date of Birth"), max_length=50) date = models.DateField("Date of Assessment", max_length=50) views.py: class client(SingleTableMixin, FilterView): model = ExpressionOfInterest model = EntryAssessment table_class = ClientTable template_name = "client.html" tables.py: class ClientTable(tables.Table): firstname = tables.Column(accessor="client_id.firstname") lastname = tables.Column(accessor="client_id.lastname") dob = tables.Column(accessor="client_id.dob") class Meta: model = EntryAssessment fields = ('date',) sequence = ('firstname', 'lastname', 'dob', 'date',) I would like the table with the firstname, lastname, dob and date columns to be visible on the /client page, and for the existing data from the database to be pulled through. however at the moment I am receiving a "invalidcursorname" at /client error, despite running makemigrations and migrate. Any help would be greatly appreciated. Thank you -
Unable to change timezone in Django -Dialogflow integration
I'm unable to change the timezone of the dates introduced on a form in a Django app, I want to send this data to Dialogflow and I need it to be in "Europe/Madrid" timezone instead of UCT. I've reading similar question but I still didn't manage to solve it so I would really appreciate if you can help me. settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Madrid' USE_I18N = True USE_L10N = True USE_TZ = True models.py class Response(models.Model): statement = models.ForeignKey(Statement, on_delete=models.CASCADE) response = models.CharField(max_length=400) created_at = models.DateTimeField( default=timezone.now(), help_text='The date and time that this statement was created at.' ) created_at = models.DateTimeField( default=timezone.now(), help_text='The date and time that this response was created at.' ) -
How to solve the error ''WSGIRequest' object has no attribute 'user'"
I am trying to host a django website using virtualmin.Virtualmin script installer support django version 1.7.And i install django 2.2.6 via putty.But i can't access my website.When i access mydomain/admin it shows " 'WSGIRequest' object has no attribute 'user' " error.How can i solve this problem? -
how to retrieve data depend on barcode or qrcode in django
i trying to make an application when i enter product data with its barcode or qrcode then retrieve the product depend on its barcode which entered i know a little about Pyzbar from pyzbar.pyzbar import decode#using decode for decoding the barcode but i dont know how to retrieve the products detail, when capture a products barcode then processing on it , something like POS system (compare with existing barcode in the database) -
Python/Django - not access to linked model in a generic view
I'm newbie in Python and Django I've 3 models linked: patient -> visit -> prescription I want to override get_context_data in a detailView to have access to all prescription related to patient visit to patient related_name = 'visits' prescription to visit related_name = 'prescriptions' but I have an error: PatientFile object has no attribute 'visits' I look what is inside self: patient.views.PatientFile object at 0x04772EB0 I don't understand self is my patient instance so I should have access to all visits with attribute 'visits'? class PatientFile(DetailView): model = Patient context_object_name = "patient" template_name = "patient/file.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['prescriptions'] = [] print('self : ', self) for visit in self.visits: context['prescriptions'].append(visits.prescriptions) return context -
How to intall sympy in my pycharm and code in django
I'm using Pycharm 2019.2.3 with python 2.7. The problem is that i want to include sympy lib. on my project and run using django framework. i am searching but solution is not find.. can uh please help me? -
pipenv or virtualenv , which one is better to use?
I am really frustrated by choosing which one to build my django projects on... what are the cons and pros of each so that i can choose one. on one hand some websites suggest using virtualenv , while on the other hand on quora some people suggest to use pipenv , some people say pipenv is not what the official site claims to be good, while other sites say this is the best every way to build you'r django projects. could you please help me get out of this headache ? -
how to change list contains as user is typing?
I have input and datalist like this. <input list="BrandTitle" name="BrandTitle"> <datalist id="BrandTitle"> {% for item in brand_list %} <option value="{{item.Title}}"> {% endfor %} </datalist> Now I want when I type something I get this on the server-side and send it to SOAP web services. and make brand_list from webservice response. I want to change the brand_list as the user is typing! for example when user type 'a' list shows: 'Apple' 'Facebook' 'Amazon' and when type 'ap' shows : 'Apple' -
How to get the data from the views.py to postgresql as I want to create a seperate table for result I am working on a django-quiz app?
i'm trying to get the data from my views.py to the database. if the views.py code is this views.py from django.shortcuts import render from .models import Questions def home(request): choices = Questions.CAT_CHOICES print(choices) return render(request, 'quiz/home.html', {'choices':choices}) def questions(request , choice): print(choice) ques = Questions.objects.filter(catagory__exact = choice) return render(request, 'quiz/questions.html', {'ques':ques}) def result(request): print("result page") if request.method == 'POST': data = request.POST datas = dict(data) qid = [] qans = [] ans = [] score = 0 for key in datas: try: qid.append(int(key)) qans.append(datas[key][0]) except: print("Csrf") for q in qid: ans.append((Questions.objects.get(id = q)).answer) total = len(ans) for i in range(total): if ans[i] == qans[i]: score += 1 # print(qid) # print(qans) # print(ans) print(score) eff = (score/total)*100 return render(request, 'quiz/result.html', {'score':score, 'eff':eff, 'total':total}) def about(request): return render(request, 'quiz/about.html') def contact(request): return render(request, 'quiz/contact.html') models.py class Questions(models.Model): CAT_CHOICES = ( ('sports','Sports'), ('movies','Movies'), ('maths','Maths'), ('generalknowledge','GeneralKnowledge') ) question = models.CharField(max_length = 250) optiona = models.CharField(max_length = 100) optionb = models.CharField(max_length = 100) optionc = models.CharField(max_length = 100) optiond = models.CharField(max_length = 100) answer = models.CharField(max_length = 100) catagory = models.CharField(max_length=20, choices = CAT_CHOICES) class Meta: ordering = ('-catagory',) def __str__(self): return self.question results.html {% extends "base.html" %} {% block title%} Result {% endblock …