Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get the latest dated dictionary from list of dictionaries
i have list of dictionary objects with date and name and status. "elements": [ { "PersonId": 301178, "Wwid": "10692133", "FullNm": "abc", "CompletionDt": "2015-04-29", "status": "Complete", }, { "PersonId": 301178, "Wwid": "10692133", "FullNm": "abc", "CompletionDt": "2019-07-30", "status" : "complete" }, { "PersonId": 301178, "Wwid": "10692133", "FullNm": "abc", "CompletionDt": "2016-08-01", "status": "Inclomplete", }, { "PersonId": 301178, "Wwid": "10692133", "FullNm": "abc", "CompletionDt": "2017-04-10", "status": "Completed", } ] In this dictionary how to pick the latest dated object using python? In the above example result= { "PersonId": 301178, "Wwid": "10692133", "FullNm": "abc", "CompletionDt": "2019-07-30", "status" : "complete" } -
Unable to Deploy Django Project On Gcloud
I'm want to deploy my Django project with MySQL on Gcloud I have done all configurations but I'm getting a major issue and it cant be deployed Im getting this error "ERROR: (gcloud.app.deploy) INVALID_ARGUMENT: This deployment has too many files. New versions are limited to 10000 files for this app. - '@type': type.googleapis.com/google.rpc.BadRequest fieldViolations: description: This deployment has too many files. New versions are limited to 10000 files for this app. field: version.deployment.files[...] django" App.yaml # [START django_app] runtime: python38 handlers: # This configures Google App Engine to serve the files in the app's # static directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to the main app. # It is required when static routes are defined, but can be omitted # (along with the entire handlers section) when there are no static # files defined. - url: /.* script: auto # [END django_app] I dont have idea why im getting this error so please let me know so I can fix this issue also this is view for sql data Sql Statics Please guys help me to fix this issue -
Call model in base html file django
Im trying to find out how to call one of my models in my base html file that extends to my other template html files in order to implement viewing of cart items in the navbar which is in my base.html file. normally i would have used context data to call models in my views (I am using Class Based Views) but this is not possible with base.html file this is the code that would be used to if it was a template with a view {% for item in orderitems %} <div class="ps-product__thumbnail"> <a href="#"> <img src="img/products/clothing/7.jpg" alt=""> </a> </div> <div class="ps-product__content"> <a class="ps-product__remove" href="#"> <i class="icon-cross"></i> </a> <a href="product-default.html">MVMTH Classical Leather Watch InBlack</a> <p><strong>Sold by:</strong> YOUNG SHOP</p><small>1 x $59.99</small> </div> {% endfor %} -
How do I populate a Django ManyToMany relationship with a list from a CSV file, only creating entries for the elements in that list?
I've been following the instructions laid out here trying to populate my Django ManyToMany relationship with data from a list from a column of a csv file. The problem is that when I run the popultate.py file, instead of populating Film.actors with the actors specified in the list from the CSV file, it populates Film.actors with every actor in the database. How do I amend it so that it only populates the model with the data from that list? Here is my models.py file: class Actor(models.Model): actor_id = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=40) class Film(models.Model): film_id = models.CharField(max_length=20, unique=True) title = models.CharField(max_length=60) actors = models.ManyToManyField(Actor) And here is populate.py: import pandas df = read_csv('csv_file.csv') def populate_film(): for index, row in in df.iterrows(): film_csv_id = str(row['IMDb ID']) film_name = str(row['Film']) film = Film.objects.get_or_create(film_id = film_csv_id, title = film_name) #The CSV actors column returns a the list of actor_ids which I query against the Actor model list_of_actors = row['Actors'] for actor_id in actor_join_list: actor_object, _ = Actor.objects.get_or_create(imdb_id = actor_id) film.actors.add(actor_object) populate_film() Thanks! -
Is there any way we can override the django.request and change the logic for cookie parsing?
On Django 1.9, if any value of the cookie contains a space, then the Django 1.9 would not parse any of the cookies and hence, csrftoken validation would fail as well. We are thinking of fixing the cookie parsing logic on Django request. -
Combination of the with and cycle django templatetags
i've 2 for loop in a django template file, and i'd like to generate the value of the cycle templatetags in the first loop, but using it in the second. Somehow like this: {% for item in firstloop %} {% with requiredvalue=!cycle 'red' 'blue' 'green'! %} {% for inneritem in innerforloop %} {{ requiredvalue }} {% endfor %} {% endwith %} {% endfor %} . This is not a working code of course, but if the firstloop has 3 elements, and innerforloop has 2 elements, i'd like to get this result: red, red, blue, blue, green, green . Is it somehow doable on the template side? Thanks. -
Docker container not running on Linux
In our project we use docker to keep our development environments similar. When running it on macOS it works, however on Linux (currently using Manjaro) it states that the container doesn't exist: docker-compose -f docker-compose.yml exec web python manage.py migrate --noinput Error response from daemon: Container 43f405eac00706b22dc075cbcaf33dbbf595971be3ce1955034302cb1284aa5b is not running make: *** [Makefile:9: build] Error 1 This is the makefile for our project: build: make down docker-compose -f docker-compose.yml up -d --build docker-compose -f docker-compose.yml exec web python manage.py migrate --noinput docker-compose -f docker-compose.yml exec web python manage.py createsuperuser --noinput --email name@testmail.org docker-compose -f docker-compose.yml exec web python manage.py startup We tried different systems and different commands, but it always fails when trying to execute the second command. -
Django can not show image in folder
I create folder images path static/media/images/ and upload image 02.jpg to folder images by FTP. I want to show image 02.jpg to index.html but it's not show image. This is my code. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index), ] if settings.DEBUG: urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) settings.py #BASE_DIR is project location STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR, 'static', 'media') index.html {% load static %} <img src="{% static '/images/02.jpg' %}" class="d-block w-100" alt=""> How to fix it ? -
'clientname' object has no attribute 'set_password'
I am working with django rest framework, registration and login. and i received this error 'clientname' object has no attribute 'set_password' how do i solve this problem? this is my serializers.py class clientnameSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = clientname fields = ('id','username','password', 'password2' , 'email') ordering = ['id',] extra_kwargs = { 'password': {'write_only': True} } def save(self): account = clientname( email=self.validated_data['email'], username=self.validated_data['username'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account this is my views.py @api_view(['POST',]) def registration_view(request): if request.method == 'POST': serializer = clientnameSerializer(data=request.data) data={} if serializer.is_valid(): account = serializer.save() data['response'] = "successfully registered a new user." data['email'] = account.email data['username'] = account.username else: data = serializer.errors return Response(data) this is my full traceback Traceback: File "/home/schoolsite/schoolsitedir/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 54. return view_func(*args, **kwargs) File "/home/schoolsite/schoolsitedir/env/lib/python3.6/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/home/schoolsite/schoolsitedir/env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch 505. response = self.handle_exception(exc) File "/home/schoolsite/schoolsitedir/env/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception 465. self.raise_uncaught_exception(exc) File "/home/schoolsite/schoolsitedir/env/lib/python3.6/site-packages/rest_framework/views.py" in raise_uncaught_exception 476. raise exc File "/home/schoolsite/schoolsitedir/env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch 502. response = handler(request, *args, **kwargs) File "/home/schoolsite/schoolsitedir/env/lib/python3.6/site-packages/rest_framework/decorators.py" in handler 50. return func(*args, **kwargs) File "/home/schoolsite/schoolsitedir/Homepage/api/views.py" in registration_view 25. account = serializer.save() File "/home/schoolsite/schoolsitedir/Homepage/api/serializers.py" in save 30. … -
Making Django database agnostic best practices
I have a Django app that I am building that others will likely view/fork on github. Currently my database setup is as below. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'brightestDjango', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost' } } I changed the USER/PASSWORD since it's sensitive data, but the issue is that others who try to run this app will need to fix this information and create a new db assuming they have postgresql. What is best practice for this? Do I just label the above as is and note in documentation that they must change their USER/PASSWORD to their own, or are there default settings or handy tools that allows others to more immediately interact with the app? -
Django. Annotate wtih Count parameter doesn't works
I have 2 models: class Parameter(models.Model): name = models.CharField('Название', max_length=50) class ProductParameter(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Продукт', related_name='parameters') parameter = models.ForeignKey( 'Parameter', on_delete=models.CASCADE, verbose_name='Параметр', related_name='product_parameters' ) I do the queryset for getting all parameters that has more than 1 ProductParameter: parameters = Parameter.objects.annotate( count=Count('product_parameters') ).exclude(count__lte=1) But that's not working. When a parameter obj has 2 ProductParameter objects, the count equals to 1. When I use the expression below, all works: parameters = [param for param in Parameter.objects.all() if param.product_parameters.count() > 1] Where is my error? -
Django- Celery periodic task to send user email only 1 time
In my case all users got emails, every n minutes. How to do better? Create some checkbox field to check if emails were send or not , I know. Interesting in any other good ideas please tasks.py @periodic_task(run_every=(crontab(minute="*/5")), name="send_email") def send_email(): post = Post.objects.filter(done=True) for post in posts: try: send_mail( subject=f'Some subject "{post.site.name}".', message="ty for reporting.", from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[post.site.email], ) except Exception as e: print(e) -
What is the best way for connecting Django models choice fields with React js select options
I find myself stuck in dealing with Django models choice fields and react select options. May someone kindly help. This is my models code: class AccountType(models.Model): category = models.SmallIntegerField(choices=( (AccountCategories.ASSET, 'Asset'), (AccountCategories.LIABILITY, 'Liability'), (AccountCategories.EQUITY, 'Equity'), (AccountCategories.REVENUE, 'Revenue'), (AccountCategories.EXPENSE, 'Operating Expense') )) classification = models.SmallIntegerField(choices=( (AccountClassifications.NONE, ''), (AccountClassifications.CURRENT, 'Current'), (AccountClassifications.NONCURRENT, 'Long-Term') )) I cant seem to figure out on how to make these choices to be my select options in React form. Was thinking maybe the solution may be in validating or cleaning these choices in my serializers but I am stuck on the how especially on linking with a React Form. Thanks in advance -
How to make an automatic Django field?
I have a model of a project and am trying to get it to be set automatically by simply adding +1 every time a new project is created: class project(models.Model): project_number = models.PositiveSmallIntegerField(primary_key=True) -
How to test Django admin?
I'm trying to test usage of the admin site. Simple tests, if viewing, adding, changing and deleting stuff works. This is my code so far: class BaseAdminTestCase(TestCase): """ Base admin site test case, create admin user and login. """ def setUp(self): self.client = Client() self.login() def create_user(self): username, password = 'admin', 'test' user = User.objects.get_or_create( username=username, email='admin@test.com', is_superuser=True )[0] user.set_password(password) user.save() self.user = user return username, password def login(self): username, password = self.create_user() self.client.login(username=username, password=password) class ClientAdminTestCsae(BaseAdminTestCase): def test_get_client_list(self): page = '/logistirio/client/' resp = self.client.get(page, follow=True) assert resp.status_code == 200 def test_create_client(self): resp = self.client.post( reverse('admin:logistirio_client_add'), { 'title': "mr", 'name': "Toni", 'surname': "Montana", 'phone1': "6969696969", 'email1': "ant@gmail.com", }, ) print(resp) firstClient = client.objects.filter(pk=1).exists() self.assertTrue(firstClient) The first test works, the second one doesn't, and I'm not sure why. The client object has inlines, if this is a problem. Has anyone any experience with this? Thank you. -
Displaying categories with objects in Django using generic.ListView
There are two related tables in the database, here are the files models.py: class Category(models.Model): name = models.CharField(max_length=40) class Movie(models.Model): name = models.CharField(max_length=40) program = models.ForeignKey(Category, on_delete=models.CASCADE) views.py: from django.views import generic class MovieListView(generic.ListView): model = Movie context_object_name = 'movie_list' now = timezone.now() queryset = Movie.objects.filter(start_datetime__gte=now).order_by('start_datetime') template_name = 'movie_list.html' base.html: {% for movie in movie_list %} {{ movie.name }} {% endfor %} After the name of the category, need to display a list of all films in this category, keeping the existing filter and sorting. How is this done the classic Django way? -
How to make a singup view using Class based views in Django?
When I started to use Django, I was using FBVs ( Function Based Views ) for pretty much everything including signing up for new users. But as I delved deep more into projects, I realized that Class-Based Views are usually better for large projects as they are more clean and maintainable but this is not to say that FBVs aren't. Anyway, I migrated most of my whole project's views to Class-Based Views except for one that was a little confusing, the SignUpView. -
Xhtml to pdf: Error with ckeditor styling
I am using Xhmtl to pdf library for converting html to pdf. All is working fine except when i use some styling in data with CKEditor than the error comes. Error: {TypeError}sequence item 1: expected str instance, tuple found I think reason is this type of styling: color:hsl(60,75%,60%); How can i get rid of it thanx. -
Adding custom domain name to Heroku for Django App
I published my site with example.herokuapp.com last night, I bought a domain today and I want to use this domain. I searched a lot of videos and resources on the internet and tried many ways but I couldn't do it. The result is Bad Request (400). The application was written in Django. This is my first deployment experience and I am waiting for your help. ALLOWED_HOSTS = ['*'] I deploy the application via GitHub.ALLOWED_HOSTS = ['*'] I changed it but my application crashed. I saved it with roll back. -
How to validate CSV file upload on the fly in Django using a custom class-based validator?
I have an upload form used to inject CSV file content into the database. So far I'm struggling with validation itself. I switched from function based validator to class based validator so I could pass argument to the validator itself to make it reusable. views.py @login_required def contact_import(request): if request.method == 'POST' and request.FILES['file']: form = ContactImportForm(request.POST,request.FILES) if form.is_valid(): post_result = form.save(commit=True) return redirect("/contacts/") else: form = ContactImportForm() return render(request,'contact_import_form.html',{ 'form': form }) forms.py class ContactImportForm(forms.Form): headers = ["lastname","firstname","email"] file = forms.FileField(label='Select your CSV File',validators=[CsvFileValidator(headers)]) def clean_file(self): file = self.cleaned_data['file'] return file validators.py class CsvFileValidator(object): def __init__(self, headers): self.headers = headers def __call__(self,file): # Extension check file_extension = os.path.splitext(file.name)[1] valid_extensions = [ ".csv", ".CSV"] if not file_extension.lower() in valid_extensions: msg = "Invalid file, select a valid CSV file" raise ValidationError("{}".format(msg), status='invalid') # File content check try: csv_format = csv.Sniffer().sniff(file.read(1024)) file.seek(0,0) except csv.Error: msg = "Invalid file, select a valid CSV file" raise ValidationError("{}".format(msg), status='invalid') csv_reader = csv.reader(file.read().splitlines(), dialect=csv_format,delimiter=";") for r_index, row in enumerate(csv_reader): # CSV headers check if r_index == 0: if sorted(self.headers) != sorted(row): msg = "Missing or invalid headers" raise ValidationError("{}".format(msg), status='invalid') # Skip blank line if not "".join(str(field) for field in row): continue return True contact_import_form.html HTML … -
ValueError: Cannot query "username": Must be "User" instance
I recently migrated my project to a new host using nginx/gunicorn instead of Apache2. The project has a custom user model with User and Profile classes (among others). The same project runs without error in the old production. But in the new environment we got ValueError when a registered user updated his profile. The code are exactly the same. However we upgraded some packages, e.g. Django 3.0.7 to 3.0.8, and may be a few others that seems harmless. Here is the error output Request Method: GET Request URL: http://157.245.210.148/update_profile/?next=/&att= Django Version: 3.0.8 Exception Type: ValueError Exception Value: Cannot query "xxx": Must be "User" instance. The view method that threw the error: def update_profile(request): user = auth.get_user(request) <------- We also tried user = request.user if not request.user.is_authenticated: return HttpResponseRedirect('/login/') myprofile = Profile.objects.get(user=user) <------ error here if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): profile_obj = form.save(commit=False) Here is the models (simplified): class User(AbstractBaseUser): username = models.CharField(max_length=255, unique=True) fullname = models.CharField(max_length=255, null=True) email = models.EmailField(verbose_name='email address', max_length=255) #, unique=True,) tier = models.ForeignKey(Tier, null=True, default=1, db_column='tier',on_delete=models.DO_NOTHING) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) confirm_email = models.CharField(max_length=100, blank=True) photo_credit_name = models.CharField(max_length=100, blank=True) current_credit_name = models.OneToOneField(Photographer, blank=True, null=True, on_delete=models.DO_NOTHING) specialty = models.CharField(max_length=500, null=True,blank=True) portfolio_site = … -
Developing web applicaton based on Django, PostgreSQL, Leaflet
I'm new guy to web development and this current task is some sort of training that I've made for myself. But at the current moment I kinda lost and don't understand what I suppose to do: don't know where should I move on. The idea is to create web application with two instruments. One of theme allows user to add point to the web map and store this point to the database. Another allows user to get information about raster value (in this case it's elevation of raster) And the question is: how can I perform this kinda of interaction between app and database. I've connected my DB through django interface and can add point through admin panel. But how I can make similar instrument for user side ? I don't asking for code. Just a direction which I should go. Also, is there is any alternative to import DEM raster rather than through leaflet-geotiff And should I deploy my DEM through app like mapserver or geoserver so my web-app can see it from browser side ? Also appreciate any literature and examples of similar problems cause I didn't find anything which will help me through this task Thank you … -
Django FormWizard Multiple submissions against same form
I am using Djang FormWizard and have scenario where i have to do 1-to-Many save. I have one company and possibly many office holders. Since this is a web based form people can fill this differently. Your company can have 1 office holder and my company can have 10 office holders. The number of forms is 3(for discussion sake). 1)First form is company detail 2)secondly form is office holders. 3)third form is a summary of what u have filled so far and a button asking if you want to add more office holders. Using FormWizard i cant seem to figure out how to implement this. In in a regular scenarios i would have setup a link to the from 2, something like myurl.com?action=addmore and then rendered the form 2 accordingly I can use wizard_goto_step in template but then i cant seem to figure out how to pass a conditional argument.(It cannot be a checkbox) has to be a button or a link. Any ideas? -
Django CMS - Empty page structure
I'm completely new to Django CMS. This is in continuation with this issue: Django CMS - Unable to modify structure of a newly added webpage I have added a new module to an existing Django project and created a new Html page. This is the templates configuration in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'site_cms', 'templates'), ], 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.template.context_processors.csrf', 'django.template.context_processors.tz', 'sekizai.context_processors.sekizai', 'django.template.context_processors.static', 'cms.context_processors.cms_settings', 'core.context_processors.request_info', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader' ], }, }, ] In the new page, I'm extending the home page of the website as I've seen other pages do. This is the home page home.html (/core/templates/core/home.html): {% load i18n easy_thumbnails_tags static %} <!DOCTYPE html> <html lang="en"> <head> {% load staticfiles i18n menu_tags%} </head> <main> <div class="container"> {% block content %} This is my new page newpage.html (/newpage/templates/newpage/newpage.html) {% extends "home.html" %} {% load easy_thumbnails_tags i18n static core_filters bootstrap4 %} {% block content %} {% load bootstrap4 %} <div class="container"> {% placeholder "content" %} After creating the new page, I added it to the website main-menu through the Django CMS bar. I selected the template for the page to the one the parent (home) uses. When … -
Django model looping relationship
i have a problem for django model. i have location, machine, and part item. One location has many Machine. Every machine has many part Item. Different machine can has same part item. Part item has default file/document/photo. Every machine that use part item has own part item file/document/photo. Part item has default maintenance procedure, but for Certain machine, maintenance procedure for part Item can be different with the default or same as the default. class location(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class machine(models.Model): name = models.CharField(max_length=100) descirption = models.CharField(max_length=255) location = models.ForeignKey(location, on_delete=models.CASCADE, related_name='machine') class partitem(models.Model): itemNumber = models.CharField(max_length=100) descirption = models.CharField(max_length=255) machine = models.ForeignKey(machine, on_delete=models.CASCADE, related_name='machine') procedureDefault = models.CharField(max_length=255) attachmentDefault = models.FileField(upload_to='uploads/%Y/%m/%d/') how do i define the attachment and procedure of part item if it different from default for certain machine? procedureForEachMachine = models.CharField(max_length=255) attachmentForEachMachine = models.FileField(upload_to='uploads/%Y/%m/%d/')