Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix - Cannot set values on a ManyToManyField which specifies an intermediary model. Use catalogue.ProductAttributeValue's Manager instead
I'm using django-import-export package for exporting my product details in xls format. Also, I am using django-oscar package and hadn't modified any of its models. I am trying to import same exported xls file. But I get some strange error: "ManyToManyField which specifies an intermediary model". After digging up into django-oscar Product model, I found it has used through model. I found why I got an error while importing but could not get a clue to solve it. Can anyone guide me what should I do ? I have very hard time understanding the django-oscar models. I merely understood that it is using through model called "catalogue.ProductAttribute". I tried some of the solutions searching on google and stackoverflow but none of them helped me. I used before_import_row function() provided by django-import-export but this didn't helped me. Product = get_model('catalogue', 'Product') class ProductResource(resources.ModelResource): my_categories = fields.Field(column_name='categories') def dehydrate_my_categories(self, product): categories = Category.objects.filter(product=product) result = '' for c in categories: result += c. return '%s' % result def before_import_row(self, row, **kwargs): product = row['product_class'] attribute = row['attribute'] ProductAttribute.objects.create(product_class=product, attribute=attribute) # create object place class Meta: model = Product fields = ( 'id', 'structure', 'upc', 'parent', 'title', 'slug', 'description', 'product_class__name', 'attributes', 'product_options', 'recommended_products', … -
django template automatically convert string type(like '02:34') to time format(seconds)
i'm working with a practice about music website, i need show music's duration in web. for convenience, i used CharFiled in model to store time format like '02:12','03:33','01:22'. but it became like '132' '213' '72'(it's clearly converted to seconds) in web when i use {{ music.duration }} in template but this problem doesn't exist in another page, in this page time show exactly right '02:12','03:33','01:22',the code is same(i copied from one page to another) so, the main question is: why would a string in python be converted to time. to be clear i am not asking for solution, i just wanna know why. i've tried to use filter {{music.duration|time}}, the result is empty in web. i guess it's means that this variable is not a class time. i put a print in view to check context ,this is one in context: 'name': 'Sweet', 'artist': 'Cigarettes After Sex', 'duration': '04:51' as you can see,it's totally normal and definitely a string then i tried to make a filter myself: @register.filter def to_time(value): print(type(value)) value = int(value) m = value//60 s = value%60 s = '0%d'%s if s<10 else s return str(m)+':'+str(s) the result of print has no doubt <class 'str'> although this … -
attach mail in django format error: not a pdf or damaged
for my homework, I'm trying to send an attach pdf to e-mail.I have generated pdf that I want to send. but, when I download the pdf file I have format error: not a pdf or damaged at the opening of the file. definition of render_to_pdf utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None pdf generator function class GeneratePDF(View): context_object_name = 'services' template_name = 'pdf.html' def get(self, request, *args, **kwargs): template = get_template('configuration/pdf.html') f=Reservation.objects.all().filter(Q(valide=True, option__in=Option.objects.all().filter(Q(code_option='GTR', posseder_niveau__in=Posseder_Niveau.objects.all().filter(niveau_id = 1))))).order_by('date_du_jour_reserve') c = Plage_Horaire.objects.all() context = { "c":c, 'f':f, } html= template.render(context) pdf = render_to_pdf('configuration/pdf.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "emploidetemps.pdf" content = "inline; filename=%s " %filename download = request.GET.get("download") if download: content = "attachment; filename=%s" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") mail function def mailjoin(request): GeneratePDF.as_view() email = EmailMessage() email.subject = "test" email.body='emploi de temps' email.from_email = settings.EMAIL_HOST_USER email.to = ['xxxxxxxx@gmail.com' ] email.attach("emploidetemps.pdf", 'application/pdf') email.send() -
how to create a function update using django and ajax
i have a django project that include a form where user insert data and save it into database using django function and ajax call. without using the ModelForm in django. now i want to allow the user to update the form that he choose and once the user choose the form the fields must be displaying the existing data. until now this was the create process. i know that the update process will need the id of the object in order to be able to update the selected record. create.html {% extends "base.html" %} {% load static %} {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/meta-Input.css' %}"> <meta name= "viewport" content="width=device-width, initial-scale=1.0"> <title>Welcome</title> </head> <body> <div class="lines"> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div><div class="line"></div> </div> <form enctype="multipart/form-data"> <div id='left-column-Input' class="formInput" include="select()"> <div class="forminputs"> <input type="text" id="fname" name="fname" autocomplete="off" required /> <label for="fname" class="label-name"> <span class="content-name" name="fname">First Name</span> </label></div> <div class="forminputs"> <input type="text" id="lname" name="lname" autocomplete="off" required /> <label for="lname" class="label-name"> <span class="content-name" name="lname">last name</span> </label></div> <div … -
Passing a list form the front-end (react) to the back-end (django)
I am using React for my front-end and I have a list that I want to process in my back-end (I am using DJango for my back-end) What are the possible ways for me to pass my array list from the front-end to the back-end. I tried saving to create objects of my list and save them in the DB and then process them but it did not work! (or maybe I did not know how to use it correctly). mylist= ['a','b','c']; // somewhere here or laterI want to pass mylist to the back end. fetch('http://localhost:8000/getSentences').then((response) => response.json()).then(function(data) { console.log(data); } I do not expect any result because I did not pass the data that I need to work on! -
aws ecs: deploying django and nginx on same instance vs separate instances, behind ALB
I am trying to deploy my production service on nginx + gunicorn + django (+RDS + Elasticache), behind AWS ALB, using ECS compose. I am trying to use ALB for load balancing purposes, which I know that nginx can handle at the same time. My questions are as follows: Is it better to deploy WebServer(nginx) & WAS(django+gunicorn) on the same instance or different instances? If it is better to deploy on different instances, then what would be the sensible proportion of numbers of instances to start with? My initial thoughts are that I should use ALB for load balancing between instances that have all of the three nginx+gunicorn+django containers running. And add autoscaling group to scale those instances. If is good enough? Thanks. -
How do I save google places location to django models?
I am trying to create an app that relies heavily on location. I am using google maps places api to allow users to select a location and add it to the database. My current issue is that I can't seem to figure out how to save the location from the google maps places JavaScript api to the database. For example Suzy chooses a store and wants to save the store and it's location to the database. I can't seem to figure out how to save the store location to the database. Any idea on how to do this? -
After Build Docker mysql Database throw OperationalError
I was trying to run a Django project with Docker + Nginx + MySQL, by following this Link After successfull build, by running docker-compose up --build my project run well but when I try to access Django admin panel by username and password. its throw this error Also, this project cannot find the static file in the admin panel. Whats I'm doing wrong? -
How to translate django-allauth templates?
I've already translated my project in Malagasy (mg_Mg) but when installing django-allauth and override templates, translation won't be applied. After python manage.py makemessages and testing some translations eg: sign up -> Hisoratra anarana in render it show sign up. But in my local app, all templates are translated correctly. In config/setting.py # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en-us', 'English'), ('fr-fr', 'French'), ('mg-mg', 'Malagasy'), ] LOCALE_PATHS = [BASE_DIR('locale')] In fandaharana/views.py def month(request, month_num, year_num): translation.activate('mg-mg') ... return render(request, 'month.html', data) -
How to create cache of a view every 5 minutes without user requesting it
So I have a view def index(request): API call here that I wish to use to update my database return render(request, ... ) I want this view to be called every 5 minutes even if no one requests the URL. Basically, create a cache of this view every 5 minute and more importantly, it will let me update my database every 5 minutes. -
How to use an existing table for user login in Django?
Since the tables already exist in the DB for login, I cant use the built-in Django models. I have used inspectdb to map the tables to the project which s working fine, but with login how do I use the existing user model for authentication the views part. This is the User table: class Credential(models.Model): username = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) type = models.ForeignKey('Usertype', models.DO_NOTHING, db_column='type') class Meta: managed = False db_table = 'tb_credential' verbose_name_plural = "Credentials" def __str__(self): return self.username views.py def login(request): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') -
Django responds w/ byte literal when DEBUG is True
I'm in the middle of migrating a Django project to Python 3 and updating several dependencies along the way. Right now, I'm using Django 2.2.3. After putting the code on the staging server I noticed that all responses are returned as bytestring literals: b'<html>\n...' This was very hard to narrow down because I first noticed it only on the staging server. Luckily I found out that this has nothing to do with NGINX nor Gunicorn but that DEBUG=True is actually the culrit. The question is: what does DEBUG=True trigger that is messing up the response? -
Django Rest Framework additional authentication checks
I'm developing an app using Django Rest Framework. How can I extend authentication checks on user login? For example, I need to check the is_active and created_at properties of the user that logs in, and allow or disallow the login based on their values, but only after the password was verified by Django. I know about Django and Django Rest Framework custom authentication. https://docs.djangoproject.com/en/2.2/topics/auth/customizing/ https://www.django-rest-framework.org/api-guide/authentication/#custom-authentication The problem is, that requires me to re-implement the built-in authentication checks. I would like to just add checks on top of that. Thanks! -
Django not uploading properly to S3 when running on heroku
I am trying to upload an Image Field using S3, in my local environment it works really well so I am confused on why, when its on heroku, it reads the URL as a double string plus a s3%, makes no sense I have already tried changing STATICFILES_STORAGE and DEFAULT_FILE_STORAGE around, even named it the same thing, but then only generates more errors, I am confused on why this does not function. class Vehicle(models.Model): vehicle_type = models.CharField(max_length=255) vehicle_id = models.CharField(max_length=255) image_url = models.ImageField(upload_to="img/", blank=True, null=True) checked = models.BooleanField(default=False) nfmc_step = models.ManyToManyField(TM, related_name='step') AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_S3_FILE_OVERWRITE = True AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' Expected result as in my local machine: https://project-name.s3.amazonaws.com/static/1.jpg What I get: https://project-name.s3.amazonaws.com/static/https%3A/project-name.s3.amazonaws.com/static/img/2_aeS9ZS2.jpg -
How to develop a hybrid system using django for web development and andriod studio as my mobile application?
I'm using python and django framework for web development. I just wanted to know how can I make a hybrid development. I already developed a web that has a admin user, staff user and user. I just wanted to know how I can apply that in mobile and still have the functionality as web. Example, you send a message to your friend on messenger through laptop and your friend receives it on his phone. -
Django media upload not working when uploading image through code
I have created a Django application in which i have a signup page which asks a user to upload their profile picture. When I'm uploading the profile picture through the Django admin panel, the images are being uploaded to the correct path and are being displayed in the website. However, the error comes when I directly select the image to upload when signing up and then When I click on the uploaded image in Django admin it shows page not found and the path to the image is being showed as C:\Users\hp\Workspace\findem\media\image.jpg Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'findem/static') ] # media folder settings MEDIA_ROOT = os.path.join(BASE_DIR , 'media').replace('\\', '/') MEDIA_URL = '/media/' User Model class UserProfile(AbstractBaseUser, PermissionsMixin): """Represents a user profile inside our system""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255, default=profile_pic) profile_picture = models.ImageField(upload_to='photos/profile_pictures/', default='photos/User.jpg') is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) highest_degree_earned = models.CharField(max_length=255, blank=False) college_name = models.CharField(max_length=255, blank=False) graduation_year = models.IntegerField(default=2020, blank=False) Template : <form class="needs-validation" novalidate autocomplete="off" action="{% url 'signup' %}", method="POST" > {% csrf_token %} <div id="Personal_Information"> <h5 class="loginSignup">Personal Information</h5> <div class="form-group row"> <label for="inputprofile" class="col-sm-2 col-form-label">Profile Picture</label> <div class="col-sm-5"> <div class="input-group"> <div class="custom-file"> <input type="file" accept="image/png, image/jpeg, image/gif" … -
How to make integer field fixed to ten numbers output in models
I want user to input their phone numbers with 10 digits, how to set integer field "phone_no" in order to achieve it ? I have set it to default but I want to check number input : models.py class Documents(models.Model): docs_name = models.CharField(max_length=200,verbose_name="Names in Documents") item_type = models.CharField(default="", max_length=100, help_text='*Enter the item name you found e.g. Marksheet,key,wallet',verbose_name="Item type" ) police_station = models.CharField(max_length=255, help_text='*Enter the police station you sending the docs', verbose_name="Police station") phone_no = models.IntegerField(default=0, verbose_name="Phone number") date = models.DateTimeField(default=timezone.now,verbose_name="Date") Description = models.TextField(blank=True, null=True, help_text='*Enter full description about item',verbose_name="Description") pay_no = models.IntegerField(default=0,verbose_name="payment number") publish = models.BooleanField(default=False) image = models.ImageField(default="add Item image", upload_to="DocsImage",blank=False, verbose_name="Images") """docstring for Documents""" def __str__(self): return self.docs_name -
sampleBot matching query does not exist
I'm new in django,I have some codes in my views.py but when I runserver I get the bellow ERROR "sampleBot matching query does not exist" models.py from django.db import models def sample_image_path(instance,filename): return instance.title class sampleBot(models.Model): title = models.CharField(null=True,max_length = 100) sample_image = models.ImageField( upload_to='sample_image_path',null=True) description = models.TextField(null=True) telegram_link = models.CharField(null=True,max_length=50) def __str__(self): return str(self.title) views.py from django.shortcuts import render from app_base.models import sampleBot def sample_details(request,id): ctx ={} ctx ['sample-detail'] = sampleBot.objects.get(id=id) return render(request,'sample-details.html',ctx) urls.py from django.contrib import admin from django.urls import path,include from app_base import views urlpatterns = [ path('',views.home), path('sample-detail/<int:id>',views.sample_details), ] I don't know how can I solve this ERROR. -
How to access subdomain in for ssh tunneling for django multi-tanant app?
One of my friends has a Multi-Tenant Django app running at gitlab ci. He's accessing the app by ssh tunneling and has given it to an android app developer who can access API via IP address. As a multi-tenant app every time a user is created a new subdomain is created. Suppose I created a user named usa. So, this can be accessed by usa.domainname.com. Since we are providing the app developer an ip address. He can access the site but not the subdomains that are created dynamically. Let's say, we have given him the ip 172.168.0.1. He can access the main site with this IP but he cannot access usa.172.168.0.1. When I ran the app I could access it at 'localhost:8000' and the subdomain at 'usa.loclhost:8000'. But I cannot access it at 'usa.127.0.0.1:8000' I understand that we cannot use subdomains with IP address. Because subdomains itself has it's own DNS. I want the app developer to access those dynamically created subdomains via IP. Since it's not deployed anywhere all I have to give the app developer is IP addresses. How can I do that? Thank you. -
how to get backward relation for a set of objects in django?
I have a model for City and Province: class Province(Model): name = CharField(...) class City(Model): name = CharField(...) province = ForeignKey(Province,......, related_name='cities') suppose I have populated the database as below: ontario = Province.objects.create(name='Ontario') quebec = Province.objects.create(name='Quebec') alberta = Province.objects.create(name='alberta') toronto = City.objects.create(province=Ontario, name='Toronto') waterloo = City.objects.create(province=ontario, name='Waterloo') montreal = City.objects.create(province=quebec, name='Montreal) calgary = City.objects.create(province=calgary, name='calgary') I can retrieve a queryset for all of the cities of ontario as below: ontario.cities.all() There are two objects in the above queryset: toronto and waterloo How can I have a queryset of all cities of ontario and quebec? I need a queryset that retrieves toronto, waterloo, and montreal -
How to add information in a page without refreshing the page?
I would like to have a page in my django aplication that has a button that search a product and after selecting quantities gets added to the page (without reloading) in a list where the total get calculated (something like that), I am a beginner in programing and I have a week reading and investigated how to do it but I don't found anything. Is because you need other programming lenguaje? Or could you indicate me some documentation or some example that I can read. Mostly because for my inexperience I don't know how to identify the relevant information in the documentation or even what to look for. -
Django activity user feed is empty
I am trying to implement a Django activity user feed for the currently logged in user in the admin. I created an action with the following code in my view: action.send(request.user, verb="created comment", action_object=comment_object) I have confirmed this creates a corresponding database entry. However, when I access the url - http://localhost:8000/activity/feed/json/, I get an empty response. Can someone help point me in the right direction? Thanks in advance. -
How to Annotate Nested Span Relationships and Reuse It for Multiple Filter Conditions?
I am trying to exclude nested foreign key fields from Django query. I have a relationship model. class Relationship(news_models.TimeStampedModel, RelationshipStatus): from_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='from_users') to_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='to_users') status = models.CharField(max_length=10, choices=RelationshipStatus.RELATIONSHIP_STATUSES) I wrote like this: Post.objects.filter( ~Q(Q(creator__from_users__to_user=user) & Q(creator__from_users__status='BLOCK')) & ~Q(Q(creator__to_users__from_user=user) & Q(creator__to_users__status='BLOCK')) ) But it does not work because this query excludes all the users who blocked or got blocked by at least one irrelevant user. I want something like this: Post.objects.filter( ~Q(creator__from_users=Subquery(Q(to_user=user) & Q(status='BLOCK'))) & ~Q(creator__to_users=SubQuery(Q(from_user=user) & Q(status='BLOCK'))) ) Or Post.objects.annotate(creator_from_users=F('creator__from_users')).annotate(creator_to_users=F('creator__to_users')).filter( ~Q(Q(creator_from_users__to_user=user) & Q(creator_from_users__status='BLOCK')) & ~Q(Q(creator_to_users__from_user=user) & Q(creator_to_users__status='BLOCK'))) ) How should I annotate or save the value in the middle and reuse it to filter nested foreign fields? -
How to filter Django object to get top X number of objects with highest property value
So I have a class called Hero with 150 objects. Each object has a property Winrate. I want to get the top 12 heros based on winrate. class Hero(models.Model): hero_name = models.CharField(max_length=20, default = 'Dota 2 Hero') hero_id = models.IntegerField() def __str__(self): return str(self.hero_id) def get_winrate(self): wins = len(Match.objects.filter(heros_won = Hero.objects.get(hero_id = self.hero_id))) losses = len(Match.objects.filter(heros_lost = Hero.objects.get(hero_id = self.hero_id))) if wins + losses != 0: return round((wins / (wins + losses)),2) else: return 0 winrate = property(get_winrate) I tried alot of filters but couldn't get it to work. -
advantages of generic view method over apiView
I am working on a big project and when it comes to the views.py, I was adviced by a friend to use apiViews over generic view or modelViewset. I would like to know what advantage a view method could have over others that makes it better to use in a big project over other methods. the project in question would have things like users making video posts and updating it, following other users, collaborating e.t.c.