Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I show auto_now_add field in Django admin?
I have a model (as below) and in that, I've set auto_now_add=True for the DateTimeField class Foo(models.Model): timestamp = models.DateTimeField(auto_now_add=True) From the doc, As currently implemented, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True set. Q: How Can I show this auto_now_add field in Django Admin? (by default Django Admin doesn't show auto_now_add fields) -
Where does the value 'form' in 'form.as_p' in Django template come from?
I know this question was asked before, but the accepted answer does not really answer the question: where `form.as_p`in django templates come from? In Django doc: Example myapp/views.py: from django.views.generic.edit import CreateView from myapp.models import Author class AuthorCreate(CreateView): model = Author fields = ['name'] Example myapp/author_form.html: <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> The question is, where does the template get the 'form' context from, since we did not explicitly define a render() function inside the AuthorCreate class? Thanks. -
Django: Select a valid choice. <choice> is not one of the available choices
I'm trying to make use a choice field to all users to add permissions to a role. The permissions are defined in their own class and are displayed in the drop-down box correctly, however when submitting the form, it says that the option selected isn't an available choice. forms.py from django import forms from .models import RolePermission, Permission class AddPermissionForm(forms.ModelForm): class Meta: model = RolePermission fields = ['permission'] permission = forms.ChoiceField(choices=Permission.choices) def __init__(self, *args, **kwargs): super(AddPermissionForm, self).__init__(*args, **kwargs) self.fields['permission'].widget.attrs.update({'class': 'form-control'}) views.py def role_view(request, role_id): role = Role.objects.get(id=role_id) add_permission_form = AddPermissionForm(request.POST) if request.method == 'POST' and add_permission_form.is_valid(): new_permission = add_permission_form.cleaned_data['permission'] # is_already_permission = RolePermission.objects.filter(role_id=role_id, permission=new_permission) # if is_already_permission: new_role_permission = RolePermission(role_id=role_id, permission=new_permission) new_role_permission.save() return redirect('core:role_view role_id=role_id') return render(request, 'role_view.html', {'role': role, 'form': add_permission_form}) Permissions class class Permission(models.TextChoices): PAGE_CREATE = 111 PAGE_EDIT = 112 PAGE_PUBLISH = 113 PAGE_DELETE = 114 I've tried changing the choice field to a select field, but that doesn't solve the problem. -
Use a single function for multiple serializer fields with different arguments
I have a serializer for a model with an image field, for which I have saved multiple different sized thumbnail images. I access them by returning their URL using the SerializerMethodField: class GalleryImageSerializer(serializers.ModelSerializer): image_sm = serializers.SerializerMethodField() image_md = serializers.SerializerMethodField() image_lg = serializers.SerializerMethodField() image_compressed = serializers.SerializerMethodField() def get_image_sm(self, obj): return default_storage.url(f'{splitext(obj.image.name)[0]}/sm.jpg') def get_image_md(self, obj): return default_storage.url(f'{splitext(obj.image.name)[0]}/md.jpg') def get_image_lg(self, obj): return default_storage.url(f'{splitext(obj.image.name)[0]}/lg.jpg') def get_image_compressed(self, obj): return default_storage.url(f'{splitext(obj.image.name)[0]}/compressed.jpg') This code works, but it kind of violates the "don't repeat yourself" guideline. As you can see, these are all duplicate SerializerMethodFields, with the only difference being the filename, eg 'lg.jpg', 'md.jpg', etc. I'd much prefer to have only one function that I call with an argument for the filename, as an example(pseudocode): class GalleryImageSerializer(serializers.ModelSerializer): image_sm = serializers.SerializerMethodField(filename='sm.jpg') image_md = serializers.SerializerMethodField(filename='md.jpg') image_lg = serializers.SerializerMethodField(filename='lg.jpg') image_compressed = serializers.SerializerMethodField(filename='compressed.jpg') def get_image(self, obj, filename=''): return default_storage.url(f'{splitext(obj.image.name)[0]}/{filename}') Currently I am unable to find any way to achieve this. Reading the source code of SerializerMethodField, it doesn't seem to support it. Is there any way to avoid creating duplicate functions for fields with arbitrary differences? -
Django Form Instance not showing the Uploaded Image
I am making a CMS platform in Django. I want to create the EDIT Post method so that anyone can edit their post. The main problem is the ImageField. As ImageField is required in Django's Models.py.So, while creating edit Post method for the user the ImageField, the image which was uploaded at the time of post creation, is empty. Here is Edit Post View def updatePost(request,pk): getEditPost= get_object_or_404(Post,pk=pk) if request.method=="POST": form = CkEditorForm(request.POST,request.FILES,instance=getEditPost) try: if form.is_valid(): form.save() except Exception as e: print(e) else: form = CkEditorForm(instance=getEditPost) context= { 'myForm':form, 'post':getEditPost, } return render(request,"post/editPost.html",context) Here is my forms.py class CkEditorForm(ModelForm): ..... ..... featuredImage = forms.ImageField(required=True) My models.py class Post(models.Model): ..... ..... featuredImage = models.ImageField(upload_to="featured_image/") -
sqlite3 works well in centos7 and python shell,but can't work in Uwsgi
I have a question need your help~ I have a django program run in a vps(centos7,django2.2),it works well with Nginx+Uwsgi. I edit three files(like a.py b.py c.py),and upload to the vps by winscp.exe,the program can't work now. I found these logs in the uwsgi.log file. File "/mnt/datasource/<privacy_hidden>/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 68, in <module> check_sqlite_version() File "/mnt/datasource/<privacy_hidden>/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 65, in check_sqlite_version raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). unable to load app 0 (mountpoint='') (callable not found or import error) I wrote "sqlite3 --version" in centos7 shell, it show version = 3.30.1 I wrote "python >>> import sqlite3 >>>print sqlite3.sqlite_version" it show version=3.30.1 I wrote "python manage.py runserver --noreload 0.0.0.0:80",it works well, no info show sqlite error. But the program can't work in uwsgi,I think the uwsgi.ini is correct. What can I do ? Thank you! -
How to save null value to date field
I have a model class League(models.Model): league = models.IntegerField(primary_key=True) season_start = models.DateField(null=True) I create objects from League model from json data which I extract from external API and save them to database. response = requests.get(leagues_url, headers = header) leagues_json = response.json() data_json = leagues_json["api"]["leagues"] for item in data_json: league_id = item["league_id"] season_start = item["season_start"] b = League.objects.update_or_create(league = league_id,season_start = season_start) Sometimes json data for season_start field have not value that is none and this none field cause error while I create league objects and save them to database. How I can solve problems caused by none values while saving them to date field -
Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001]. AWS Elastic Beanstalk
I tried following this tutorial https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html but after I execute eb create django-env I get this error: Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001]. AWS Elastic Beanstalk I found similar questions about the same issue but none of them solved the problem. I can't figure out what is wrong. I would greatly appreciate any insights. 🙂 -
How to get value from class Car to class Order
I'm need to get "Make" from class Car to "Make" in Order Class: class Car(models.Model): Make = models.CharField(max_length=64, null=True) #that i need to get in Order class Model = models.CharField(max_length=64, null=True) def __str__(self): return str(self.Make) + " " + str(self.Model) class Order(models.Model): #make = Car.Make - like that, but it is not work #make1 = models.ForeignKey(Car.Make, null=True, on_delete=models.SET_NULL) # it doesn't work either car = models.ForeignKey(Car, null=True, on_delete=models.SET_NULL) # that's work but it's give me return of __str__ def __str__(self): return str(self.Order_amount) + " " + str(self.Order_status) P.S. I just started to learn django, and I can not find any information about it -
Add more button in JS not woking
I am trying to add rows in my django template using JavaScript but it is not working like it's supposed to: HTML <html> <head> <title>gffdfdf</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="/static/jquery.formset.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <form id="myForm" action="" method="post" class=""> {% csrf_token %} <h2> Team</h2> {% for field in form %} {{ field.errors }} {{ field.label_tag }} : {{ field }} {% endfor %} {{ form.player.management_form }} <h3> Product Instance(s)</h3> <table id="table-product" class="table"> <thead> <tr> <th>player name</th> <th>highest score</th> <th>age</th> </tr> </thead> {% for player in form.player %} <tbody class="player-instances"> <tr> <td>{{ player.pname }}</td> <td>{{ player.hscore }}</td> <td>{{ player.age }}</td> <td> <input id="input_add" type="button" name="add" value=" Add More " class="tr_clone_add btn data_input"> </td> </tr> </tbody> {% endfor %} </table> <button type="submit" class="btn btn-primary">save</button> </form> </div> <script> var i = 1; $("#input_add").click(function() { $("tbody tr:first").clone().find(".data_input").each(function() { if ($(this).attr('class')== 'tr_clone_add btn data_input'){ $(this).attr({ 'id': function(_, id) { return "remove_button" }, 'name': function(_, name) { return "name_remove" +i }, 'value': 'Remove' }).on("click", function(){ var a = $(this).parent(); var b= a.parent(); i=i-1 $('#id_form-TOTAL_FORMS').val(i); b.remove(); $('.player-instances tr').each(function(index, value){ $(this).find('.data_input').each(function(){ $(this).attr({ 'id': function (_, id) { var idData= id; var splitV= String(idData).split('-'); var fData= splitV[0]; var tData= splitV[2]; return … -
Django: DatePicker with "django-widget-tweaks"
Good day, I'm trying "create" a DatePicker for one of my Inputfields in Django but it's not working! In my models.py: class Customer(models.Model): ... name = models.CharField() date = models.DateField() In my views.py: def Page(request): CustomerFormSet = modelformset_factory(Customer, fields='__all__') formset = CustomerFormSet (queryset=Customer.objects.none()) ... context = {'formset': formset} return render(request, 'app/base.html', context) In my template: {% extends 'app/base.html' %} {% load widget_tweaks %} <form actions="" method="POST"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form.id }} ... {% render_field form.name class="form-control" %} ... {% render_field form.date class="form-control" %} ... Now my first Inputfield works fine! It returns a fitting Field in Bootstraps "Form-Group"-Layout. But my InputField for Dates remains a simple TextInput with no calendar apearing to choose from. My Question is: am I doing something wrong or is it still impossible to obtain such a function in this way? Thanks and a nice evening to all of you. -
Setting the static files for Gunicorn Django deployment
I am trying to deploy a Django project with Nginx and Gunicorn, but Gunicorn cannot find the static files when I run it. My File structure is like this: user@testing:~$ ls db.sqlite3 main manage.py project static templates This is the nginx file for the project server { listen 80; server_name localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/static; } location / { include proxy_params; proxy_pass http://localhost:8000; } } Settings.py file STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' Thanks in advance! -
Render different templates for ListView
I have a ListView with some good functionality that i want to use from another app. The way i did it was using get_template_names. def get_template_names(self): referer = self.request.META['HTTP_REFERER'] if "/mwo/order/" in referer: return ['invent/use_part.html'] return ['invent/part_list.html'] Which i access from two different apps: path('inventory/', PartListView.as_view(), name='partlist'), ... path('mwo/order/<int:pk>/add_part/', PartListView.as_view(), name='add_part'), But it causes a bug if i use a direct link to 1st url from navbar and not from another app. Now i'm new to django and i'm pretty sure there should be a better way for this. What can i use instead of request referrer to render different template for ListView when i access it from another view. -
How to reuse effectively Django models
I have 2 type of Products , 1 is Product and 1 is sub product (child of product) but it will use same attribute of product . so my product table is like class Activity(models.Model): owner = models.ForeignKey(owner, on_delete=models.CASCADE) Name = models.CharField(max_length=50 , null=False, blank=False) and now it have like 4 tables of its properties for example I will paste 2 here. class workinfDatDates(models.Model): agenda = models.ForeignKey(Activity, on_delete=models.CASCADE) Date = models.DateField() and class BlockedDates(models.Model): agenda = models.ForeignKey(Activity, on_delete=models.CASCADE) blockDate = models.DateField() Now Sub Product is child of it like class SubActivity(models.Model): activity = models.ForeignKey(Activity, on_delete=models.CASCADE) subName = models.CharField(max_length=50 , null=False, blank=False) it should have same attributes like block dates and working dates etc . Now I should create new tables for it ? or is there any good way to use by including something to already defined tables ? -
Scale page to standard letter fomat with CSS
With regards to a webpage generated using Django, I would like to just print the page as a PDF in chrome. But when I do so, the view does not fit onto a standard 8.5/11 papersize. Is there a straightforward method of using CSS/HTML to scale items so that when you select print, it will fit everything onto a standard letter size sheet? So for desktops, if I have something like: @media only screen and (min-width: 768px) { /* For desktop: */ .col-1 {width: 8.33%;} .col-2 {width: 16.66%;} .col-3 {width: 25%;} } Would it be something like this for paper sizes? @media only screen and (min-width: 8.5in) { /* For printing: */ .col-1 {width: 8.33%;} .col-2 {width: 16.66%;} .col-3 {width: 25%;} } Or is there a much better way of accomplishing this? -
django v2.2:python manage.py runserver always reload
I have a question about django,can you help me ? I has write a django program ,it works well in my pc(windows10) and the vps(centos7,django 2.2). When I changed some code in 3 files,it works well in my pc,but can't work in the vps. I write this command in vps:" python manage.py runserver 0.0.0.0:80 ",it cames this: ***\a.py changed, reloading. Watching for file changes with StatReloader ***\b.py changed, reloading. Watching for file changes with StatReloader ***\c.py changed, reloading. Watching for file changes with StatReloader ***\a.py changed, reloading. Watching for file changes with StatReloader ***\b.py changed, reloading. Watching for file changes with StatReloader In the fact,these files only changed once,not changed after the command, It continued reloading... I must input " python manage.py runserver --noreload 0.0.0.0:80 ". I think it's something error ? Thank you! -
Django foreign key on many to many field
A company can have many job categories. A job has to be related to that company's job categories. How can I do it correctly? class Company(models.Model): job_categories = models.ManyToManyField(JobCategory,blank=False) class Job(models.Model): category = models.ForeignKey(Company, on_delete=models.CASCADE) -
Django - Datetime field shown as in admin panel
I have a model where I can create objects without a problem from the admin panel, I created a form to do the same directly within the website but I cannot manage to create an object directly from the form because of the error shown in the second picture. It is the "DateTimeField". Best case scenario, someone knows which piece of code is required for the form to display a menu ( as shown in picture 1 ) where the user can click which time and date he wants to. Thank you very much Second image: -
I cant install django using pip [closed]
I tried everything i found on the internet but it keeps showing like this enter image description here -
possible to use tuple, deconstruct with request.user, django?
Normally, I know tuple can be used as (email, username) = ('hello', 'user') that email will be equal to hello But I am wondering if I can do something like (email, username) = request.user so I do not have to keep on typing request.user and instead just use email and username like how javascript works. if I did the above, I would get an error saying TypeError: object is not iterable Thanks in advance for any suggestions and advices. -
Pythonanywhere TemplateDoesNotExist at /accounts/login/
When I run my app locally it works, but when I tried uploading it to pythonanywhere I get the following error: How do I fix this? If it will help my files are positioned like this: Music (the Django project folder) |_manage.py |_Music (the folder that contains settings file) |_App (the App itself with models, views etc. and my templates is here too) |_templates |_App |_registration |_login.html If you need more information I can upload it. -
I keep getting a naive date warning even though my model default uses timezoned date
Every time I run python manage.py test I get a warning saying that my model fields recived naive datetime: (venv) C:\Users\Philip\CodeRepos\Acacia2>python manage.py test journal.tests.test_models Creating test database for alias 'default'... C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\fields\__init__.py:1365: RuntimeWarning: DateTimeField Ledger.last_spreadsheet_update received a naive datetime (1970-01-01 00:00:00) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\fields\__init__.py:1365: RuntimeWarning: DateTimeField JournalEntry.last_integrity_check received a naive datetime (1970-01-01 00:00:00) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" However my models are configured with a default datetime that includes a timezone: class Ledger(models.Model): sort = models.PositiveIntegerField(default=0, blank=False, null=False) name = models.CharField(max_length=255) coa_sub_group = models.ForeignKey(COASubGroup, on_delete=models.PROTECT) is_reconcilable = models.BooleanField(default=False) spreadsheet_row = models.IntegerField(blank=True, null=True, unique=True) last_spreadsheet_update = models.DateTimeField(blank=False, null=False, default=datetime.datetime(1970, 1, 1, 0, 0, tzinfo=timezone('UTC'))) class JournalEntry(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False, blank=False) date = models.DateField(null=False, blank=False) # Data integrity check fields last_integrity_check = models.DateTimeField(blank=False, null=False, default=datetime.datetime(1970, 1, 1, 0, 0, tzinfo=timezone('UTC'))) integrity_check_fail = models.BooleanField(null=False, blank=False, default=0) What could I be doing wrong? -
403 CSRF verification failed Django when refresh url?
I have create a view that takes in a post request from my /login route, but after accepting the login post request and redirecting to /, when the user refresh the browser, I get a 403 CSRF failure code. How can i optimize my code so that if the user refreshes the browser it doesn't prompt the error? view def index(request): username = password = '' if request.method == 'POST': HttpReferrer = request.session.get('HttpReferrer') if HttpReferrer == '/login': username = request.POST['username'].lower().strip() password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: login(request, user) return index_(request) else: err = {"err_login": {"code": 404, "message": "The username and password combination do not match our records. Please double-check and try again."}} return render(request, 'auth/auth.html', err) -
How to get details of Current User in Django Rest Framework?
I'm working on my API based on Django Rest Framework. I've managed to add current user automatically on POST request via HiddenField. Now I want to return some additional information about current user within the GET request for blog post. I've tried to access this data from CurrentUserDefault() and via source='author.username'. First one doesn't work at all, the second option breaks on Save, because author wasn't provided in request. class BlogSerializer(serializers.HyperlinkedModelSerializer): author = serializers.HiddenField(default=serializers.CurrentUserDefault()) # author_name = serializers.ReadOnlyField(source=serializers.CurrentUserDefault().name) # author_username = serializers.ReadOnlyField(source='author.username') How can I access details of Current User and append it as read-only fields? -
Not able to match field from get_user_model in django
I am working on a Books inventory project, where users can add their books and others can see them. What I'm trying on home page to show all the books, but only the owner will see the 'Edit' and 'Delete' options. Others will see 'View Details' Option. I've used get_user_model() feature of Django to get the owner of the book when the user adds new book: ... class Book(models.Model): title =models.CharField(max_length =255) author =models.CharField(max_length =255) genre =models.CharField(max_length=255) date=models.DateTimeField(auto_now_add =True) owner =models.ForeignKey(get_user_model(),on_delete =models.CASCADE,) ... Now when I'm mapping the username of the user and the owner of the book, It's not working. This id the HTML template: ... {% for book in object_list %} <div class="card"> <span class="font-weight-bold">{{book.title}}</span> <span class="font-weight-bold">by {{book.author}}</span> <span class="text-muted">Genre: {{book.genre}}</span> <span class="text-muted">Owner: {{book.owner}}</span> <span class="text-muted">User: {{user.username}}</span> <div class="card-footer text-center text-muted"> {% if user.username == book.owner %} <a href ="{% url 'book_edit' book.pk %}">Edit</a> | <a href="{% url 'book_delete' book.pk %}">Delete</a> {% else %} <a href="#">Show Details</a> {% endif %} </div> </div> <br /> {% endfor %} ... I'm bringring both the username and owner seprately too for comparison. Still I'm getting show details for all the books. For Debugging I also tried equating both 'user.username' and 'book.owner' …