Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin, how can I add the FK selector in a StackedInline record
Given the following models : class Person(models.Model): name = models.CharField(max_length=50) family = models.ForeignKey( "Family", related_name="members", on_delete=models.CASCADE ) def __str__(self) -> str: return self.name class Family(models.Model): name = models.CharField(max_length=50) def __str__(self) -> str: return self.name And the following admin settings : class PersonAdmin(admin.StackedInline): model = Person list_display = ("name", "family") extra = 0 class FamilyAdmin(admin.ModelAdmin): model = Family list_display = ("name",) inlines = [PersonAdmin] extra = 0 admin.site.register(Family, FamilyAdmin) I would like to be able, from the Family edit page, to change the family of a person. Say I have Person A belonging to Family 1, I would like to be able to "migrate" this person to another family from the family edit page. Unfortunately, even if I explicitly specify the fields in the PersonAdmin class, the dropdown won't show. Any help or even a simple tips to know where and what to look would be greatly appreciated. I've tried looking for a solution on Django Admin Cookbook, on Google and on SO, but haven't found a solution to this and I'm pretty much a django (admin) noob. -
Django Static File not Updated
I am working on Django 4.1 on Windows locally and found that my static file did not update when I modified it, even the content showed on http://127.0.0.1/static/app_name/styles/css_name.css is the old CSS file. This issue suddenly happened after almost 1 year of development. In setting.py: DEBUG = True STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') And I have already tried the following method: Hard Reload Ctrl+F5 Clear Browser Cache Reboot/Restarting Browser/Server/Computer Run server on another port Open in Incognito Window Use another Computer to Test Ran python manage.py collectstatic/python manage.py collectstatic --clear/python manage.py collectstatic --noinput --clear, in here I found that after I ran this command, the modified static files will change back to the original unmodified version. Add a random tag at the end when loading the static file, /static/app_name/styles/css_name.css?v=aCtZoGSzObVTeNCAbWjPyLpyStrYek6A In setting.py add STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' Add the following in urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, view=cache_control(no_cache=True, must_revalidate=True)(serve)) All of the above methods didn't solve my issue. I saw someone has suggested Restart gunicorn/nginx will help, but seem it is on Linux but not Windows. What can it be? Maybe Django is saving some old static files somewhere and fetches them every time? -
How to let an authenticated user like a blog post in Django, update the like count and change the color of the heart icon
I started building my first Django Project a few days ago and I've been making progress, but for the past two days I've been stuck with the problem stated in the post's title. I can't seem to implement the like functionality in my web application. I'm going to just post the parts of my code that I believe would be helpful in aiding me. so, in my models.py I have - class Post(models.Model): image = models.ImageField() title = models.CharField(max_length=255) slug = models.SlugField(unique=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='posts', default='uncategorized') post = models.TextField() date = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) in my views.py I have - @login_required def like_post(request, post_id): post = get_object_or_404(Post, pk=post_id) if request.method == 'POST': if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.like_count -= 1 else: post.likes.add(request.user) post.like_count += 1 like = Like(user=request.user, post=post) like.save() post.save() return JsonResponse({'like_count': post.like_count}) else: return HttpResponseBadRequest() in my urls.py I have - path('like_post/<int:post_id>/', views.like_post, name='like_post') in my post_list.html I have - <form method="POST" action="{% url 'article:like_post' post.pk %}"> {% csrf_token %} <button class="like-button" data-post-id="{{ post.id }}"><i class="fas fa-heart{% if post.likes.filter(id=request.user.id).exists %} liked{% endif %}"></i>{{ post.like_count }}</button> {% endif %} <button class="comment-button"><i class="fa-solid fa-comment"></i>5 comments</button> </form> underneath the … -
django "copyOnWrite" for default model instances
Suppose I have a django application that provides Exercises. Those exercises have sub-categories and principles they belong to. Each Exercise belongs to one or no user. Simplyfied, they look like that: model Category(models.Model): owner = models.ForeignKey(AUTH_USER_MODEL, null=True, default=None) name = models.TextField() model SubCategory(models.Model): name = models.TextField() category = models.ForeignKey(Category, null=False) model Exercise(models.Model): owner = models.ForeignKey(AUTH_USER_MODEL, null=True, default=None) sub_categories = models.ManyToManyField(SubCategory) principles = models.ManyToManyField(Principles) # some other fields # ... What I want, is provide defaults (owner = None) for newly registered users. This would mean copying all principles, categories, subcategories and exercises upon the users registration. In addition, if I want to add a new exercise as default, I have to copy it for every user. I have already implemented the logic for copying everything (exchanging the foreign keys, etc.) This means that every user operates on their own set of data. No special cases except for the creation of new defaults. However, suppose I have 500 users and 100 default exercises, this amounts to 50k exercises alone. (Not to speak about the ~10 categories, with ~20 sub-categories each and ~120 principles) Seems not to scale too well. My second approach is some sort of "copy on write", where I … -
DJango forms that allow you to change the database of a specific user
I'm creating a Django social network application. My function intakes the request from a logged in user and changed their respective details based on the input of their forms. Forms.py class ProfileForm(forms.ModelForm): class Meta: model = AppUser fields = ['bio','profileimg'] Model.py class AppUser(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='blank-profile-picture.png') def __str__(self): return self.user.username settings.html <form id="profile_form" method="post" action="/home/" enctype="multipart/form-data"> {% csrf_token %} {{ profile_form.as_p }} <input type="submit" name="submit" value="submit" /> </form> This is my current views code: `def settings(request): user_profile = AppUser.objects.get(user=request.user) if request.method == 'POST': profile_form = ProfileForm(request.POST or None,request.FILES or None, instance=user_profile) if profile_form.is_valid(): profile_form.save() else: return HttpResponse('Form is invalid') else: profile_form = ProfileForm(instance=user_profile) return render(request, 'settings.html', {'profile_form': profile_form})` I tried running the code but nothing happens in the database -
Django and celery tasks - how to display celery progress when redirecting
Hi I have a broad question about using celery, redis and django (along with celery-progress). I have a django cbv with a form. Upon a post request this starts some celery processes and I use a modified version of celery-progress to update the page with a progress bar for each task. I'm struggling to find the best way to do this in terms of redirection of the request. I have tried two ways: 1. class MyView(FilterView) template_name = '/path/to/template1.html' # code to create form in django-tables2 def post(self, request, *args, **kwargs): self.context = {'server': SERVER} submit = request.POST.get('submit', None) if submit: ids = request.POST.getlist('report_form') # get queryset from selected IDs qs = MyModel.objects.filter(id__in=ids) # create empty dictionary to store id and celery task task_dict = {} # loop through queryset for obj in qs: # execute report creator method (celery task) task = self.celery_create_reports(id=obj.id, user_id=request.user.id) # add obj as key and task id as value to dict task_dict[obj] = task.id logger.info(task.id) logger.info(f"task_dict={task_dict}") # add dict to context context = {'task_dict': task_dict,} # direct to different template template_name = '/path/to/template2.html' return render(request, template_name, context) return render(request, self.template_name, self.context) def celery_create_reports(self, id, user_id): """ """ # execute task return download_technical_reports.delay(id=id, user_id=user_id) ^ … -
cumulative sum on jsonfield dict - django - postgresql
I have a fixed set of product_ids (eg 0, 1, 2, 3) My shoppingcart model has a jsonfield containing a dict indicating how many products it has of each product_id: from django.db import models class ShoppingCart(models.Model): stats = models.JSONField() With for one object stats may be: stats = { "0": 4, # has 4 products of id 0 "3": 1, # has 1 product of id 3 } And another object my have: stats = { "0": 1, # has 1 product of id 0 "1": 1 # has 1 product of id 1 } Now I would like to calculate how many products there are in total of each product id, preferably using database functions on the jsonfield in django. For this example, the result should be: counts = { "0": 5, "1": 1, "2": 0, "3": 1 } Is there an efficient way of calculating this? Don't really know how to tackle this without looping over all objects. -
Django rest framework permission by custom role
I using Django Rest Framework and I have custom User model where is column Role and Hash Model.py class User(AbstractUser): Role = models.CharField() Hash = models.CharField() Serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'Role', 'Hash','is_staff') View.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsAuthenticated] this working fine! And my question is possible create view which show fields according by Role? For example... If user with admin role login then see everything.. fields = ('id', 'username', 'first_name', 'last_name', 'Role', 'Hash','is_staff') But if login user with role for example mamager then he see just this. fields = ('id', 'username', 'first_name', 'last_name', 'Role','is_staff') -
zsh: command not found: python | I just want my python files to run again
I was messing around with Django for a task on my bootcamp and now my VSCode won't run my python files using the run button in the top right. Here's what I see in my IDE: garethmorton@MacBook-Pro T28 2D Lists % python -u "/Users/garethmorton/VSCode Python/T28 2D Lists/minesweeper.py" zsh: command not found: python garethmorton@MacBook-Pro T28 2D Lists % If I right click and select run Python file in terminal my code runs and I get this: /usr/local/bin/python3 "/Users/garethmorton/VSCode Python/T28 2D Lists/minesweeper.py" garethmorton@MacBook-Pro T28 2D Lists % /usr/local/bin/python3 "/Users/garethmorton/VSCode Python/T28 2D Lists/minesweeper.py" How do I fix the file path so that I can just run the code like I used to? thanks I have tried a few things I was told to do but to be honest I don't understand it enough to explain. I would love to just be able to delete the IDE and reinstall. By the way I'm on mac so I'm not sure if that makes things more complicated I definitely have the python extension installed.. everything should be installed and ready because ive been running python code for months on my bootcamp -
Does indentation matter in django?
{% if object.name== '' %} {% block name %}{{ object.name}}{% endblock name %} {% else %} {% block name %} {{ object.alternate_name}} {% endblock name %} {% endif %} I have this code in Django and for some reason, I get the error that the block name has been repeated twice and that seems impossible because they're inside an if-else statement. However, I realized my indentation looks like it did above. I'm not sure whats causing this. -
Ckeditor - RichTextField in Template doesn't work - Django
I am trying to display the RichTextField in a Django Template. In the Admin Panel it works but not in the template. My Template called create.html: {% block main %} <div class="blocker" style="height: 100px;"></div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Absenden</button> </form> {% endblock %} Forms.py: class Create(forms.ModelForm): content = RichTextField() title = forms.CharField(label='title', max_length=100) class Meta: model = Post fields = ['title', 'content'] Views.py def create(request): if request.method == 'POST': form = Create(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] Post(title=title, content=content).save() return redirect("../blog") else: form = Create() return render(request, 'create.html', {'form': form}) Thanks for answering :D I tried different things in the forms. -
Task not executed in Django's Celery
Since I am not an English speaker, I use translation tools to write my text. Please help me. Task not executed Here are the execution environment and messages Local PC OS windows 10 Python 3.8 DB Server CentOS 7.3 Redis 4.0.6 psql (PostgreSQL) 10.4 pip Package (relevant parts only) Package Version celery 5.2.7 Django 3.2 django-celery-results 2.4.0 django-redis 5.2.0 redis 4.1.1 *PROJECT\prj\settings.py CELERY_BROKER_URL = 'redis://:' + REDIS_PASSWORD + '@' + REDIS_HOST + ':6379/1' CELERY_RESULT_BACKEND = 'django-db' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TIMEZONE = 'Asia/Tokyo' CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 PROJECT\prj_init_.py from .celery import app as celery_app __all__ = ('celery_app',) PROJECT\prj\celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'prj.settings') app = Celery('prj') app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') PROJECT\common\task.py from celery import shared_task @shared_task def load_croeds_csv(csv_file): print("start") print("end") return "ok" PROJECT\manegements\view.py class ProhibitedAreaCsvRegView(ContextRootStaff, FormView): template_name = 'manage/prohibited_area_csv.html' form_class = ProhibitedAreaCsvForm def get_context_data(self, **kwargs): context = super(ProhibitedAreaCsvRegView, self).get_context_data(**kwargs) title = "" context.update({ 'title': title, 'form': self.form_class() }) return context def form_valid(self, form): context = self.get_context_data(form=form) csv_file = form.cleaned_data["csv_file"] temp_path = save_csv_file(csv_file) result = load_croeds_csv.delay(temp_path) print(result.state) context.update({ 'result': result }) return self.render_to_response(context=context) (venv) PROJECT>celery -A prj worker -l info -------------- celery@HP1-USER10 v5.2.7 (dawn-chorus) --- … -
Django model unique constraint based on existing model data?
Is it possible to make reference to existing model data, as part of a Django unique constraint check? For example, class MyModel(models.Model): .... my_field = models.IntField(...) class Meta: constraints = [ models.CheckConstraint( check=models.Q(my_field__gte=MyModel.objects.all().last().my_field, name="example_constraint" ] In this pseudocode example, I query MyModel, fetching the latest record, and use the value of it's 'my_field' property as part of the constraint, when adding a new MyModel. -
How to change string representation in django
I have model with a str function def __str__(self): return f"{self.first_name} {self.last_name}" //output for example foo bar Now i a specific form with a dropdown menu filled with the model above. In the dropdown menu the options are showed as the str from the model (sow foo bar). In this model however i want to show only the lastname. How can ik change the str function for just this form ? -
Why django showing 'function' object has no attribute 'objects'?
'function' object has no attribute 'objects' is being shown when I try to fetch objects from database I was following code with harry playlist on django ,and trying to fetch product from database my problem.I have created 3 products in admin panel. I saw some solutions to my problem ,where the problem was solved by changing the function name. But my problem seems to be different. this is my models.py enter image description here function in view.py where I make the call....error showing on the line7 enter image description here trying to render it in html enter image description here -
How do I stop the camera after QR code is scanned?
I am using instascan.min.js for my QR scanner. According to the documentation, I simply need to add in scanner.stop() to my script to terminate the camera session once it has scanned a QR code. I am not sure where in the javascript code I can add that line or am I supposed to write another function? Have been stuck on this for quite some time. Hope to seek any assistance. Thank you! <script> var app = new Vue({ el: '#app2', data: { scanner: null, activeCameraId: null, cameras: [], scans: [] }, mounted: function () { var self = this; self.scanner = new Instascan.Scanner({ video: document.getElementById('preview'), scanPeriod: 5}); self.scanner.addListener('scan', function (content, image) { self.scans.unshift({ date: +(Date.now()), content: content }); }); Instascan.Camera.getCameras().then(function (cameras) { self.cameras = cameras; if (cameras.length > 0) { self.activeCameraId = cameras[0].id; self.scanner.start(cameras[0]); } else { console.error('There is no camera.'); } }).catch(function (e) { console.error(e); }); }, methods: { formatName: function (name) { return name || '(unknown)'; }, selectCamera: function (camera) { this.activeCameraId = camera.id; this.scanner.start(camera); this.scanner.stop(camera) } } }); </script> -
Django use related_name in all query set
So I have model class Category(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='upload') created_at = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=128) updated_at = models.DateTimeField(auto_now=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) I want to make response look like { title: '', children: { title: '', chidlred:{ title: '', children } } } Im trying to use this in my views: @api_view(('GET',)) @permission_classes((AllowAny,)) def get_all_cats(req): queryset = Category.objects.all() for item in queryset: item['sub'] = queryset.children But it gives me enter image description here I understand I can use single query like Category.objects.first() and them use .children on it But i need all categories Thanks you so much! -
Python or JavaScript POST HTTP 1.1 error 404
I use python and JavaScript to make the website that you can register by linking with SQl. However, when I use the command flask run, there is POST /register HTTP 1.1 error. I can't register on the website and the website shows "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." I would like to know that is the py or js is incorrect or something with the server. Thank you in advance I would like to know that is the py or js is incorrect or something with the server. -
How to filter by request user in Django-filter model
Im using django-filter package and i want to know how can i pass queryset in ModelChoiceFilter of request user in my django-filter model filters.py class PresenceDateFilter(django_filters.FilterSet): presence_info__counter_presence = ModelChoiceFilter(queryset=CounterParty.objects.filter(counter_user=request.user)) #request.user is not working work_date = DateTimeFromToRangeFilter( widget=django_filters.widgets.RangeWidget( attrs={'type': 'date', 'class': 'form-control'}, )) class Meta: model = PresenceDetailInfo fields = ('presence_info__counter_presence', 'work_date', ) -
Django e-commerce
I am having trouble saving and viewing the order history of my shopping cart after checkout. I am saving the order in the checkout session and trying to view it with the order history view. @login_required def order_history(request): orders = Order.objects.filter(user=request.user).order_by('-date_ordered') return render(request, 'order_history.html', {'orders': orders}) stripe.api_key = settings.STRIPE_SECRET_KEY YOUR_DOMAIN = @csrf_exempt def create_checkout_session(request): if request.method == 'POST': try: cart_items = CartItem.objects.filter(user=request.user) line_items = [] total_price = 0 for item in cart_items: line_items.append({ 'price': item.item.stripe_price_id, 'quantity': item.quantity, }) # Create checkout session with line items and total price checkout_session = stripe.checkout.Session.create( line_items=line_items, mode='payment', success_url=YOUR_DOMAIN + '/success', cancel_url=YOUR_DOMAIN + '/cancel.html', automatic_tax={'enabled': True}, ) # Create a new Order object and save it to the database order = Order.objects.create( user=request.user, total_price=sum(item.item.price * item.quantity for item in cart_items), ) order.checkout_session_id = checkout_session.id order.save() # Associate each cart item with the order instance for item in cart_items: item.order = order item.save() # Clear the user's cart cart_items.delete() except Exception as e: return HttpResponse(str(e)) return redirect(checkout_session.url) else: return HttpResponse("This page is only accessible via POST requests") @csrf_exempt def complete_hook(request): # Retrieve the request body and the Stripe signature header payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: # Verify the Stripe signature event … -
Access multilevel v-model from HTML (Nested element)
The HTML code is here <section id="id_element"> <label for="x1">x1 </label> <input type="text" id="x1" v-model="product.xs.x1" ></input> <label for="x2">x2</label> <input type="text" id="x2" v-model="product.xs.x2" ></input> </section> here is my javascript : <script> const create = Vue.createApp({ delimiters: ['[[', ']]'], data() { return { product : { xs: { "x1" : "alpha", "x2" : "beta" }, ys: { "y1": "one", "y2": "two", "y3": "three", "y4": "four" } } } } create.mount("#id_element"); </script> I want to access a nested element, but i had the error of Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'x1') how to access a multi level vue.js element from HTML. I tried both : v-model="product.xs["x1"]" and v-model="product.xs.x1" So please anyone having a solution for this, it will be great. -
Access Variable in Python fstring in Django Template
I have created a variable called item using a fstring which is a combination of other variables: item = f'{item_id}_{flavour}_{strength}' Is there a way to now access the variables within this fstring to display them in a django template. At the moment all I have done is pull the whole item string into the template: <td class="py-3"> <p class="my-0"><strong>{{ item.product.name }}</strong></p> <p class="my-0"><strong>Flavour: </strong>{% if item.product.has_flavours %}{{ item.item|upper }}{% else %}N/A{% endif %} </p> Which renders in the html template as: front end display I want to access the flavour variable in the string and the strength variable in the string and display them in the template against the Flavour and Strength headings. -
Are there alternative fields for many-to-many?
I have this code in models.py (left only key fields for easier perception): class Album(models.Model): title = models.CharField(max_length=200) class Song(models.Model): album = models.ManyToManyField('Album', through='AlbumSong') class AlbumSong(models.Model): album = models.ForeignKey('Album') song = models.ForeignKey('Song') serial_number = models.CharField(max_length=3) And admin.py: class SongsInline(admin.TabularInline): model = AlbumSong fields = ['song', 'serial_number'] extra = 0 @admin.register(Album) class AlbumAdmin(admin.ModelAdmin): inlines = [SongsInline] Using TabularInline means that the songs will be shown in the dropdown lists. Imagine that there are 100 songs in one album. Then there will be 100 dropdown lists. And it's hard to edit. What are alternative more convenient field types? It is important that on the edit album page I should be able to create and delete songs. -
Django - Jsonfield get all values in an array without specifing an index
Assume we have a queryset of the MyJsonModel. How can I get all json key-values for lets say key "a" in my jsonfield "a_json"? Lets assume each a_json include a list with multiple dictionaries which all have the "a" key. How can I then get those "a" key-values in an Array via .values_list or values? So that it results in tuples where each of them represent an object and the "a" key of its "a_json" field. I couldn't find anything online related to this question. I am using django=4.1 and postgres -
Use Azure active directory as custom authentication backend for Django
I have Django running on an Azure web app and have followed this example to integrate the MSAL library so that users from the active directory can log in. This works to the extent that I can use @ms_identity_web.login_required in my views to limit access to specific pages only to sign in AD users. However, what I'm really aiming to do is to use the active directory as a custom authentication backend so that all django users come from the the active directory and that they can all access the admin section. My employer unfortunately does not allow me to use any third-party packages such as django_microsoft_auth though. For now I've read the Django documentation, particularly the section on Customizing authentication in Django. That clarifies some things, but I am still at a loss about how to proceed as every answer I've found so far recommends using some third-party package to implement some custom backend. If anyone can point me in the right direction in terms of how to proceed I would appreciate it immensely.