Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django debug toolbar Internal IP and static files
I installed Django debug toolbar and configured it as explained in the docs. I am in local development configuration. As soon as I set up Internal IPs as indicated I get the following error > FileNotFoundError at /admin/ [Errno 2] No such file or directory: '/home/odile/Documents/dev_logiciels/djangoE6000_techniques/E6000_stitch_techniques/static' Settings.py is ALLOWED_HOSTS = ['127.0.0.1', ' E6000.pythonanywhere.com'] INTERNAL_IPS = ['127.0.0.1'] ...... STATICFILES_DIRS = ( os.path.join(BASE_DIR, "E6000_stitch_techniques", "static"), ) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') When I comment the line Internal-IPS I get no error but no debug bar. ANy help welcomed. -
remote: -----> Python app detected remote: ! Requested runtime (Python 3.6.4) is not available for this stack (heroku-18)
remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Requested runtime (Python 3.6.4) is not available for this stack (heroku-18). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to sreeman-billing. remote: To https://git.heroku.com/sreeman-billing.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/sreeman-billing.git' i have found many answers to this question so i have changed the version to the stable version that heroku supports but heruko isnt taking the version from runtime file instead it detecting the version automatically please can someone suggest me any way to make this work -
How can I handle multiple image uploads without the server slowing down?
I followed this tutorial to upload multiple images with the help of AJAX. https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html To summarize it: I have a model that stores the images A form with an image field A view that handles the form in the post method Ajax sends a post request to this view We have a server on Heroku an the problem is if someone uploads a lot of images with a size of >5MB per image the site is extremely slow. Not only for the uploader but for every other user as well. How can you solve such a problem? -
RelatedObjectDoesNotExist at /login/
Everything was working fine now this is the error im getting i cant even login in to admin it gives the same error there too -
Django json field
Want to know the detail usage of django json field. Is it best idea for django modelform? If I use django json field, how to use edit view easily? New to django and didn't find good example of usage. -
Overriding serializer create for nested serializer with many=True
I am trying to have the ClassificationResultsSerializer many Classifications by having a nested serializer as shown below. class ClassificationSerializer(serializers.ModelSerializer): class Meta: model = Classification fields = ('summary', 'wiki_url', 'score') class ClassificationResultsSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') classifications = ClassificationSerializer(many=True) def create(self, validated_data): classifications_data = validated_data.pop('classifications', []) classificationresults = ClassificationResults.objects.create(**validated_data) for data in classifications_data: Classification.objects.create(classificationresults=classificationresults, **data) return classificationresults class Meta: model = ClassificationResults fields = ('id', 'owner', 'classifications') I defined the create method for ClassificationResultsSerializer to handle the nesting as per https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers, and I call the ClassificationResultsSerializer in my views as such: serializer = ClassificationResultsSerializer(data={ 'owner': self.request.user, 'classifications': [ { 'summary': 'a summary', 'wiki_url': 'url', 'score': 1 } ] }) but I keep getting psycopg2.IntegrityError: null value in column "classifications" violates not-null constraint The reason I'm sure is because I'm popping classifications in create, then creating the classificationresults without classifications now being null, despite the documentation telling me to do this. How am I able to solve this problem? -
AWS beanstalk deployment failed with exit status 1
I've been trying for several days now to set up Django under Amazon Web Services' Elastic Beanstalk. I am getting two error most of the time: 1.ERROR - Your WSGIPath refers to a file that does not exist. 2.ERROR: Your requirements.txt is invalid. Snapshot your logs for details. Here's directory structure: ├── .ebextensions │ └── django.config ├── .elasticbeanstalk │ ├── config.yml ├── .git ├── .gitignore ├── manage.py ├── saleor │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── requirements.txt Here is django.config file inside .ebextensions: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: saleor/wsgi.py packages: yum: gcc: [] python36-devel: [] gcc-c++: [] libffi-devel: [] postgresql93-devel: [] Error: ------------------------------------- /var/log/eb-activity.log ------------------------------------- File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/sandbox.py", line 47, in _execfile exec(code, globals, locals) File "/tmp/easy_install-q1ck81sr/cffi-1.11.5/setup.py", line 240, in <module> File "/usr/lib64/python3.6/distutils/core.py", line 163, in setup raise SystemExit("error: " + str(msg)) SystemExit: error: command 'gcc' failed with exit status 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 1101, in run_setup run_setup(setup_script, args) File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/sandbox.py", line 251, in run_setup raise File "/usr/lib64/python3.6/contextlib.py", line 99, in __exit__ self.gen.throw(type, value, traceback) File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/sandbox.py", line 198, in setup_context yield File "/usr/lib64/python3.6/contextlib.py", line 99, in __exit__ self.gen.throw(type, value, traceback) File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/sandbox.py", … -
View from forked django-oscar app not returning any data to template
I have forked the django-oscar catalogue app to alter the models being used. Not in a major way, and not in a way that would affect pulling data from the database as far as I can see. This seems to be supported by the fact the the django-oscar dashboard still works fine and lets me add and view products. My models.py from my forked app: from django.db import models class Collection(models.Model): name = models.CharField(max_length=50) prod_category = models.CharField(max_length=50) description = models.TextField() manufacturer = models.TextField() num_products = models.PositiveIntegerField() image_url = models.URLField() from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): collection = models.ForeignKey(Collection, on_delete=models.CASCADE, null=True) multiplier = models.DecimalField(max_digits=2, decimal_places=1, default='2.2') from oscar.apps.catalogue.models import * Here is my relevant view from my views.py def product(request): template = loader.get_template('/home/my_app/furniture_site/main_page/templates/main_page/product.html') prods = Product.objects.values_list('categories') context={'prods': prods} return HttpResponse(template.render(context)) I tried loading from the built in model and my forked model (commenting and uncommenting one or both), neither makes a difference: #from forkedoscarapps.catalogue.models import Product from oscar.core.loading import get_class, get_model Product = get_model('catalogue', 'product') And the code I am using in the template to display data from the view: {% for instance in prods %} <li><{{ instance.name }}</li> {% endfor %} There is at least one category called beds, which … -
Django Elastic-Search Integration Problems
im currently trying to implement elasticsearch on my app to search trough my posts. currently im doing this trough a direct query against the Postgres DB. urls.py ... #url(r'^search/$', myproject_views.globalsearch_local.as_view(), name='search'), # Use a local Search function (small-setup) url(r'^search/$', myproject_views.globalsearch_elastic, name='search'), # Use Elasticsearch (large-scale-setup) ... base.html (q as search input) ... <div class="globalsearch"> <form id="searchform" action="{% url 'search' %}" method="get" accept-charset="utf-8"> <label for="{{ categorysearch_form.category.id_for_label }}"></label><br> <div class="form-row align-items-center"> <div class="custom-dropdown">{{ categorysearch_form.category }}</div> <input class="class-search-input-fields" id="searchbox" name="q" required="required" type="text" placeholder="Search myproject"> <button class="btn btn-dark" type="submit"> <i class="fa fa-search"></i> </button> <div class="category-globalsearch"> ... views.py (search views) ... # Use Elasticsearch (large-scale-setup) def globalsearch_elastic(request): qs = request.GET.get('q') if qs: posts = PostDocument.search().query("match", titel=qs) else: posts = '' for post in posts: print(post) return render(request, 'myproject/search_results.html', {'object_list':posts}) # Use a local Search function (small-setup) class globalsearch_local(ListView): """ Display a Post List page filtered by the search query. """ model = Post paginate_by = 10 template_name = 'myproject/search_results.html' def get_queryset(self): keywords = self.request.GET.get('q') if keywords: query = SearchQuery(keywords) title_vector = SearchVector('title', weight='A') content_vector = SearchVector('content', weight='B') tag_vector = SearchVector('tag', weight='C') vectors = title_vector + content_vector + tag_vector qs = Post.objects.annotate(rank=SearchRank(vectors, query)).filter(rank__gte=0.1).order_by('-rank') return qs seetings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
django blog error keeps occuring on deployment to heroku
I am getting the following error when I try open my blog page after deployment to Heroku. it works ok in cloud9 but throws up the error once I deploy it. All the other pages of the site work fine. Can anybody help me please? [ Blog models.py file from django.db import models from django.utils import timezone from django.urls import reverse from django.conf import settings from django.contrib.auth.models import User from django.db.models.signals import pre_save from django.utils.text import slugify import datetime class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='user') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to='images', default='Upload Picture') category = models.CharField(max_length=200) description = models.CharField(max_length=340) views = models.IntegerField(default=0) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='post_likes', blank=True) def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse('post_detail', kwargs={"slug": self.slug}) def get_like_url(self): return reverse('like', kwargs={"slug": self.slug}) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def get_absolute_url(self): return reverse("post_list") def __str__(self): return self.text -
How to run a Django shell command from a script outside the Django project
I have a web scraper. It outputs JSON data. I have a Django project that uses this JSON data. These are in two separate repos/directories. My scraper copies the data file into my Django project. What I want is for that scraper script to then run my custom command, which I would usually activate in the command line with: python manage.py load_concerts name_of_file.json How do I make my scraper script (which again, is outside of the Django project) run the commands? (Googling these search terms is giving me people asking the opposite question, asking how to run a python script from the command line. I want to run a command prompt from a python script.) -
LOGIN_REDIRECT_URL not working in django2.1
i am learning django and i am having hard time integrating built-in django login systems. In settings.py i have provided LOGIN_REDIRECT_URL AND LOGOUT_REDIRECT_URL here, LOGOUT_REDIRECT_URL is working fine when i click Logout button. Button LOGIN_REDIRECT_URL is not working when i have provided with login credentials. settings.py LOGOUT_REDIRECT_URL = 'post_list' LOGIN_REDIRECT_URL = 'post_list' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] urls.py from django.urls import path, include from django.contrib import admin urlpatterns = [ path(r'admin/', admin.site.urls), path(r'', include('blog.urls')), ] blog/urls.py from django.urls import path from .views import (BlogListView, BlogDetailView, BlogCreateView, BlogUpdateView, BlogDeleteView) urlpatterns = [ path('', BlogListView.as_view(), name='post_list'), path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), path('post/new/', BlogCreateView.as_view(), name='post_new'), path('post/<int:pk>/edit/', BlogUpdateView.as_view(), name='post_edit'), path('post/<int:pk>/delete/', BlogDeleteView.as_view(), name='post_delete'), ] login.html {% extends 'base.html' %} {% block content %} <h2>Login</h2> <form action="post"> {% csrf_token %} {{form.as_p}} <button type='submit'>Login</button> </form> {% endblock %} base.html <body> <div class="container"> <header> <div class="nav-left"> <h1><a href="/">Django Blog</a></h1> </div> <div class=nav-right> <a href="{% url 'post_new' %}"> + New Blog Post. </a> </div> </header> {% if user.is_authenticated %} <p>Hi! {{user.username}}</p> <a href="{% url 'logout' %}">Logout</a> {% else %} <p>You are not logged in. </p> <a href="{% url 'login' %}">Login</a> {% endif %} {% block content %} {% endblock %} </div> </body> -
Module Structure Python + Django, No module named 'entities'
See the picture below for my project structure. In riskgame/view.py I tried to reach the entity Risk.py: from entities.Risk import Risk def index(request): game = Risk() return HttpResponse("test") When I tried this I get the error: ModuleNotFoundError: No module named 'entities' " Also from api.risk.riskgame.entities.Risk import Risk I get the error ModuleNotFoundError: No module named 'api' What is a good structure for my project? -
Issue in serving Static files in Django with Nginx
I am new to Django and I have referred to all other questions regarding this but being a newbie I would like to know If I am missing something else. My App Setting : STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I run the command : python manage.py collectstatic My Nginx Config file : upstream mtl_website_server { server unix:/home/ubuntu/environments/mtl_app_env/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name <My-IP>; client_max_body_size 4G; access_log /home/ubuntu/logs/nginx-access.log; error_log /home/ubuntu/logs/nginx-error.log; location /static/ { alias /home/ubuntu/environments/mtl_app_env/mtl_website/staticfiles/; } location /media/ { alias /home/ubuntu/environments/mtl_app_env/mtl_website/staticfiles/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://mtl_website_server; break; } } } I have restarted nginx too after all this with command : sudo service nginx restart But with all the css and image file it gives 404 not found error. Please help me if I am missing something. -
Python read csv file and add new row and then after some test delete the row
I am using a CSV file where first tasks is to just push that file to a server, second after the first tasks make some changes in csv file which now has an object, {'file': <_io.TextIOWrapper name='timepay/tests/Prop_Delhi.csv' mode='r' encoding='UTF-8'>} response = client.post('/path/to/push/', data=files) So point is to make a change in this file object and again push the newly edited file object to the server so the server updates the new content to a database. (In short, create a new file object with newly updated contents.) Once the newly updated file object tasks are done, remove the updated row from the file object and keep the original file as it is. -
Django makemessages "struct.error: unpack requires a buffer of 4 bytes"
I have a django instance packed in Docker container in docker-compose. I'm trying to generate makemessages files for project, but when I try to run makemessages, that's what I receieve in response root@6fc510c9c5d1:/code# python manage.py makemessages /usr/local/lib/python3.6/dist-packages/daphne/server.py:12: UserWarning: Something has already installed a non-asyncio Twisted reactor. Attempting to uninstall it; you can fix this warning by importing daphne.server early in your codebase or finding the package that imports Twisted and importing it later on. UserWarning, Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/usr/local/lib/python3.6/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/usr/local/lib/python3.6/dist-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/models.py", line 94, in <module> class Group(models.Model): File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 152, in __new__ new_class.add_to_class(obj_name, obj) File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 315, in add_to_class value.contribute_to_class(cls, name) … -
pipenv: get path of virtual enviremtnt in pipenv
How to can get the path of virtualenv in pipenv? can configure it to use a custom path for newly created virtualenv? -
Django Test - Send Array of Arrays containing Integer
currently i am trying to send an array of arrays containing integers to my rest api, this is part of my test: res = self.client.post( '/data', { 'data': [ [1,2,3], [4,5,6] ] } ) In my serializer i try to print the data: def create(self, validated_data): print(self.context['request'].data) print(self.context['request'].data['data']) But i just get: <QueryDict: {'data': ['[1, 2, 3]', '[4, 5, 6]']}> [4, 5, 6] Expected: {'data': [[1, 2, 3], [4, 5, 6]]} [[1, 2, 3], [4, 5, 6]] How can this be? Did i send the wrong format or did i access the json the wrong way...? Thanks and Greetings! -
How to add Email verification in Django Rest- Framework?
I add Email verification or Email sending option in Django but in Rest framework when i try sending email from serializer class it doesn't respond. Anybody give me some idea's how can i do this ? -
Django download static file using html button
I am creating a site with Django where users can gather data from diffrent websites, review it, save it to database and download all the data as a file(txt or csv). I have this problem where i can't create a href link ({% static 'files/filename' %}) to specific static file that users can download. When i try to add href attribute to a link and click it i get this error where instead of for example this: <a id="download" href="/static/file/Shrek_reviews.txt" download=""></a> i get this: <a id="download" href="/static/file/%22%20%2B%20btn_n%20%2B%20%22_reviews.txt" download=""></a> can someone tell how can i parse file name to {% static 'file/file_name' %} so it can work propertly ? Below is my view function and ajax function that creates href attribute and download file. Thanks in advance for Your help ajax function $('button').click(function(){ var btn_t = $(this).text(); var btn_n = $(this).attr('name'); $.ajax({ type: "POST", url: "{% url 'proces:films_data' %}", data: { csrfmiddlewaretoken: '{{ csrf_token }}', btn_text:btn_t, btn_name:btn_n, }, success: function(data){ if(btn_t == 'txt') { $("#download").attr("href", "{% static 'file/" + btn_n + "_reviews.txt' %}"); } else { $("#download").attr("href", "{% static 'file/" + btn_n + "_reviews.csv' %}"); } $('#download').trigger('click'); } }); }); View function def films_data(request): db_film_data = Films.objects.all() if request.method == "POST": … -
Integrity error with django-vote (new row for relation violates check constraint num_vote_up_check)
I'm trying and failing to get django-vote to work for my django app. Once a vote is made, nothing can be changed else a sql error. Also once adding a vote, this does not update the counts of the model. It seems the app is not working, as I can't find any more information on what I'm doing wrong. Here's my setup: #products.models.py from vote.models import VoteModel from django.db import models class tags(VoteModel, models.Model): name = models.CharField(max_length=50, unique=True) class gymproduct(models.Model): tags = models.ManyToManyField(tags, blank=True) .... I want users to vote on specific tags for a gymproduct. I can add a tag no problem. But when I try to use the api for the django-vote things don't seem to work as advertised. For example: #debugsqlshell from products.models import * from profiles.models import Profile #my custom user model firsttag = tags.objects.first() user = Profile.objects.first() firsttag.votes.up(user.id) #This returns true. firsttag.vote_score #This should return one, but returns 0, did the previous vote not count? firsttag.num_vote_up #This should return one, but returns 0??? firsttag.votes.down(user.id) # This breaks sql with the error: # IntegrityError: new row for relation "products_tags" violates check # constraint "products_tags_num_vote_down_check" I don't know why I get this IntegrityError error (I'm using postgres). … -
Why in Saleor checkout, shipment in France and other countries not working?
I have installed Saleor on macos High sierra for evaluation purpose I have populated Saleor with Example Data, and everything works fine. But when I Try to checkout the process is stuck at shipping step, with the following message : Unfortunately we do not ship to your selected country. Please enter an alternative shipping address or contact us, if you think that's a mistake. I have try many countries but the result is the same ... All countries are configured correctly by the Example Data Any idea ? Does I miss something ? Thanks for help. -
XlsxWriter/OpenPyXl object save as HttpResponse to create download
I've been scratching my head far too long with this one. Here it goes - I am trying to export a user model class(as excel sheet), after making some changes to it then returning it as HttpResponse object for download. Here is my view code: if request.method == 'POST': form = ExportStudentscsv(request.POST) if form.is_valid(): data = form.cleaned_data #get course from dropdown value course = data.get('course') # find course id based on course title courseid = Course.objects.get(title=course) #find groups using course id groups = Groups.objects.filter(course=courseid) desiredintake = data.get('desiredintake') intakeyear = data.get('intakeyear') user_resource = UserResource() queryset = User.objects.filter(desiredintake=desiredintake, intakeyear=intakeyear, role=4) if not queryset: return page_not_found(request, "Bad Request") dataset = user_resource.export(queryset) dataset.xls response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="students.xls"' workbook = xlsxwriter.Workbook(response, {'in_memory': True}) worksheet = workbook.add_worksheet('Groups') worksheet.data_validation('B11', {'validate': 'list', 'source': ['open', 'high', 'close']}) workbook.close() response['content_type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' response['Content-Disposition'] = 'attachment; filename=students.xls' return response else: args = {'form': form} return render(request, 'epitaadmin/export_studentscsv.html', args) I followed the approach given in the third answer given in this post XlsxWriter object save as http response to create download in Django, but no luck. I don't get the data-validation changes made here - workbook = xlsxwriter.Workbook(response, {'in_memory': True}) worksheet = workbook.add_worksheet('Groups') worksheet.data_validation('B11', {'validate': 'list', 'source': ['open', … -
Add a field value outside form in Django
Whenever I have to add a value to the instance of a form obtained from the context or from the URL I do it in the following way, using form.instance. class PreguntaForm(forms.ModelForm): class Meta: model = Pregunta fields = ('etiqueta', 'grupo', 'tipo_pregunta', 'opciones', 'mostrar_tabla', 'activo') def __init__(self, *args, **kwargs): cuestionario = kwargs.pop('cuestionario', False) super(PreguntaForm, self).__init__(*args, **kwargs) self.fields['grupo'].queryset = Grupo.objects.filter(cuestionario=cuestionario) class PreguntaNueva(InfoPregunta, CreateView): form_class = PreguntaForm encabezado = 'Nueva Pregunta' model = Pregunta def get_form_kwargs(self): kwargs = super(PreguntaNueva, self).get_form_kwargs() kwargs['cuestionario'] = self.dame_cuestionario() return kwargs def form_valid(self, form): form.instance.cuestionario = self.dame_cuestionario() return super(PreguntaNueva, self).form_valid(form) The problem that arises now is that I want to perform a check CreateView and EditView. To DRY, I want to do it in the clean method of the model, but the value that I assign to form.instance.cuestionario, is not available within the clean method. How could I do it? This value must not be edited by the user in any case. -
Django queryset: check for foreignkey values and substract them from queryset
Let's imagine we have 2 models: class Blog(models.Model): title = models.CharField(...) status = models.Charfield(choices=choices.STATUS, default='pending') class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name="entries") text = models.TextField() ready = models.BooleanField(default=False) Every entry can be added in many blogs. I want to filter all entries with ready = True whose blog has the status = published.