Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Foreign key in custom user manager
I'm trying to create a custom user model in django, using a ForeignKey as required_field. My Manager is as follows: from django.contrib.auth.models import BaseUserManager from .models import State class CustomUserManager(BaseUserManager): def create_user(self, email, first_name, state, password=None, **extra_fields): email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, state=State(pk=state), **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, first_name, state, password=None, **extra_fields): email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, state=State(pk=state), **extra_fields) user.set_password(password) user.save() return user When trying to use createsuperuser via manage.py, the following exception happens from .models import State ImportError: cannot import name 'State' from 'account.models' The State class exists in account.models, the module is called account I don't know how else to create the user, as a State instance is required. -
How to architect Apollo Server with Django
I had build a backend server via using Django-REST framework (For JWT authentication), I planned to apply GraphQL in my project too. When I start to learn Graphene-Python, I found out that Apollo server is having a bigger community and I plan to apply it in my project instead of using Graphene-Python. But i cant figure out how to architect my project. What I think is use Django-REST to allow my user to perform CRUD. And data retrieve using GraphQL (Apollo Server). I hope to architect my project in a long run. How can I use JWT generated by Django-REST and use in the Apollo server too? Is constructing project in this way a good choice? Or should I stick with Graphene-Python and Django? My question maybe broad, but I really want some comment from people with more experience before I put my step in. Thanks in advance. -
Python Django How to upload new image on update using custom form
I am new with python django and exploring the CRUD functionality using a custom form, i was able to edit other information successfully using below codes Model.py def image_path(instance, filename): basefilename, file_extension = os.path.splitext(filename) chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890' randomstr = ''.join((random.choice(chars)) for x in range(10)) _now = datetime.now() return 'profile_pic/{year}-{month}-{day}-{imageid}-{basename}-{randomstring}{ext}'.format( imageid=instance, basename=basefilename, randomstring=randomstr, ext=file_extension, year=_now.strftime('%Y'), month=_now.strftime('%m'), day=_now.strftime('%d') ) class Profile(models.Model): profile_fname = models.CharField(max_length=200, verbose_name="first name") # character field profile_lname = models.CharField(max_length=200, verbose_name="last name") profile_email = models.EmailField(unique=True, max_length=200, verbose_name="Email") profile_image = models.ImageField(upload_to=image_path, default='profile_pic/image.jpg') pub_date = models.DateTimeField('date registered') # DateTimeField def __str__(self): return self.profile_email View.py def processedit(request, profile_id): profile = get_object_or_404(Profile, pk=profile_id) try: profile_info = Profile.objects.filter(id=request.POST['id']).update(profile_email=request.POST['email'], profile_fname=request.POST['fname'], profile_lname=request.POST['lname'], profile_image=request.FILES['image']) except (KeyError, Profile.DoesNotExist): return render(request, 'profiles/detail.html', { 'profile': profile, 'error_message' : "Problem updating record", }) else: return HttpResponseRedirect(reverse('profiles:detail', args=(profile.id,))) I assumed that profile_image=request.FILES['image'] will update the profile_image field but it only updated the database and did not move the selected image, is there another way to handle image using a custom form? -
How to use Django Cycle for displaying Two post on one row?
Following code giving me the output of one post in one row, how can I change it to display two posts in one row ? <div class="col-md-4 mt-3 left"> {% for post in disease_list %} <div class="card mb-4"> <div class="card-body"> <h6 class="card-title"><a href="{% url 'disease_detail' post.slug %}"> {{ post.title }}</a></h6> </div> </div> {% endfor %} </div> Does Cycle method is good to implement here ? If Yes then how ? -
How to create unique_together on two date fields in Django model
I have a table in my Django project where the key field must depend on a combination of two dates. The table is: models.py class basicPrice(models.Model): to_charge = models.DecimalField(max_digits=5, decimal_places=2, verbose_name='Basic Charge') from_date = models.DateField(null=True, verbose_name='From date') to_date = models.DateField(null=True, verbose_name='To date') class Meta: unique_together = [['from_date', 'to_date'],] And in my forms.py, I am doing: def validate_unique(self): try: self.instance.validate_unique() except ValidationError: self._update_errors({'from_date': _('Record exists for the combination of key fields.')}) My requirement is that a new record can not be created for the same combination of dates, from_date and to_date. However, with the current arrangement I am getting validation error for the second record onwards (i.e. the first record was created as expected, but creating subsequent ones is raising error), even though I am keeping the dates different. I tried this solution but still stuck at the very same issue. My question is: How do I create a unique_together for my model based on two date fields. -
Can snmpreceiver or pysnmp module be used to collect data for a printer monitoring system using django?
i am trying to generate SNMP data for printers for later analysis using a prediction algorithm to be able to fortell emanating faults in printers before they actually occur. I seek advice on how best i could collect the data and prepare it in a dataset format like .csv so as to feed it into my classifier. Would really appreciate any help rendered Cheers! -
Problem witth uploading and viewing images with django
Hope someone could help me, Thanks! I can't figure out what is wrong with my code. I already read tons of articles about this problem but none of 'em have helped me. It's really simple, I'm trying to upload a dynamic image with django, but I keep having this problem. The 'cover' attribute has no file associated with it. ''' Environment: Request Method: GET Request URL: http://127.0.0.1:8000/band/ Django Version: 3.0.4 Python Version: 3.8.2 Installed Applications: ['search.apps.SearchConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\arian\Dev\db_vinili\src\dbvinili\search\templates\search\band.html, error at line 22 The 'cover' attribute has no file associated with it. 12 : <div class="cat"> 13 : <h2> BAND </h2> 14 : </div> 15 : 16 : 17 : {% for Info in object_list %} 18 : <div class="container"> 19 : 20 : <div class=album> 21 : <!-- insert an image --> 22 : <img src= " {{Info.cover.url}} " width="100%"> 23 : 24 : </div> 25 : 26 : 27 : <div class="info"> 28 : <!-- insert table info --> 29 : <table> 30 : <tr> 31 : <td> Band </td> 32 : <td> {{Info.band}}</td> Traceback (most recent call last): File "C:\Users\arian\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", … -
Error in for loop using jinja format in html5 file
I want to display a series of dynamic entries on my webpage.So i have used a for loop in my html5 file using jinja but keep getting this error. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.5 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 264: 'endfor'. Did you forget to register or load this tag? Exception Location: D:\anacondapython3\lib\site-packages\django\template\base.py in invalid_block_tag, line 534 Python Executable: D:\anacondapython3\python.exe Python Version: 3.7.4 Python Path: ['E:\\coding\\fyp\\travel', 'D:\\anacondapython3\\python37.zip', 'D:\\anacondapython3\\DLLs', 'D:\\anacondapython3\\lib', 'D:\\anacondapython3', 'D:\\anacondapython3\\lib\\site-packages', 'D:\\anacondapython3\\lib\\site-packages\\win32', 'D:\\anacondapython3\\lib\\site-packages\\win32\\lib', 'D:\\anacondapython3\\lib\\site-packages\\Pythonwin'] Server time: Thu, 26 Mar 2020 12:29:39 +0000 Error during template rendering In template E:\coding\fyp\travel\templates\index.html, error at line 264 Invalid block tag on line 264: 'endfor'. Did you forget to register or load this tag? 254 <div class="destination_image"> 255 <img src="images/destination_1.jpg" alt=""> 256 <div class="spec_offer text-center"><a href="#">Special Offer</a></div> 257 </div> 258 <div class="destination_content"> 259 <div class="destination_title"><a href="destinations.html">{{dest.name}}</a></div> 260 <div class="destination_subtitle"><p>{{dest.dest}}</p></div> 261 <div class="destination_price">{{dest.price}}</div> 262 </div> 263 </div> 264 {% endfor %} 265 266 267 268 </div> 269 </div> 270 </div> 271 </div> 272 </div> 273 274 <!-- Testimonials --> the part i want to make dynamic using for loops look like this: <!-- Destinations --> <div class="destinations" id="destinations"> <div class="container"> <div class="row"> <div class="col text-center"> <div class="section_subtitle">simply … -
Unknown custom command in django 2.2
I have a problem with running the command in django 2.2. The application is in INSTALLED_APPS. I receive a message: Unknown command: 'my_command' Type 'manage.py help' for usage. Below is the structure of the project: project/ app/ managment/ commands/ my_command.py models.py views.py ... my_command.py from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'My custom command' def handle(self, *args, **options): code here -
How to make that one user can have multiple picks but only one pick can have 5 heroes - DjangoModel
I know what I need. Problem is that I don`t have a clue how to write it. I want that user that register on website can have multiple drafts, like draft1, draft2, draft3, etc. but all the draft`s cant have more then 5 heroes. In my posgresql i have one user and 119 heroes at this moment that have their IDs. I tried something like this : models.py from django.db import models from users.models import User from heroes.models import Hero from django.core.exceptions import ValidationError class UserPick(models.Model): draft = models.IntegerField() def __str__(self): return str(self.draft) def save(self, *args, **kwargs): if self.__class__.objects.filter(draft=self.draft).count() >= 5: return None return super().save(*args, **kwargs) class UserDrafts(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_id") pick = models.ForeignKey(UserPick, on_delete=models.CASCADE) hero_id = models.ForeignKey(Hero, on_delete=models.CASCADE) def save(self, *args, **kwargs): if self.__class__.objects.filter(user_id=self.user_id).count() >= 5: raise ValidationError('Maximum five picks are allowed per user') return super().save(*args, **kwargs) def __str__(self): return self.user_id.username class Meta: verbose_name = "UserDraft" verbose_name_plural = "UserDrafts" As title say i want to have that one user can have multiple drafts but all the draft need to have 5 heroes exactly or it error will be thrown. I`m trying to figure it out in my head but it wont work :) What i mean is … -
Is there a way of chaining multiple models and query them in a single response?
Hi i'm new to Django and need a little help. I'm building an API using Django and Graphene for a news site. I created multiple post models for each news cast so that each news cast can just view their corresponding model in the Django Admin panel. The problem i'm facing is that i need to chain or combine all the models for a single query so i can display all of the posts created from all of the models. In this example i imported both of the post model in the schema file. Is this the right approach if yes is there a way of chaining them into a single query? import graphene from graphene_django import DjangoObjectType from .models import News, Sport from users.schema import UserType from graphql import GraphQLError from django.db.models import Q class NewsType(DjangoObjectType): class Meta: model = News class SportType(DjangoObjectType): class Meta: model = Sport class Query(graphene.ObjectType): news = graphene.List(NewsType) sports = graphene.List(SportType) def resolve_news(self, info): return News.objects.all() def resolve_sports(self, info): return Sports.objects.all() Thank you! -
Broken Requirements.txt?
To give all details about my issue it's probably best to give a slight backstory. For the past few months I've been working on a Django project at work. Because of recent obvious events I'm working from home, thus I had to transfer the project to my home PC (using Git). At work I made a requirements.txt, which I would use to get all the packages at home. This worked, but it wouldn't install at home, and I soon found out it was because the requirements.txt had a package that was invalid and didn't exist. This is: pkg-resources==0.0.0 I deleted it from the requirements file and everything went fine afterwards. Fast forward to now: I'm trying to deploy the project on our amazon beanstalk, and its failing with this error: 2020-03-26 12:03:10 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2020-03-26 12:03:13 ERROR [Instance: i-0xxxxxxx] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2020-03-26 12:03:13 INFO Command execution completed on all instances. Summary: [Successful: … -
How do I can I get data from model functions to appear in Django Admin?
How can I get data for get_num_states to appear as a field, showing number of states a country has, in Django Admin for each record I have of a country? I know that get_num_states seems to be working as I am able to display info from the function in html templates. However I currently don't see it displaying in Django Admin. class Country(models.Model): country_name = models.CharField(max_length=50) create_date = models.DateTimeField() def get_num_states(self): return State.objects.filter(country=self.id).count() def __str__(self): return self.country_name class State(models.Model): state_name = models.CharField(max_length=50) country = models.ForeignKey(Country, on_delete=models.CASCADE) -
How to get model field value from model and field in django template?
I would like to create a template for printing table. I was thinking that when I put all objects of specific model into rows and specific fields of that model into columns I could get values in cells. This is my idea: # views.py def users(request): all_users = models.CustomUser.objects.all() fieldnames = ['id', 'email', 'first_name', 'last_name', 'department'] fields = [all_users[0]._meta.get_field(field) for field in fieldnames] context = { 'rows': all_users, 'columns': fields, } return render(request, 'table.html', context=context) # table.html <table> <tr> {% for col in columns %} <th>{{ col.verbose_name }}</th> {% endfor %} </tr> {% for row in rows %} <tr> {% for col in columns %} <td>{{ row|col }}</td> # or row.col or row:col {% endfor %} </tr> {% endfor %} </table> How can I get there? Is this the right way of thinking and doing? Or should I somehow manage the data before rendering? -
Pop up a table using ajax in Django
In my project I am trying to add a pop up in a table row but by javascript only Its not working. I dont understand how to add the ajax request for the pop up. The which I want to up but if I add this to then It totally conflict . and If I am adding at the end of the div then I am not able to use the value because it is outside of the for loop. Here is the template: {% extends 'admin-template/base.html' %} {% load static %} {% block content %} <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Orders</title> </head> <body> <div class="container-scroller"> <!-- partial:../../partials/_navbar.html --> {% include 'admin-template/_navbar.html' %} <!-- partial --> <div class="container-fluid page-body-wrapper"> <!-- partial:../../partials/_sidebar.html --> {% include 'admin-template/_sidebar.html' %} <!-- partial --> <div class="main-panel"> <div class="content-wrapper"> <div class="page-header"> <h3 class="page-title"> Extras</h3> <!--<nav aria-label="breadcrumb"> <a href="editusers.html"> <button type="submit" class="btn btn-gradient-primary mb-2">Add Products</button> </a> </nav>--> </div> <div class="row"> <div class="col-lg-12 grid-margin stretch-card"> <div class="card"> <div class="card-body"> <!--<h4 class="card-title">Bordered table</h4> <p class="card-description"> Add class <code>.table-bordered</code>--> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}><font color="{{ message.tags … -
how can I render a view only when a certain field is True? - Django
I have created detailed views for the posts in my Django-based blog using the DetailView generic class and everything works fine so far. The problem, however, is that I have a field in my post model that is used to set the status of the posts (active, inactive, blocked) and I only want to render the detailed views when the status is active. If anyone knows of a way to achieve this, please let me know and I ask that you be as detailed as possible. Thanks -
Media images are not loading in template page when DEBUG=false in setti gs.py in django
facing error while debug is true in production I hosted my website but there is a problem with the media files. The media files are not loading in the templates because I set DEBUG = True , in my settings.py file. What should I do now to fix this error ? -
Load CSV file in Django view and turn into HTML table
I have this view code def datatable(request, file): csv_fp = open(f'data/{file}.csv', 'r') reader = csv.DictReader(csv_fp) headers = [col for col in reader.fieldnames] out = [row for row in reader] return render(request, 'datatable.html', {'data' : out, 'headers' : headers}) and here's my template <table id="table" class="display" style="width: 100%;"> <thead> <tr> {% for header in headers%} <th>{{ header }}</th> {% endfor %} </tr> </thead> <tbody> <tr> {% for row in out%} <td>{{row}}</td> {% endfor %} </tr> </tbody> </table> I'm trying to turn this CSV into a table in my Django template. The headers are done correctly, but the rows are off. Is there a better way to read the rows so it'll go into tbody easier? -
Django Signals check when all post_save completed and the run final function
Is there a way to catch all post_save signals (initiated from the current request) and to check when all of them are finished? If all post_save completes then run final function. Example: from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=Model1) @receiver(post_save, sender=Model2) @receiver(post_save, sender=Model3) def example_function(sender, instance, created, **kwargs): if created and isinstance(instance, Model1): run_model1_fun() if created and isinstance(instance, Model2): run_model2_fun() if created and isinstance(instance, Model3): run_model3_fun() #IF all post_save completed run_final() -
Exclude .env directory from flake8 tests?
I'm getting thousands of flake8 errors stemming from my local .env. An example of some of the error messages: ./env/lib/python3.7/site-packages/pip/_vendor/pyparsing.py:3848:80: E501 line too long (85 > 79 characters) ./env/lib/python3.7/site-packages/pip/_vendor/pyparsing.py:3848:84: E202 whitespace before ')' ./env/lib/python3.7/site-packages/pip/_vendor/pyparsing.py:3855:51: E201 whitespace after '(' ./env/lib/python3.7/site-packages/pip/_vendor/pyparsing.py:3855:65: E202 whitespace before ')' ./env/lib/python3.7/site-packages/pip/_vendor/pyparsing.py:3858:50: E201 whitespace after '(' ./env/lib/python3.7/site-packages/pip/_vendor/pyparsing.py:3858:78: E202 whitespace before ')' ./env/lib/python3.7/site-packages/pip/_vendor/pyparsing.py:3861:31: E231 missing whitespace after ',' ./env/lib/python3.7/site-packages/pip/_vendor/pyparsing.py:3865:1: W293 blank line contains whitespace ./env/lib/python3.7/site-packages/pip/_vendor/pyparsing.py:3866:1: E302 expected 2 blank lines, found 1 My directory looks like this: My flake8 file looks like this: [flake8] exclude = migrations, __pycache__, manage.py, settings.py, How can I add my env file contents to the exclude list in flake8? I've tried adding: ./env, In the flake8 file but it hasn't stopped the errors. -
Posting Foreign key to DRF Api using React
I want to Post the Company object using React. However, the Foreign key seems to be failing. I'm not sure how so I pass the data for address and invoice address. Below is my code models.py class Address(models.Model): id = models.UUIDField() city = models.CharField(max_length=20, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Company(models.Model): id = models.UUIDField() address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name='address') invoice_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name='invoice_address') serializers.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address exclude = ('id', 'created', 'modified') class CompanySerializer(serializers.ModelSerializer): address = AddressSerializer() invoice_address = AddressSerializer() class Meta: model = Company def create(self, data): #create address if it does not exist -
Django QuerySet evaluation on accessing elements via []
@pytest.mark.django_db def test_cats(self): CatFactory.create_batch(2) cats = Cat.objects.all() self.assertNotEqual(cats[0], cats[1]) Why does this test case pass? Is this one of the cases when Django QuerySets get evaluated (iteration, slicing, etc.)? -
django-rules: where to put the rules/predicates?
Stupid question but when using django-rules for usage in RulesModel, where to I put my custom predicates? Do I create a separate rules file and import it into models.py? -
Djongo takes wrong Database URL
I'm using djong (mongodb) as my database backend for a django application. I configured in the settings.py : 'HOST': '172.17.0.2', 'PORT': 27017 (172.17.0.2) is the ip of the docker container the mongodb is running in. If I now run python3 manage.py runserver I get the error: pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused which makes sense because the mongodb is not runnig on localhost. But why dows pymongo think that ? Thanks ! -
Django: How to properly render SplitDateTimeWidget for DateTimeRangeField
Online material (docs, code) for django's (postgres-specific) range fields is lacking. I tried overriding the widget for DateTimeRangeField, but can't get it to show 2 pretty date-time inputs using SplitDateTimeWidget (start datetime, end datetime) for my field. I have settled for overriding the type attribute and getting the following okayish output, without this, it's just plain type="text". Current behaviour: Expected behaviour: My models.py from django.db import models from django.contrib.postgres.fields import DateTimeRangeField class MyModel(models.Model): ... datetimerange = DateTimeRangeField() ... My admin.py from django import forms from django.contrib import admin from django.contrib.postgres.forms.ranges import RangeWidget, DateTimeRangeField class MyModelAdminForm(forms.ModelForm): class Meta: model = models.MyModel fields = "__all__" widgets = { "datetimerange": RangeWidget( forms.SplitDateTimeWidget( date_attrs={"type": "date"}, time_attrs={"type": "time"}, ), ) } @admin.register(models.MyModel) class MyModelAdmin(ListLimit, admin.ModelAdmin): form = MyModelAdminForm I tried playing around with (inheriting from) the default field DateTimeRangeField but no luck there as well.