Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python rstrip usage within loop while reading csv file
I have a csv file where I am looping and matching with my database for getting results according to these matches. I encountered a problem, in case where there is a space at the end of the text. So I did my research and found that I need to add rstrip function to remove spaces at the end of the text. Here is my code: with open(path, encoding='utf-8') as f: data = csv.reader(f, delimiter='|') for row in data: line = row[0] cleanline = line.rstrip() lines.append(cleanline) query = line The code is not working.I tried also strings like /s or strip and replace functions as well but nothing is working. What can be the reason ? What am I doing wrong ? -
Can't remember my postgres user password to connect server
I'm working in this Django app but I stopped working on it per two weeks, so my computer was off during this time. Now I want to work on it again this error appear to me over and over again in my command line, I opened pgAdmin and found is because I need my password for my postgres user and I can't remember it. Does anybody knows how to fix this? -
Python: how to install GDAL on windows 10?
I am working on a django project, and I need to install the GDAL library, and this can be done by downlaoding it from this link : http://www.gisinternals.com/sdk/ (following the GDAL documentation ) but I'm afraid the link doesn't work. is there an other way to install GDAL? -
The kakao autoresponder API has problems accessing the keyboard
I want to make chatbot using kakaotalk. but have problems accessing the keyboard. I use python,pycharm and django. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'globalHaksik', ] urlpatterns = [ path('admin/', admin.site.urls), path('globalHaksik/', include('globalHaksik.urls')), ] urlpatterns = [ path('keyboard/', views.keyboard), ] from django.http import JsonResponse def keyboard(request): return JsonResponse({ 'type': 'buttons', 'buttons': ['오늘', '내일'] }) KakaoTalk shows this error. Required* keyboard Fail 415 wrong keyboard initialization When I use view.py like this, it works fine on the internet. def keyboard(request): return HttpResponse("Hello, world. You're at the polls index.") why is this errer? -
Creating multiple Django model forms to change/edit multiple existing objects on the same page without passing object-id via URL
I'm trying to build an Object detection service where the user can choose multiple objects he would like to detect. The Object Model looks like the following: #models.py class Object(models.Model): name = models.CharField(max_length=50) image = models.ImageField() detect = models.BooleanField(default=False) def get_absolute_url(self): return reverse('Objectdetector:objectdetail', kwargs={'pk': self.pk}) def __str__(self): return self.name The page is showing an overview of all the objects a user has created and there is a checkbox next to each object linked to the "detect" attribute. The model form looks like this: #forms.py class DetectForm(forms.ModelForm): class Meta: model = Object fields = ['detect'] So in the views.py I'm trying to stick to the Django documentation and pass the instance to the form like such: form = DetectForm(instance = objectinstance) but i can't figure out how I am supposed to do it correctly. This is the view, you can ignore the post method for now: class DetectView(generic.ListView): template_name = 'Objectdetector/detect.html' def get(self,request): objectinstance = #Please help form = DetectForm(instance = objectinstance) objs = Object.objects.all() args = {'form':form, 'all_obj': objs} return render(request, self.template_name, args) def post(self, request): form = DetectForm(request.POST) if form.is_valid(): form.save() return redirect('Objectdetector:detectobjects') args = {'form':form} return render(request, self.template_name, args) I then want to loop through all objects and … -
Django: Convert Word doc to pdf in Python on machine without Word installed
I'm currently working on a Django web-app that needs to retrieve several documents from a DMS, merge them into a single, large PDF, and distribute this file as output for the user. The largest issue in this process stems from the fact that some of these files are retrieved by python in doc/docx format. Typically I would use something like pythoncom and comtypes.client to convert these files before moving forward with the merger, like so: wdFormatPDF = 17 pythoncom.CoInitialize() word = comtypes.client.CreateObject('Word.Application') word.Visible = False doc = word.Documents.Open([retrieved doc file]) doc.SaveAs(os.path.join([newly created pdf file]), FileFormat=wdFormatPDF) doc.Close() word.Quit() However, this only works on a machine that has Microsoft Word installed. Since the app would ideally be running on an IIS server, this isn't really an option in my environment. I considered testing pypandoc and miktex/xelatex (which would still require external references on the Windows Server, but my options are starting to seem limited), like so output = pypandoc.convert_file([retrieved doc file]), 'pdf', outputfile=os.path.join([newly created PDF file])) While this creates the PDF, there are problems with the conversion. I can account for some by adding font settings to the extra arguments, but the doc files have images and some specific alignments that don't … -
Migrating User Password from Rails To Django (Bcrypt)
I'm moving our site from Rails to Django and have migrated the user password hashes. Installed bcrypt via pip install bcrypt In base.py, I have set the base hash in PASSWORD_HASHERS to: 'django.contrib.auth.hashers.BCryptPasswordHasher' Set the Django site's DJANGO_SECRET_KEY to Rail's SECRET_KEY_BASE. Restarted the server However, I still get an error that the password is incorrect. The issue may or may not be related to Migrating Parse.com passwords to Django, but I don't believe so as our Rails app is not using a salt. -
Count items via ForeignKey models, Django 1.11
I have 3 models: class Product(TimeStampedModel): product_id = models.AutoField(primary_key=True, ) brand = models.ForeignKey('Brand', related_name='products', on_delete=models.CASCADE) title = models.TextField(blank=False, null=False) '''...''' class Brand(models.Model): brand_id = models.AutoField(primary_key=True,) brand_name = models.CharField(max_length=50) shops = models.ManyToManyField('Shop', related_name='shops') '''...''' class Shop(models.Model): shop_id = models.AutoField(primary_key=True,) shop_name = models.CharField(max_length=30) '''...''' I want to show in my HTML Brand and amount of products which belong to this brand, smth like this: FooBar 50 BazFoo 25 BarBob 12 How can I do this in the fastest way? I have tried: brands = {} for prod in products_list: brands[prod.brand.brand_name] = brands.get(prod.brand.brand_name, 0) + 1 But this iteration sometimes takes ~7 seconds (for the list of 20k+ items). May be there is some kind of ORM trick or something else? P.S. Currently I am getting brands like this, without products amounts: brands = Brand.objects.filter(shops__shop_name__in=[shop]) -
django extract only year from date time in queryset
I have a purchases table with a column datatime. I would like to select all purchases I have done in the current year. bellow is my code but is not working! import datetime today = datetime.date.today() year = Purchases.objects.filter(date__year = today.year) I expect the year should be 2018 extracted from 2018-04-12 -
How to hide/show columns according to user input using django-tables2
I have a table with many columns (and rows), which I render using {% render_table table_all %} in a html template of my django app. I want to display certain columns and give the user the choice to show additional columns (using f.ex. a checkbox or drop-down menu). Is this possible with django-tables2? Or do I have to use javascript? -
Django queryset with LOTS of annotations performance
Is there a limit for the number of annotations on a queryset? Will there be a significant performance hit if I add lots of (over 50) annotations to a queryset? -
Check if the response of a get api is a proto object
I fetch a proto object from an api , is there anyway I can validate that the response is a proto file. One thing which I did was check content-type as mentioned in the json counterpart of this question. But the answer goes on further to validate json using JSON.parse The content-type of a proto file comes out to be application/octet-stream ( protobuf can have this content-type , check this ) Is there any other check I should do to validate response is a proto object ? -
Adding Wagtail to an existing Django app
I'm quite new to Django and Wagtail, and I'm having some difficulty with what I think is a very basic use. How do I allow Wagtail to edit an existing view's template, while serving that template using Django's serving mechanism? Assume I have an app (HomePage) created to serve the site's main index (/). I have the HomePage's views set up to render template and certain elements dynamically. Now I want that template to be editable via Wagtail's CMS interface. Something as simple as an image on the frontpage, or a headline. The closest I've gotten so far has been to follow the Wagtail beginner's tutorial to override the base HomePage class in my app's models.py. That only made my pages available via the /pages/ URL. Thank you for any help. -
Visual Studio Code strange underscoring
I'm making some django project since yesterday and it all went fine until I started it up today. I launched Visual Studio Code and program became to underscoring lines which was fine to it yesterday, i literally haven't change anything and i see now red underscore in few files. I remind that yesterday everything was fine. Have a look: Can i disable this non-sense underscoring? -
How to display image on Django running on AWS EC2?
I know I'm close to this one, I just can't drag it the 2% across the finish line - I'm trying to add a static image to a site I've created in Django, that I'm hosting on my AWS EC2 instance. I've got the image to display here: /project/app/static/media/image.jpg where /project/app/static/css holds the CSS style file. I've got the following code in my project/settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "static/media/") And the following code in my project/urls.py file: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and my html file in project/app/templates folder has: <img src="{{ MEDIA_URL }}/image.jpg" alt="Image Text"> I've also run python manage.py collectstatic to no change. Has anyone had this problem before? It's killing me. -
Django, Postgres DateRangeField
im using the range fields feature for postgrest in Django, and i made a model in wich the date from and date to are stored in a range for checking if it overlaps, but there is a problem, if the date from and date to are the same date the model get stored like this. DateRange(empty=True) I tested that this DateRange feature can store a range that has the same date at start and at the end if i test it in the shell, but, in the model when it gets saved it just save it like i just mentioned before. ¿What can i do? Edit: This is the code. class Reservaciones(models.Model): class Meta: verbose_name_plural = "Reservaciones" def random_string(): return str( randint(10000, 999999999) ) fechas_semana = [ timezone.localdate() + timedelta(days=i) for i in range ( 0 - date.today().weekday(), 7 - date.today().weekday() ) ] fecha_vie = fechas_semana[4] ESTADOS= ( ("Pendiente", "Pendiente"), ("Reservado", "Reservado"), ("Usado", "Usado"), ) nucleo = models.ForeignKey( Nucleo, on_delete = models.CASCADE, null = False, blank = False, limit_choices_to = { 'estado': "Activo" } ) cabaña = models.ForeignKey( Cabaña, on_delete = models.CASCADE, null = False, blank = False, limit_choices_to = { 'estado': "Activo" } ) estado = models.CharField( max_length = … -
Pagination is not working on django_tables2
I am using the django_tables2 and wanted to show the pagination effect through the following code: table = QuestionTrackTable(QuestionTrack.objects.filter(qt_weight__gt=0), prefix='1-') RequestConfig(request, paginate={'per_page': 10}).configure(table) export_format = request.GET.get('_export', None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, qt_table) return exporter.response('table.{}'.format(export_format)) return render(request, 'cmit/report_result.html', {'table': table}) Problem is that the output does not show the pagination rather it shows a pager only. Here is the screenshot: -
How to save custom choice for ChoiceBlock (ChoiceField)
In wagtail, I'm creating a custom block which have dependents dropdowns. I don't know in advance which choices will be so I'm initializing these choices empty. I have a working custom form for the admin site of wagtails, they populate dynamically. When I hit save, it only saves the first dropdown which I provided values. The two and three dropdowns are saving empty instead of the actual value. I checked the POST request and they're correct values traveling. class CustomChoiceField(forms.ChoiceField): def valid_value(self, value): return True class CustomChoiceBlock(blocks.FieldBlock): def __init__(self, required=True, choices=(), help_text=None, **kwargs): self.field = CustomChoiceField(required=required, choices=choices, help_text=help_text) super(CustomChoiceBlock, self).__init__(**kwargs) class MyCustomblockBlock(blocks.StructBlock): one = CustomChoiceBlock(required=True, choices=INITIAL_CHOICES) two = CustomChoiceBlock(required=True, choices=()) three = CustomChoiceBlock(required=True, choices=()) def get_form_context(self, value, prefix='', errors=None): context = super(MyCustomblockBlock, self).get_form_context(value, prefix=prefix, errors=errors) forms = [] children = [child for key, child in context['children'].items()] for idx, child in enumerate(children): form = child.render_form() forms.append(form) context['forms'] = forms return context class Meta: icon = 'cogs' form_template = 'core/admin/my_template.html' In my_template I have the JS logic to populate the values for the dropdowns. -
QuerySet filter ArrayField contains exact match
I have a model that generally looks like this: class CategoryModel(models.Model): categories = ArrayField(..) Let's say I have two categories, "categoryA" and "categoryB" categoryA's categories is equal to [123, 562], and categoryB's categories is equal to [5, 32] When I want to query for CategoryModels which contain exactly 5 as an item in it's categories list, I use CategoryModel.objects.filter(categories__icontain=5) Unfortunately, the above query returns both categoryA and categoryB, not just categoryB. What is the proper way to perform this query? -
Django & Stripe: How to send error messages?
I integrated Stripe in my project and as long all credit card details are fine, my app works perfectly. However, I didn't integrate yet error message handling and I have a bit a problem to understand how this works. I am not that familiar with Ajax yet, and maybe there lies the problem. Looking into the reference API, and clicking on Python, this doesn't look like Python code to me, and I don't know how to handle the error message handling as it's explained there. Can anyone help me out with the attached code? I also would be interested what I have to look into and learn, to better understand what's written under Python in the API reference. def stripe_charge(self, transaction_profile, **kwargs): try: c = stripe.Charge.create( amount=kwargs['total']*100, currency='eur', description=kwargs['order_id'], receipt_email=transaction_profile.email, source=kwargs['token'], ) new_charge_obj = self.model( transaction_profile = transaction_profile, stripe_id = c.id, paid = c.paid, refunded = c.refunded, outcome = c.outcome, outcome_type = c.outcome['type'], seller_message = c.outcome.get('seller_message'), risk_level = c.outcome.get('risk_level'), ) new_charge_obj.save() except stripe.error.CardError as e: # Since it's a decline, stripe.error.CardError will be caught body = e.json_body err = body.get('error', {}) # print "Status is: %s" % e.http_status # print "Type is: %s" % err.get('type') # print "Code is: %s" … -
how to perform arithmetic operations in a class with variables in models.py in Django
I want to calculate salary of employees through my equation total_salary=(time_out - time_in )* base_salary + (time_out - 8PM) * base_salary*0.20 class salary(models.Model): empname = models.ForeignKey('employee1',default='0',on_delete=models.CASCADE) base_salary = models.IntegerField(default='0', help_text="Base Salary") time_in = models.DateTimeField(default=datetime.now, blank=True) time_out = models.DateTimeField(default=datetime.now, blank=True) total_salary=models.CharField(max_length=20,default='0',blank=True,editable=False) def default_over_time(): now = datetime.now() start = now.replace(hour=8, minute=0, second=0, microsecond=0) return start if start > now else start + timedelta(days=1) def save(self,*args,**kwargs): self.total_salary=(self.time_out - self.time_in) self.total_salary=(self.time_out - self.time_in )* self.base_salary + (self.time_out - self.default_over_time) * self.base_salary*0.20 self.total_salary=str(self.total_salary) super(salary,self).save(*args,**kwargs) I have tired everything. I would be very grateful if i get some help here -
Django - UPDATE user fields in two different views (forms)
I have hard time with such a easy thing (I guess). My aim is to create two subpages with 2 different forms yet connected with the same user model: /account/register.html - page only to manage registration (create user with login,email,password) /account/questionnaire.html - page for UPDATING the same user information such as age,weight,height etc. I've got 'POST' communicates in server log but nothing appears when I'm checking up django admin site. models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.PositiveIntegerField(blank=False) weight = models.PositiveIntegerField(blank=False) height = models.PositiveIntegerField(blank=False) forms.py from django import forms from django.core import validators from django.contrib.auth.models import User from account.models import UserProfile class RegisterUserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password') class RegisterUserInfoForm(forms.ModelForm): class Meta(): model = UserProfile fields = ('age','weight','height') views.py from django.shortcuts import render from account.forms import RegisterUserForm, RegisterUserInfoForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required def register(request): registered = False if request.method == 'POST': user_form = RegisterUserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True else: print(user_form.errors) else: user_form = RegisterUserForm() return render(request,'account/register.html',{ 'user_form':user_form, 'registered':registered, }) @login_required def questionnaire(request): if … -
django-cookiecutter, docker-compose run: can't type in terminal
I'm having an issue with a project started with django cookiecutter. To verify that the issue was not with my project, I'm testing on a blank django cookiecutter project. The issue is that when I run: docker-compose -f production.yml run --rm django python manage.py createsuperuser I get the prompt but can't type in the terminal. Same thing when I run: docker-compose -f production.yml run --rm django python manage.py shell I get the shell prompt, but I can't type. The app is running on a machine on DigitalOcean created with the docker-machine create command. Any thoughts on what the issue could be and how I could debug this? -
How can I personalize the template of the django-oscar?
I'm a beginner in django/oscar. I created my virtual env and I followed the procedure for create a new django project. Now, I want to personalize my page without to fork the repo.I want only extend oscar's template (for example change background, add a new navbar ecc). -
Django filter model with timestamp
I have the following models: class User(models.Model): id = models.CharField(max_length=10, primary_key=True) class Data(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.IntegerField(default=0) Given a single user, I would like to know how I can filter using timestamp. For example: Obtain the data from user1, between now and 1 hour ago. I have the current timestamp with now = time.time(), also I have 1 hour ago using hour_ago = now-3600 I would like to obtain the Data that has a timestamp between these two values.