Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django web development prblem: blank=True and null=True but still can not create post without image field
This is my upload location: def upload_location(instance, filename): file_path = 'blog/{author_id}/{title}-{filename}'.format( author_id=str(instance.author.id),title=str(instance.title), filename=filename) return file_path This is my class: class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000) image = models.ImageField(upload_to=upload_location, null=True, blank=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.title The form: class CreateBlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'body', 'image'] And the view: def create_blog_view(request): context = {} user = request.user if not user.is_authenticated: return redirect('must_authenticate') form = CreateBlogPostForm(request.POST or None, request.FILES or None) if form.is_valid(): obj = form.save(commit=False) author = Account.objects.filter(email=user.email).first() obj.author = author obj.save() form = CreateBlogPostForm() return redirect('home') context['form'] = form return render(request, "blog/create_blog.html", context) The problem is that I don't know why the error This field is required appears when I try to publish a post on the website. Not only that but if I try to set a default picture it does not work either, basically blank=True and null=True don't do what they should have done and default="default.jpeg" does not do the trick of putting a default image from the beginning either. I don't know honestly why this happens, tried to change multiple things in … -
How to access dynamic number of inputs and HTML elements in Django?
I am pretty new to all of this and am building a food order app. Now I am at a point where I have dynamically generated a page with JavaScript that contains a HTML-form with varying (potentially large) number or HTML elements such as dish name, price, amount, extra toppings (inputs to be selected), etc and a "Place Order" submit button for a POST request. Normally, in my Django-URL, I would access the submitted information (e.g. the input text named username) for example like this: username = request.POST["username"] But how do I go about it in my case? I need much more than only 2 text input fields with hard-defined names. Is there a way of calling my Django url maybe with a large array or JSON object as parameter? -
How to show only one div onclick from a loop in django
I want to show only that ans-area which have same id with question from a loop with a button click which is in another div.But when i do that with jquery it will select all divs having .ans-area class. -
Django filter on prefetch related queryset
I'm using Django 2.2 I have many reverse related models to the User model and I want to get count from each model with different filters. For example, I have a Relations model like status = ( ('Active', 'active') ('Inactive', 'inactive') ) class Relation(models.Model): user = models.ForeignKey(User, related_name='relation') status = models.CharField(choices=status, default=ACTIVE) Now I want to get the count and the queryset for each status separately for the user. For that I have defined the model methods inside the User model def get_relation(): return self.relation.all() def get_active_relation(self): return self.relation().filter(status='active') def get_inactive_relation(): return self.relation().filter(status='inactive') def get_active_count(): return self.get_active_relation().count() def get_inactive_count(): return self.get_inactive_relaiton().count() I have the user object as user = User.objects.prefetch_related( 'relation' ).get(pk=request.user.pk) Now when I get the count, it executes an extra query for that user.get_active_count() How can I filter on the prefetch_related objects? I found a use of lambda to get the max value from the prefetch_related in another SOF answer: https://stackoverflow.com/a/12609454/3719167 Is it possible to use lambda to filter the queryset as well? -
Check remaning time to start a event is less then 24
In django I want to check how much time remaining to start a event , I know about this thing time_threshold = datetime.now() - timedelta(hours=24) event = Event.objects.get(seleteddate__lt=time_threshold) but my problem is I have saved startdate and start time in 2 diff variables like this class Event(models.Model): seleteddate = models.DateField(blank=True,null=True) startTime = models.TimeField() P.S I cant make it a datetime field due to other use cases. So How I can check on basis of both that how much time it remaning to start an event. -
Wagtail ImageChooserPanel giving a error `no such column: projects_projectblogdetail.project_image_id`
I currently got an issue when trying to use ImageChooserPanel in wagtail. My goal is to make a blog type model that will accept a header image. My issue is I keep getting a error saying that no column exists called project_image_id. Error: no such column: projects_projectblogdetail.project_image_id Do I need to add the project_image_id by itself? Or is that suppose to be taken care by the ForeignKey? Here is my model code: class ProjectBlogDetail(Page): """ The Our Projects page will work as a blog to add new project articles """ template = "projects/blog-detail.html" project_body = RichTextField(blank=True, default="Project Description") project_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) created_on = models.DateTimeField(default=timezone.now) content_panels = Page.content_panels + [ FieldPanel('project_body'), ImageChooserPanel('project_image'), ] def serve(self, request): context = news_letter_subscribe_form(request) if request.method == 'POST': newsletter_form = NewsletterForm(request.POST) if newsletter_form.is_valid(): return news_letter_subscribe_form_submit(request) else: context.update({ 'post': self, }) return render(request, 'projects/blog-detail.html', context) Any help will be gladly appreciated. -
Callable FilePathField to get user id
I have a model where user uploads a file in his own folder inside the media directory def user_directory_path(instance, filename): return 'user_{0}/{1}/{2}'.format(instance.user.id,'files', filename) class FileUploadModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='fileuploadmodels') uploadedfile = models.FileField(upload_to=user_directory_path, null=True, blank=True) Now, I want the user to select one of his uploaded files in a form but I am unable to get user in the FilePathField def get_readduppath(instance): return os.path.join(settings.MEDIA_ROOT,'user_{0}'.format(instance.user.id)) class ReadDupModel(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='readdupmoddels') alignFile = models.FilePathField(path=get_readduppath, recursive=True, allow_folders=True ,blank=True, null=True) Here is the form class ReadDupForm(forms.Form): class Meta: model = ReadDupModel fields = ('alignFile',) -
Multi-user/ Multi- Role system in Django
Let's consider a school system. There are teachers and students, having their particular id's. The teacher schedules the tasks, and the students should be able to look at the tasks given and update the tasks' status. Now, I want the Django application to allocate tasks only to the students belonging to a particular teacher. 1. Tasks should be given to the students by only their respective teachers. 2. Tasks should be viewed by the student, who is actually assigned to, and not by others. How can I build such a multi-user/ multi-role system? -
How would one record the last datetimefield in models.py?
See below for my models.py class Customer(models.Model): last_purchase = models.DateTimeField(blank=True, null=True) class Order(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) How would one record the last Datetimefield in models.py? For example if I wanted to display the last purchased order of a product that continuously updates itself in a page. -
Django can't find module 'iexfinance'
I would like to fetch some stocks data via the iexfinance API but can't get the package running. I installed the iexfinance module (docu) C:\Users\Jonas\Desktop\CFD\CFD>pip3 install iexfinance Collecting iexfinance Using cached iexfinance-0.4.3-py3-none-any.whl (51 kB) Installing collected packages: iexfinance Successfully installed iexfinance-0.4.3 Started a seperate app 'feeder' for the API logic C:\Users\Jonas\Desktop\CFD\CFD>py manage.py startapp feeder Included it in my settings INSTALLED_APPS = [ [...] # My Apps 'calculator', 'accounts', 'feeder', ] And created one first easy query: from iexfinance.stocks import Stock aapl = Stock("AAPL") apple_price = aapl.get_price() print(apple_price) and get this error: C:\Users\Jonas\AppData\Local\Programs\Python\Python38\python.exe C:/Users/Jonas/Desktop/CFD/CFD/feeder/feeder.py Traceback (most recent call last): File "C:/Users/Jonas/Desktop/CFD/CFD/feeder/feeder.py", line 8, in <module> from iexfinance.stocks import Stock ModuleNotFoundError: No module named 'iexfinance' Process finished with exit code 1 My manage.py file links to the correct settings.py path. What do i miss? -
Django project in PYCHARM
Hello I have made this code DATABASES = { 'default': { 'ENGINE': 'Django.db.backends.mysql', 'NAME': 'Firstdb', 'USER': 'root', 'PASSWORD': 'root' } } However this is giving me an error whenever I write: from Django. db import connection c=connection.cursor() d-jango.core.exceptions. ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
How to change serializer field name when validation error is triggered
I need to change the view of the error displayed when I validate the field. serializer.py class ElementCommonInfoSerializer(serializers.ModelSerializer): self_description = serializers.CharField(required=False, allow_null=True, validators=[RegexValidator(regex=r'^[a-zA-Z0-9,.!? -/*()]*$', message='The system detected that the data is not in English. ' 'Please correct the error and try again.')] ) .... class Meta: model = Elements fields = ('self_description',......) This error is displayed { "self_description": [ "The system detected that the data is not in English. Please correct the error and try again." ] } The key of error dict is field name - self_description. For FE I need to send another format like: { "general_errors": [ "The system detected that the data is not in English. Please correct the error and try again." ] } How to change this? -
change behavior of function in TestCase
I have sendmail function that is being called in post_save signal. I would like this function just to return None instead for all test cases. How to achieve this? Use patch from mock.patch in setUp? How? -
what is the best Approach?
I have been learning and Coding in Django_Rest_framework. I want to ask what should be the approach to design an API. Do I use the model classes and serializers and ViewSet or Should I Approach a long route, like simple serializer class and ApiView Classes being a developer I know it is important to do reusability and save time to write the code but I want to sharpen up the skill in writing RestApi. What approach should I take? -
Django Foreignkey populates field in Form
I've been struggling with passing the pk from objects in ListView template. So the objective is to pass the pk from one specific car from a template that has a list of cars. This pk will then populate a form by using a foreignkey named 'vehicle2wash'. I've tried class based views as well as function based views. I'm open to any solution. This view is giving me an error but I feel like it's the closest I can get. Thanks in advanced! models class CarModel(model.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) plates = models.CharField(max_length=20, unique=True) def __str__: return f"{plates}" class WashModel(model.Model): message = models.CharField(max_length=20, unique=True) vehicle2wash = user = models.ForeignKey(CarModel, on_delete=models.CASCADE) views class WashService(LoginRequiredMixin, CreateView): model = Wash_service form_class = WashServiceForm template_name = 'service_app/standard_wash_form.html' def get_initial(self): initial = super(WashService, self).get_initial() initial = initial.copy() initial['car_pk'] = request.CarModel.pk return initial html taken from ListView template <form action="{% url 'service_app:standard_service' car_pk=object.pk %}" method='POST' > {% csrf_token %} <input class=btn btn type="submit" value="Add"/> </form> -
How do i disabled/enabled submit button
i am working on a project using Django. I have 3 posts in homepage and each have a comment form with a submit button. How do i disable the submit button if there is no text in textarea and when there is a text in textarea the submit button will be enabled, after form is submitted the submit button will become disabled. My comment saved in database when i submit the form, I have tried using this http://jsfiddle.net/mehdi354/c3wyh761/14/ it worked but my comment is not saving in database. How do i solve this? Form: <span class="md-form"> <form enctype="multipart/form-data" class="feeds-form form-inline md-form form-sm" method="POST" action="{% url 'site:home' %}"> {% csrf_token %} <input type="hidden" value={{post.id}} name="post_comment"> <textarea name="comment_post" class="textinput textInput animated fadeIn" placeholder="Add a comment..." required="" id="id_comment_post{{ post.id }}" onkeyup=""></textarea> <button type="submit" class="submit" id="submit1-{{post.id}}" disabled>button</button> </form> </span> Ajax form submit: <script> $(document).on('submit', '.feeds-form', function(event){ event.preventDefault(); var pk = $(this).attr('value'); console.log($(this).serialize()); $.ajax({ type: 'POST', url: "{% url 'site:home' %}", headers: { 'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val() }, data: $(this).serialize(), dataType: 'json', success: function(response) { $('#newfeeds-form'+pk).html(response['form']); $('textarea').val(''); //console.log($('#newfeeds-form'+pk).html(response['form'])); }, error: function(rs, e) { console.log(rs.resopnseText); }, }); }); </script> Jquery disable/enable button: $(document).on("keydown",".textinput",function(){ let buttons = $(this).closest("form").find(".submit") if($(this).val() == "") { buttons.attr("disabled",true); } else{ buttons.attr("disabled",false); } $(document).on("click",".submit",function(e){ $(this).closest("form").trigger("reset");; … -
Putting a string below a function definition in Python
I was reading the Django documentation, and I came across this code: from django.db import models class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField() def baby_boomer_status(self): "Returns the person's baby-boomer status." import datetime if self.birth_date < datetime.date(1945, 8, 1): return "Pre-boomer" elif self.birth_date < datetime.date(1965, 1, 1): return "Baby boomer" else: return "Post-boomer" What is the purpose of putting a string below a function definition i.e baby_boomer_status()? -
What are problems with a browser caching?
Stack: django, templates+js+jquery, docker, nginx. Firstly I wrote a form without an image field and there wasn't the attribute Attribute enctype with the value multipart/form-data in the html template. But I needed to changed it. I added custom CustomFileField(FileField) in the model and multipart/form-data in the template. But when I go to the site and save this form, I see that the image saves with the wrong path "1.png" but the right is "images/1.png" (upload_to="images", storage=get_public_media_storage()). I cleared the cache in Chrome but nothing changed. P.S. I use CustomFileField(FileField) because I need images with the extentions: 'png', 'jpg', 'jpeg' and 'svg'. What problems can happen? -
error pip installing social-auth-app-django
I am using virtual environment on a win10, i tried installing social-auth-app-django but it is showing me this error: Command "python setup.py egg_info" failed with error code 1 in C:\Users\Yash\AppData\Local\Temp\pip-install-7u8h37nm\cffi\ Command "C:\Users\Yash\PycharmProjects\djangoproject\venv\Scripts\python.exe c:\users\yash\pycharmprojects\djangoproject\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip install --ignore-installed --no-user --prefix C:\Users\Yash\AppData\Local\Temp\pip-build-env-5ybb8f9v\overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools>=40.6.0 wheel "cffi>=1.8,!=1.11.3; platform_python_implementation != 'PyPy'"" failed with error code 1 in None -
How Django can trigger a task automatically even when the django application page is not opened
I am new to Django. So I would really appreciate if any of you please provide me a direction on how to achieve my goal. I have a long running task. Django should monitor the task in background when the Django application is accessed in a browser. When the task is complete, Django to trigger a different task automatically when the application is not accessed. Is it possible? -
How to get page view count on wagtail/django?
I am planning to create a page within a blog website where it arranges and displays the all blog posts based on page view count. Not sure how to pull it off. models.py class BlogPost(Page): date = models.DateField(verbose_name="Post date") categories = ParentalManyToManyField("blog.BlogCategory", blank=True) tags = ClusterTaggableManager(through="blog.BlogPageTag", blank=True) body = RichTextField(blank=False) main_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=False, on_delete=models.SET_NULL, related_name='+') def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) blogposts = self.get_siblings().live().public().order_by('-first_published_at') context['blogposts'] = blogposts return context content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), FieldPanel('tags'), ImageChooserPanel('main_image'), FieldPanel('body', classname="full"), ] -
Django database sync error while makeinh migartion
Django database sync error. While making migrate it shows error. Everything was correct So, i have deleted all files form migration folder except init.py. The error solved. Is there any way to solve db sync error in Django -
How can I use the blog index within the homepage?
I'm new to wagtail and pretty new to django. I'm wondering how to implement the blog that's documented here: https://docs.wagtail.io/en/stable/getting_started/tutorial.html but directly within the home page. Meaning, I'd like the blog index to be the root of the site (like most blogging sites have). Thanks in advance! -
Django nested transaction.atomic throw IntegrityError "SAVEPOINT does not exist" with MySQL
I am trying to make nested transaction.atomic() work. The following block of code crashes when exiting first transaction.atomic() with the following error MySQLdb._exceptions.OperationalError: (1305, 'SAVEPOINT s4568333760_x1 does not exist') from django.contrib.auth.models import User from django.test import TransactionTestCase from django.db import transaction class FooTest(TransactionTestCase): def test_bar(self): with transaction.atomic(): with transaction.atomic(): u = User.objects.create_user(username="abc", password="pass") print("created user: {}".format(u.username)) It seems like this happens due to the fact that Django fails to execute TRANSACTION START or SET AUTOCOMMIT=0 during the test. I know this by looking at local MySQL query log. Of course, my final test is not that simple, but the following example shows the concept which should work by does not. Am I doing something wrong or is this a bug of Django? -
Django Error when running server locally - AttributeError: 'list' object has no attribute 'read'
Getting below error when trying to run server in VS Code for Django. Command: python manage.py runserver Error: C:\DjangoServerTest\DjangoServerTest>python manage.py runserver Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 601, in run_with_reloader exit_code = restart_with_reloader() File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 230, in restart_with_reloader p = subprocess.run(args, env=new_environ, close_fds=False) File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\run\__init__.py", line 145, in __new__ process = cls.create_process(command, stdin, cwd=cwd, env=env, shell=shell) File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\site-packages\run\__init__.py", line 121, in create_process shlex.split(command), File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\shlex.py", line 305, in split return list(lex) File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\shlex.py", line 295, in __next__ token = self.get_token() File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\shlex.py", line 105, in get_token raw = self.read_token() File "C:\Users\subhasispanda\AppData\Local\Programs\Python\Python37-32\lib\shlex.py", line 136, in read_token nextchar = self.instream.read(1) AttributeError: 'list' object has no attribute 'read' Can you please help here?