Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to schedule a celery task through a django view
Is there any way to define a date and time in a django view and run a celery task at the defined time? For example def test(request): date = '2020-09-12' time = '11:34' # run the below task at the specified time test_celery_test.delay() ... I want the task to run only once at the specified time and should not repeat -
how can I format django-html code in vscode
So, recently I have been coding in Django and in its templates folder, as we know, we put HTML files. So earlier when I use to code in HTML only(not Django-HTML), vscode used to auto-format the code and align the tags with tab spaces properly. but in Django-html, the code is not getting auto formatted, also I have enabled the 'prettier extension' but still this problem exists: {% extends 'base.html' %} {% block title %}Contact Us {% endblock title %} {% block contactactive %} active{% endblock contactactive %} {% block body %} <div class="container my-4"> <h2>Contact our developers!</h2> <form action="/contact/" method="post"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="enter your full name" /> </div> </div> {% block body %} but I want my code to be formatted like this: {% extends 'base.html' %} {% block title %}Contact Us {% endblock title %} {%block contactactive %} active{% endblock contactactive %} {% block body %} <div class="container my-4"> <h2>Contact our developers!</h2> <form action="/contact/" method="post"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="enter your full name" /> </div> </div> {% block body %} are there any settings or any tools which I should … -
Rest-Framework: Serialize model with relationship to same model
I have a Tag model as follows: class Tag(models.Model): name = models.CharField(max_length=50) aliases = ArrayField( models.CharField(max_length=50), size=8, ) parent = models.ForeignKey(to="self", null=True, on_delete=models.CASCADE) class Meta: db_table = "tags" def __str__(self): return self.name Notice I have the parent field which is a ForeignKey to another tag object. In my serializer if I add the field parent to fields I get the following ImproperlyConfigured error. Could not resolve URL for hyperlinked relationship using view name "tag-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. class TagSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Tag fields = ["name", "aliases", "parent"] extra_kwargs = {"aliases": {"validators": []}} What I initially thought was I could add the TagSerializer for the parent attribute, but at this time it wouldn't be defined. So how would I serialize the parent tag? -
Decimal Field unable to update value
I have a DemicalField and have a def() for change the value of it. However, the value unable to change through the def(). May I know why? Models.py: class BillingAddress(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) district = models.CharField( max_length=2, ) deliver = models.CharField(max_length=4, null=True) shipping_fee = models.DecimalField(decimal_places=2, max_digits=10, default=0) def __str__(self): return self.street_address def fee_caculate(self): if self.deliver == 'deli': if self.district == 'K': self.shipping_fee = 20 elif self.district == 'T': self.shipping_fee = 30 else: self.shipping_fee = 50 return self.shipping_fee -
Queryset to call ModelFormField into Chart JS - Django
I am attempting to pass user submitted data from a django model form into a Chart.js chart that renders on a detail view page. I am having trouble figuring out why I cannot call values from an instance of the model form submission in my views.py and subsequently pass that to the js which renders the chart. When I hardcode values into my class-based view defined variables for TAM and LTM_sales the chart renders. Please see code below: Models.py: class Strategy(models.Model): total_addressable_market = models.IntegerField(blank=True, null=True) last_twelve_months_sales = models.IntegerField(blank=True, null=True) Views.py def strategy_detail(request, id): strategy = get_object_or_404(Strategy, id=id) .... context ={ 'strategy': strategy, .... } return render(request,'hypo_app/strategy_detail.html', context) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, default=None): strategy = Strategy.objects.all() TAM = ?? LTM_sales = ?? labels = ['TAM', 'LTM Revenue'] default_items = [TAM, LTM_sales] data = { "labels": labels, "default": default_items, } return Response(data) URL from django.urls import path from .views import UserExperimentListView, ChartData from . import views urlpatterns = [ .... path('chart_data/', ChartData.as_view(), name='chart_data'), ] JAVASCRIPT within the strategy_detail.html file <script> {% block jquery %} var endpoint = '/chart_data/' var defaultData = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = … -
Integrate React in an existing Django project
I have been working on a django project for a while now and I would like to add React to it. I know there are some materials online, I have been checking them, especially the following three: link1 link2 link3 I am not an expert yet I am a bit confused which method I have to follow. I just want to add React to one of my apps first. I am kinda afraid of adding it if it would mess with other apps in my project. So, could somebody please tell/enlight me on the correct way which would allow me to have just a part of a website using Django working with React, while other parts are just working like before using js/html. If you have done this before, I also would be glad to hear your feedback and how you did it ! Thanks Cheers, Roman. -
Django - get_context_data() missing 1 required positional argument: 'form'
I am trying to add inlineformset to the Django Blog project. I got post and I want to add multiple images to the post via Class Based Views. But when I am trying to get_context_data I receive this error: get_context_data() missing 1 required positional argument: 'form' Models.py: class Post(models.Model): title = models.CharField(max_length=100) content = RichTextField(blank=True, null=True) class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='gallery/') description = models.CharField(max_length=300, blank=True) Forms.py class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ['title' , 'content' ] PostImageFormSet = inlineformset_factory(Post, PostImage, fields=['image', 'description'], exclude=['post'] , max_num=30, extra=3) Views.py class PostCreateView(LoginRequiredMixin, CreateView): form_class = CreatePostForm template_name = 'blog/post_form.html' def get_context_data(self, form): context = super(PostCreateView. self).get_context_data(**kwargs) if self.request.POST: context['post_images'] = PostImageFormSet(self.request.POST) else: context['post_images'] = PostImageFormSet() return context def form_valid(self, form): context = self.get_context_data(form=form) formset = context['post_images'] form.instance.author = self.request.user if formset.is_valid(): response = super().form_valid(form) formset.instance = self.object formset.save() return response else: return super().form_invalid(form) Any idea why I am receiving this kind of error? Thank you. -
How to display Django reverse ForeignKey Data?
I have 2 models, and I want to display data through my first model, suppose Model1 have some fields and Model2 have ForeignKey of Model1, and I am getting data through Model1 on the display page, but I want to display some records from Model2 also, Please let me know how I can display data from Model2. here is my models.py file... class Model1(models.Model): namefield=models.Charfield(blank=True)class Model1(models.Model): emailfield=models.Charfield(blank=True) phone=models.Charfield(blank=True) class Model2(models.Model): name=models.CharField(default=None) type=models.CharField(default=None) father=models.CharField(default=None) model1=models.Foreignkey(Model1, related_name='model_one', on_delete=models.CASCADE) here is my views.py file... def display_data(request, id): test_display = Model1.objects.filter(pk=id).first() context = { 'test_display': test_display } return render(request, 'page.html', context) please note I am displaying data here from Model1...but I want to display name, type and father from Model2 here is my test.html file... <p>{{ test_display.namefield }}</p> <p>{{ test_display.emailfield }}</p> <p>{{ test_display.phone }}</p> <p>{{ test_display.model_one.name }}</p> <p>{{ test_display.model_one.type }}</p> <p>{{ test_display.model_one.father }}</p> these last 3 records displaying nothing -
ModuleNotFoundError: No module named 'fcntl' when I try to deploy my django project on heroku
I try to deploy my django project on heroku, and follow commands below heroku login git init git add . git commit -m "first commit" heroku create heroku git:remote -a name pip install gunicorn gunicorn application.wsgi when it comes to the latest command, error occurs: ModuleNotFoundError: No module named 'fcntl' How can I solve it? -
rest framework ManyToMany field related data get in createApiView?
i want to learn about django rest framework.how can i get many to many field related data get in CreateApiView. i have a shopkeeper create api form template. if shopkeeper select a book from option menu then the book price show in html input using ajax ? models.py class Book(models.Model): name = models.CharField(max_length=20) price = models.IntegerField(null=True) class Keeper(models.Model): books = models.ManyToManyField(Book) serializer.py class KeeperSerializer(serializers.ModelSerializer): books = serializers.SlugRelatedField(queryset=Book.objects.all(), slug_field='name') for book in books: print('selected book price:' book.price) class Meta: model = Keeper fields = ['id', 'books'] -
Webpack dev server redirects to
I am running a Webpack development server for my React single page app (Django backend). Django serves the React app from '/'. I also have a Django URL configured for '/admin' as that's where inbuilt admin section lives for the site. This works fine in production but, on development server, when I type in 'localhost:3000/admin', it gets redirected to '/' and the single page app is served. I am unable to go to any URL after slash to get a 404 error, everything gets redirected to '/' and the React app is served. Is there a way to configure the webpack development server to pass through requests after '/' to the backend, as in production? -
Django recursive serializer
Currently i'm trying to set a recursion limit of a self referentiated model, but im failing to grasp how this serialzier recursion works in Django 3.0. Currently I have 5 users and my output is as follows: { "user": "user_1", "sponsor": null, "reply_set": [ { "user": "user_2", "sponsor": 1, "reply_set": [ { "user": "user_3", "sponsor": 2, "reply_set": [ { "user": "user_4", "sponsor": 3, "reply_set": [ { "user": "user_5", "sponsor": 4, "reply_set": [] } ] } ] } ] } ] }, ... But I would like to set a limit to the recursion, giving me a tree with with the relations between the user_1 and user_4 only (between only 4 users). { "user": "user_1", "sponsor": null, "reply_set": [ { "user": "user_2", "sponsor": 1, "reply_set": [ { "user": "user_3", "sponsor": 2, "reply_set": [ { "user": "user_4", "sponsor": 3, "reply_set": [ ] } ] } ] } ] }, In the case above, the user_5 still exists and have the user_4 as it's parent, but I do not want to show him in the user_1 tree. Only the relationships between 4 users. My model # models.py class SponsorTree(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) sponsor = models.ForeignKey('self', related_name='reply_set', null=True, on_delete=models.SET_NULL) points = models.DecimalField(default=0, … -
ValidationError at /blog/addblog/ ['“” value has an invalid date format. It must be in YYYY-MM-DD format.']
This is how it shows in datepickerI have tried mostly everything but not able to find the solution. I am new to Django and basically a beginner so help me to do this. Tried many resources still the error shows up: ValidationError at /blog/addblog/ ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] In my views.py def addblog(request): if request.method == "POST": title = request.POST.get('title', '') head0 = request.POST.get('head0', '') chead0 = request.POST.get('chead0', '') head1 = request.POST.get('head1', '') chead1 = request.POST.get('chead1', '') head2 = request.POST.get('head2', '') chead2 = request.POST.get('chead2', '') pub_date = request.POST.get('pub_date', '') thumbnail = request.POST.get('thumbnail', '') add = Blogpost(title=title, head0=head0, chead0=chead0, head1=head1, chead1=chead1, head2=head2, chead2=chead2, pub_date=pub_date, thumbnail=thumbnail) add.save() que = True return render(request, 'blog/addblog.html', {'que': que}) return render(request, 'blog/addblog.html') In my models.py class Blogpost(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=50) head0 = models.CharField(max_length=500, default="") chead0 = models.CharField(max_length=5000, default="") head1 = models.CharField(max_length=500, default="") chead1 = models.CharField(max_length=5000, default="") head2 = models.CharField(max_length=500, default="") chead2 = models.CharField(max_length=5000, default="") pub_date = models.DateField() thumbnail = models.ImageField(upload_to='shop/images', default="") def __str__(self): return self.title In my settings.py DATE_FORMAT = 'd-m-Y' DATE_INPUT_FORMATS = [ '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%d-%m-%Y', # '2006-10-25', '10/25/2006', '10/25/06' '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, … -
How to use Wagtail's admin widgets in custom form?
I'd really love to reuse the same widgets used in the admin part of my website made with Wagtail in my custom templates. Is there an easy way to do that ? For example : Picture of a field in wagtail's admin Will look like this when used in my html template : Same field but in my view My model currently looks like this : @slugify_field('name') class Company(models.Model): # more CharFields that I erased for brevity address = models.CharField( blank=True, max_length=255, help_text="The company's address.", ) founded = models.DateField( blank=True, null=True, help_text='The foundation year.', ) short_description = models.TextField( blank=True, help_text='A short description for the search view.', ) description = RichTextField( blank=True, help_text='A complete description for the company view.', features=['h4', 'bold', 'ul', 'link'] ) website = models.TextField( blank=True, help_text="The company main website", ) panels = [ FieldPanel('status'), FieldPanel('owner'), FieldPanel('name'), MapFieldPanel('address'), FieldPanel('founded'), FieldPanel('employees_count'), FieldPanel('contact', widget=autocomplete.ModelSelect2(url='contact-autocomplete')), FieldPanel('short_description'), FieldPanel('description'), FieldPanel('website'), FieldPanel('tags', widget=autocomplete.ModelSelect2Multiple(url='unseekable-tag-autocomplete')), FieldPanel('seeking', widget=autocomplete.ModelSelect2Multiple(url='seekable-tag-autocomplete')), FieldPanel('offering', widget=autocomplete.ModelSelect2Multiple(url='seekable-tag-autocomplete')), ] def __str__(self): return self.name class Meta: verbose_name = 'Company' verbose_name_plural = 'Companies' And my Form is like this : from django.forms import ModelForm, Textarea from wagtail.admin.edit_handlers import FieldPanel from .models import Company class CompanyForm(ModelForm): class Meta: model = Company exclude = [ 'status', 'owner', 'name', 'contact', 'slug', … -
django post_delete signal not triggered by delete foreign key object
i have a problem with my django project. I have two models: class A(models.Model): ... class B(MyFile): a = models.ForeignKey('otherapp.A', on_delete=models.CASCADE, related_name="files") thisfile = models.FileField(storage=MyStorage(), upload_to=create_path) ... I would like to delete the file if the object from class B will deleted. For this i have add a signal in the signals.py: @receiver(post_delete, sender=B, dispatch_uid='delete_b') def delete_b(sender, instance): instance.thisfile.delete(save=False) and edit the apps.py class BappConfig(AppConfig): name = 'bapp' def ready(self): import bapp.signals Now if i delete an instance of class B all works fine and the file delete also. But if i delete an instance of class A the instance of class B delete also but not the file. I think that the post_delete not triggered if the foreign key object delete. But Why? -
What the best way to create Family Tree with Django?
Is there any tutorials about it? The main goal is creation of the tree of persons (e. g. like a cards) with plus signs (or any possibility to add) that will add a different family relations to our person for every registered user. I already created a prototype of website with registration/signup/forgot_password and profile/profile_edit pages. But I don't understand where to move next. What I need to learn to achieve my goal? (javascript? some articles in django documentation? I need to use ManyToManyFields relations? more jinja implementation in html?) -
How to show users past order history in django?
I am a BCA student and new to django. I am doing my final year project in django. I am having a problem as to how to show a users all past order history. I declared two classes in models.py as OrderModel and OrderedItem. I want to show a users all order history, but whenever i run my code it shows multiple item details with a single order. Here's models.py: class OrderModel(models.Model): username = models.CharField(max_length = 150) email = models.EmailField(max_length = 254) phoneno = models.CharField(max_length = 20) address = models.TextField() timestamp = models.DateTimeField(auto_now = True) status = models.CharField(max_length = 20, default = "pending") paid = models.BooleanField(default = False) class OrderedItem(models.Model): orderid = models.ForeignKey(OrderModel, on_delete = models.CASCADE, null = True) name = models.CharField(max_length = 50) img = models.ImageField(upload_to='pics') quantity = models.CharField(max_length = 10) category = models.CharField(max_length = 30) price = models.IntegerField() total_price = models.IntegerField() Here's views.py: @login_required(redirect_field_name='login') def user_orders(request): orders = OrderModel.objects.filter(username = request.user.username) length = len(orders) if length == 0: context = {'orders': orders} else: items = OrderedItem.objects.all() context = { 'orders': orders, 'items': items } return render(request, "myorders.html", context) Here's html file: <h2 style="text-align: center">Past Orders</h2> {% if not orders %} <div> You haven't order anything yet. </div> {% … -
How can I remove the default rules of django UserCreationForm such as the password shouldn't match the personal info etc
Im working on a project for my classmates so we can interact make some events etc . so Im using Django's UserCreationForm , but it has many rules such as the password shouldn't match with personal info or it should be of more than 8 characters so how do i remove these rules. -
page view count for django detail view
I want to get the number of views to the details page, and I did, but I have a problem, Every time I refresh the page, the number of views increases. I want the view to increase only once for each user, not to increase the number of visits each time the page refresh. model: class Product(models.Model): name = models.CharField(max_length=300) create = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) slug = models.SlugField(unique=True) information = models.TextField(blank=True, null=True) views = models.IntegerField(null=True, blank=True, default=0) view: def details(request, id): product_view = Product.objects.get(id=id) product_view.views = product_view.views + 1 product_view.save() return render(...) -
Multiple forms on one model
I Have a questions about plugin code in "Django Bootstrap Modal Forms" Django Bootstrap Modal Forms I use one model but i wanna add multiple forms in the same template. What can i do in this case ? I tried use similar views like this # Update class BookUpdateView(BSModalUpdateView): model = Book template_name = 'examples/update_book.html' form_class = BookModelForm success_message = 'Success: Book was updated.' success_url = reverse_lazy('index') class BookUpdateView_One(BSModalUpdateView): model = Book template_name = 'examples/update_book_one.html' form_class = BookModelForm_One success_message = 'Success: Book was updated.' success_url = reverse_lazy('index') And the rest of the code similar to the first view. This works differently to regular forms and I don't know how to go about it. -
Making a django form interactive
html file <div id="calculator"> <h2>Kalkuleeri saematerjali hind</h2> <form method="post" action="{% url 'products' %}"> {% csrf_token %} <label>Valige materjali kvaliteet/tüüp:</label><br> <select name="tyyp"> <option value="taiskant">Täiskant</option> <option value="v_poomkant">Väike Poomkant</option> <option value="s_poomkant">Suur Poomkant</option> <option value="voodrilaud">Voodrilaud</option> </select><br><br> {% if not tyyp %} <button type="submit">Edasi</button><br><br> {% endif %} </form> <form method="post" action="{% url 'products' %}"> {% csrf_token %} {% if tyyp %} <label>Valige mõõdud: (Paksus mm x Laius mm)</label><br> <select name="moot"> {% for product in products %} <option value="1">{{ product.nimi }}</option> {% endfor %} </select><br><br> <label>Pikkus:</label><br> <select name="pikkus"> <option value="kunikolm">Kuni 3,1 m</option> <option value="kolmkuniviis">3,2 - 5,1 m</option> <option value="viiskunikuus">5,2 - 6,0 m</option> </select><br><br> <label>Kogus:</label><br> <input type="number" required> <select name="yhik"> <option value="tm">Tihumeetrit</option> <option value="jm">Meetrit</option> <option value="lauda">Lauda</option> </select><br><br> <button type="submit">Kalkuleeri</button> <input type="text" class="calculator-screen" value="" disabled /> {% endif %} </form> views.py file def products_view(request, *args, **kwargs): taiskant_list = Taiskant.objects.all() s_poomkant_list = S_Poomkant.objects.all() v_poomkant_list = V_Poomkant.objects.all() voodrilaud_list = Voodrilaud.objects.all() context = {} if request.method == "POST": tyyp = request.POST['tyyp'] context['tyyp'] = tyyp if request.POST['tyyp']=="taiskant": context['products'] = taiskant_list return render(request, "products.html", context) elif request.POST['tyyp']=="s_poomkant": context['products'] = s_poomkant_list return render(request, "products.html", context) elif request.POST['tyyp']=="v_poomkant": context['products'] = v_poomkant_list return render(request, "products.html", context) elif request.POST['tyyp']=="voodrilaud": context['products'] = voodrilaud_list return render(request, "products.html", context) else: return render(request, "products.html", context) The problem is, I am trying … -
Add action to custom submit button in django admin change form
I have custom submit button: submit_line template override: <input type="submit" value="{% translate 'My action button' %}" name="my_action"> And only one place where I can get acces to this button its in my modelAdmin method - save_model(). But I need to validate some data from request.POST, and in save_model it is not possible. So I found second "solution" - provide a custom form and add request to it in creation. Something like that: My admin class: form = MyForm def get_form(self, request, obj=None, **kwargs): ModelForm = super(MyAdmin, self).get_form(request, obj, **kwargs) class MyFormWithRequest(ModelForm): def __new__(cls, *args, **kwargs): kwargs['request'] = request return MyForm(*args, **kwargs) return MyFormWithRequest And in form: def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(MyForm, self).__init__(*args, **kwargs) And then I can acces request.POST in clean method for example. But that solution broke fields - my datetimefield don't have a datepicker, and my foreign key field dont have add/change/delete widget - only list. How I can fix this? Is there better way to add custom action to admin change form? thx in advice -
I need help in choosing relevant field for my django models , want a field like a list which can contain multiple items
Im working on a project where a user can add a event and other user can enroll himeself in that event so I want that which ever user fills the form of enrollment his name should be added to the list. My models Class Event(models.Model): Topic = CharField participants = want a field here which can store multiple items that is the name of user. So when the user registers a method appends the user name in this list. -
How to find out what the problem is with Keras load_img?
I am following a tutorial to built a small image classification app and am coming into a problem when I reacth the try/except block. from django.db import models from keras.preprocessing.image import load_img, img_to_array class Image(models.Model): picture = models.ImageField() classified = models.CharField(max_length=200, blank=True) uploaded = models.DateTimeField(auto_now_add=True) def __str__(self): return "Image classifed at {}".format(self.uploaded.strftime('%Y-%m-%d %H:%M')) def save(self, *args, **kwargs): try: print('self.picture >>>>>>> ', self.picture) # works fine img = load_img(self.picture, target_size=None) print('img >>>>>>', img) # does not work img_arr = img_to_array(img) except: print('classification failed') super().save(*args, **kwargs) The image gets saved fine to the database, but it the code when I am using 'load_img' doesn't work (as the print statement below does not run) -
Need to remove apscheduler jobs created without an ID
I'm using apscheduler in a Django 2 application. When creating my scheduler and adding the job, I used replace_existing=True but forgot to add an ID for the job. Now, I have several instances of the same job running in Production. How can I remove the extra apscheduler jobs? I have tried get_jobs() and print_jobs() with no luck. Is there a method to view, modify, & delete existing job stores? scheduler = BackgroundScheduler() scheduler.get_jobs() # and scheduler.print_jobs()