Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to delete a comment from a post in django
I am currently trying to delete a comment from my database via a button in django template. Model looks like this from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField from profiles.models import UserProfile class Post(models.Model): user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='user_posts') title = models.CharField(max_length=220, unique=True) location = models.CharField(max_length=220) rating = models.DecimalField( max_digits=6, decimal_places=2) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="activity_post") updated_on = models.DateTimeField(auto_now=True) description = models.TextField() featured_image = CloudinaryField('image', blank=False) created_on = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name='activity_likes', blank=True) like_count = models.BigIntegerField(default='0') class Meta: ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() def liked_by_user(self): return self.likes.values_list('id', flat=True) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="user_comment") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_on'] def __str__(self): return f"Comment {self.body} by {self.name}" Delete function def delete_comment(request, post_id): users_comment = get_object_or_404(Comment, post=post_id) users_comment.delete() return redirect(reverse('activity')) URLS from . import views from django.urls import path urlpatterns = [ path('like/', views.like, name='like'), path("add/", views.add_post, name="add_post"), path('edit/<int:post_id>/', views.edit_post, name='edit_post'), path('delete/<int:post_id>/', views.delete_post, name='delete_post'), path('edit_comment/<int:id>/', views.edit_comment, name='edit_comment'), path('delete_comment/<int:post_id>/', views.delete_comment, name='delete_comment'), path("activity/", views.PostList.as_view(), name="activity"), path('comment/<int:post_id>/', views.Comment.as_view(), name='comment'), path('searched_posts/', views.search_posts, name='searched_posts'), path('post/<int:post_id>/', views.post_detail, name='post_detail') ] here is the comment part that … -
Django 'list' object attribute 'startswith'
I've been working to deploy my Django app to AWS but suddenly can't run in local due to an attribute error: 'list' object has no attribute 'startswith' Tracebacks i'm getting when I attempt to runserver include bootstrap and various django/core listings. I can't seem to find any 'startswith' issues in my urls.py or views.py files but hope there is any easy solution. BTW: I am not attempting to upload any csv and removed the 'script' directory from my project to make sure there wasn't some errant call going there. -
How to disable a form from views.py .?
How do I achieve the below: @login_required def close_auction(request,listing_id): listing = Listing.objects.get(pk=listing_id) if request.method == "POST": listing.Auction_closed = True **Disable the Bids on the Listing And display some message such as "The auction is Closed"** return render(request, "auctions/index.html",{ "listing": Listing.objects.get(pk=listing_id), "user": User.objects.get(pk=request.user.id), "owner": listing.owner }) Below is my code in index.html: <!-- if the user is the one who created the listing: they can close the listing go to the close_auction view to close --> {% if user == owner %} <form action="{% url 'close_auction' listing.id %}" method="post"> {%csrf_token%} <button>Close this Listing</button> </form> {% endif %} Below is my models.py: class Listing(models.Model): Title = models.CharField(max_length=64) Description = models.TextField(max_length=500) Category = models.CharField(max_length=16) Starting_Bid = models.IntegerField() Image = models.ImageField() Auction_closed = models.BooleanField(default=False) #def bid(self): #return self.Starting_Bid class User(AbstractUser): watchlist = models.ManyToManyField(Listing, blank= True, related_name="watcher") listing_owner = models.ForeignKey(Listing,on_delete=models.CASCADE,related_name="owner",null=True) class Bid(models.Model): Bid_amount = models.IntegerField() listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids") bid_placed_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bid_placer", null=True) What I am trying to achieve here: If the user is the owner of the listing then he/she should be able to 'close the listing'. Once the listing is closed, the 'Place a Bid' form should be disabled and some message should be shown instead. -
Showing items on or after the current date and time
I asked a similar question before, regarding my Django site that I am developing and I am trying to only show users appointments on or after the current date and current time. It was recommended that I try this: now = datetime.today() appointment_wanted = Appointment.objects.filter( title=title_wanted, date__gte=now) However, once I started to test it, I noticed it works correctly for all appointments except ones that are within four hours of the current time today. -
Nginx not calling static files on site
Django works fine but static files are not called server { listen 80; server_name www.bakuklinik.shop bakuklinik.shop; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /root/myprojectdir/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } settings.py STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'static') I'm using Ubuntu 20.04 on DigitalOcean You can view the site here: http://bakuklinik.shop/ -
Python error when using Django and Djongo on fresh computer
I recently reformatted my computer and had to setup my enviornment. I pip installed django, djongo, and then installed MongoDB with Compass. I pulled my code from Github and tried to run it. I get the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python310\lib\site-packages\django\db\utils.py", line 113, in load_backend return import_module("%s.base" % backend_name) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Python310\lib\site-packages\djongo\base.py", line 12, in <module> from .cursor import Cursor File "C:\Python310\lib\site-packages\djongo\cursor.py", line 4, in <module> from .sql2mongo.query import Query File "C:\Python310\lib\site-packages\djongo\sql2mongo\query.py", line 16, in <module> from sqlparse import parse as sqlparse ModuleNotFoundError: No module named 'sqlparse' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Python310\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] … -
Django Celery Task: AttributeError: type object 'Command' has no attribute '__annotations__'
I'm trying to set up a celery task which basically runs a script to deactivate a bunch of facilities inside a json file. I used to run it manually and it ran fine but now i get the following error when Celery tries to run it as a task: AttributeError: type object 'Command' has no attribute '__annotations__' Can anyone tell me why it is not working? This is the code i am using: tasks.py import requests import json from project.users.models import Facility from django.core.management.base import BaseCommand from config import celery_app IMPORT_URL = 'https://example.com/file.json' @celery_app.task() class Command(BaseCommand): def delete_facility(self, data): data = data if Facility.objects.filter(UUID=data, ReportedStatusField='closed'): print("Facility status already set to closed") else: facility, facility_closed = Facility.objects.update_or_create(UUID=data, defaults={ 'ReportedStatusField': 'closed' } ) print("Facility status set to closed") def handle(self, *args, **options): headers = {'Content-Type': 'application/json'} response = requests.get( url=IMPORT_URL, headers=headers, ) response.raise_for_status() data = response.json() for data, data_object in data.items(): if data in ["deleted"]: for data in data_object: self.delete_facility(data) -
Get input from user to use in django class based view
I have the following code: class ObjectiveCreate(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = Objective form_class = ObjectiveCreateForm template_name = "internalcontrol/objective_create_form.html" # Check that user is a consultant def test_func(self): user = self.request.user return user.is_consultant # Get user profile and entity and inject identity and entity into ObjectiveCreateForm def form_valid(self, form): user = self.request.user profile = UserProfile.objects.get(user=user) entity = profile.entity new_profile = UserProfile.objects.get(user=user, entity=entity) form.instance.consultant = new_profile form.instance.entity = entity return super().form_valid(form) # Enable use of self.request in form def get_form_kwargs(self): kwargs = super(ObjectiveCreate, self).get_form_kwargs() kwargs["request"] = self.request return kwargs It works well when the consultant works with only one entity. Within each entity, the consultant has only one profile, and so the profile can therefore be uniquely associated with the applicable entity. The problem is when the consultant works with more than one entity. That is what I would like to handle with the revised code. I cannot move beyond the line below with the elif: # Get user profile and entity and inject identity and entity into ObjectiveCreateForm def form_valid(self, form): user = self.request.user if len(UserProfile.objects.filter(user=user)) == 1: # As mentioned above, this section of the code works well. profile = UserProfile.objects.get(user=user) entity = profile.entity new_profile = UserProfile.objects.get(user=user, entity=entity) form.instance.consultant = … -
Distinct values on filtered queryset and 'Q' operator
I have these models: class Event(models.Model): title = models.CharField(max_length=200) [...] class dateEvent(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) [...] and in my views.py I want to create a query which selects an event given specific parameters (start date, etc.). I have no issues with my query: distinct = Event.objects.values('id').annotate(id_count=Count('id')).filter(id_count=1) events = Event.objects.filter(Q(dateevent__start_date_time__gte=start_date) & Q(dateevent__start_date_time__lte=end_date)) This pulls up more ideantical results if there is more than one dateevent for each event though, which I don't want. This is my attempt of getting distinct values, which fails with a 'QuerySet' object has no attribute 'Q' error. what am I missing? events = Event.objects.filter(id__in=[item['id'] for item in distinct]).Q(dateevent__start_date_time__lte=end_date).distinct().exclude(type='recording release').order_by('dateevent__start_date_time') -
Django. Model. how to create request and get value with two conditions
I have django Model below class Bid(models.Model): bid = models.DecimalField(max_digits=20, decimal_places=2, verbose_name="Bid") user = models.ForeignKey(User, on_delete=models.CASCADE) lot = models.ForeignKey(Lot, on_delete=models.CASCADE) how can I get username from field 'user' with two conditions: known 'lot' and max 'bid' value. Try explain, I know 'lot' and I need to get 'user' for this 'lot', where value of 'bid' is max. -
Autofill django fields when entering user ID
i have been searching for solution to auto fill all the fields in my execution profile page, 2 I have a modelform with seven fields: execution_number, matter, client, opponent, date, court, update.(date is set to auto_now and so does not appear in the form) basically all i want is when i enter execution_number it should automatically fill in all other fields that will inherent from the database. would appreciate the help, i am still a beginner in programing, so would appreciate the support :) MODELS from django.db import models class Execution(models.Model): COURT = ( ('Muscat', 'Muscat'), ('Seeb', 'Seeb'), ) execution_number= models.CharField(max_length =200, null= True) matter=models.CharField(max_length =200, null= True) client = models.CharField(max_length =200, null= True) opponent =models.CharField(max_length =200, null= True) date= models.DateTimeField(auto_now_add=True, null= True) court= models.CharField(max_length =200, null= True, choices = COURT ) update = models.CharField(max_length =200) def __str__(self): return self.execution_number VIEWS def search_execution(request): execution_number = request.execution_number # form = ProfileUpdateForm(request.POST, request.FILES) <-- remove if request.method == 'POST': form = Execution(request.POST, request.FILES, instance=execution_number) if form.is_valid(): form.save() # <-- you can just save the form, it will save the profile # user.save() <-- this doesn't help you, it doesn't save the profile and since user isn't changed you don't need to save … -
psycopg2.errors.UndefinedTable: relation "libman_classbooks" does not exist
I had mistakenly deleted my migration folders for all my apps in my project. I therefore had to redo makemigrations and migrate for each of those apps. When thence I try to access the specific areas with relational paths I get an error. relation "libman_classbooks" does not exist When I try to make some changes on the models, save and try to run makemigrations and migrate. this does not go on well but returns. django.db.utils.ProgrammingError: relation "libman_classbooks" does not exist. I have been forced to guess that I need to manually create the tables in the database. Using CREATETABLE. I don't know if this is the best option though. So I think my option may be possible in development thro' the pgAdmin, but what about in production? If CREATETABLE is the best option to take, how will I do it for the production database??. I already have data in my database which do not need interference. -
405 Error when trying to update picture in Django
I cannot update user profile_picture, I can update all other information related to a user but not their profile picture. When I try to update a profile_picture I get a null value for the picture and this error: Method Not Allowed: /update_profile/2/ [29/Apr/2022 14:11:16] "GET /update_profile/2/ HTTP/1.1" 405 13924 This is my API endpoint: path('update_profile/<int:pk>/', views.UpdateProfileView.as_view(), name='update_profile'), This is my UpdateProfileView: class UpdateProfileView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer def profile(request): if request.method == 'PUT': try: user = User.objects.get(id=request.user.id) serializer_user = UpdateUserSerializer(user, many=True) if serializer_user.is_valid(): serializer_user.save() return Response(serializer_user) except User.DoesNotExist: return Response(data='no such user!', status=status.HTTP_400_BAD_REQUEST) My UpdateUserSerializer: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = serializers.CharField(source='profile.city', allow_blank=True, required=False) country = serializers.CharField(source='profile.country', allow_blank=True, required=False) profile_pic = Base64ImageField(max_length=None, use_url=True, required=False) # serializers.ImageField(source='profile.profile_pic', use_url=True, required=False) class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'profile_pic'] # fields = UserDetailsSerializer.Meta.fields + ('city', 'country') extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}, 'city': {'required': False}, 'country': {'required': False}, 'profile_pic': {'required': False} } def update(self, instance, validated_data): profile_data = validated_data.pop('profile', {}) city = profile_data.get('city') country = profile_data.get('country') profile_pic = profile_data.get('profile_pic') instance = super(UpdateUserSerializer, self).update(instance, validated_data) profile = instance.profile if … -
Is there a way to filter out items from RelatedManager in a ModelViewSet?
I'm using DRF for a simple API, and I was wondering if there's a way to achieve this behavior: I've got two models similar to the following: class Table(models.Model): name = models.CharField(max_length=100) ... class Column(models.Model): original_name = models.CharField(max_length=100) name = models.CharField(max_length=100, blank=True, null=True) ... table = models.ForeignKey(Table, on_delete=models.CASCADE, related_name="columns") And their serializers as follows: class ColumnSerializer(serializers.HyperlinkedModelSerializer): table = serializers.HyperlinkedRelatedField( read_only=True, view_name="table-detail" ) class Meta: model = Column fields = ["url", "name", "table"] class TableSerializer(serializers.HyperlinkedModelSerializer): dataset = serializers.HyperlinkedRelatedField( read_only=True, view_name="dataset-detail" ) tags = serializers.SlugRelatedField( many=True, slug_field="name", queryset=Tag.objects.all() ) columns = ColumnSerializer(many=True, read_only=True) class Meta: model = Table fields = [ "url", "name", ... "columns", ] This returns me an output similar to { ... "results": [ { "url": "http://0.0.0.0:8001/api/tables/1/", "name": "some-name", "columns": [ { "url": "http://0.0.0.0:8001/api/columns/1/", "name": "id", "table": "http://0.0.0.0:8001/api/tables/1/" }, ... } which is totally fine. But what I'd really want to do is, if a Column has name=None, it's filtered out from every API ViewSet. I've managed to do it on the ColumnViewSet by doing queryset = queryset.filter(name__isnull=False), but I can't do it for the TableViewSet or others that might show a Column list. I've tried tinkering with the ColumnSerializer, but the best I could get from it was … -
Is it possible to rename the application's group name in Django?
For example, you have "Groups" and "Users" under "AUTHORIZATION AND AUTHENTICATION" (or something named like that). If you make a new app and register its model, it's gonna write out the name of the application. I want to rename that in the admin. -
GNUPLOT integration with web application
I would like to point out that I am just learning programming, so I am not so experienced. I would like to create a web application in django REST framework as backend and ractjs as front end, which would create graphs using gnuplot,I would like the application to work more or less like an overleaf where the user enters the commands from gnuplot and when the button is pressed the finished graph appears. My question is what's the best way to integrate or invoke gnuplot to work like that and what's tools i should use? I saw a similar topic on the forum but no answer to his question Text. Would javascipt be a good choice or would python be sufficient for such a task? Any tips are welcome. -
NoReverseMatch at /allbook Reverse for 'random_book' with arguments '('',)' not found. 1 pattern(s) tried: ['info/(?P<pk>[0-9]+)\\Z']
NoReverseMatch at /allbook Reverse for 'random_book' with arguments '('',)' not found. 1 pattern(s) tried: ['info/(?P[0-9]+)\Z'] views.py class MoreInfoView(View): def get(self, request, id): book_info = BookModel.objects.filter(id=id).first() stuff = get_object_or_404(BookModel, id=self.kwargs['id']) total_likes = stuff.total_likes() return render(request, 'bookapp/more_info.html', context={ 'id': id, 'book_info': book_info, 'book': BookModel, 'total_likes': total_likes, }) def random_book(self): book_pks = list(BookModel.objects.values_list('id', flat=True)) pk = random.choice(book_pks) book = BookModel.objects.get(pk=pk) return HttpResponse(book) html <li class="navigation"><a class="nav-link" href="{% url 'random_book' pk %}">random</a></li> url.py urlpatterns = [ path('', index, name='index'), path('allbook', AllBookView.as_view(), name='allbook'), path('addbook', AddBookView.as_view(), name='addbook'), path('register', RegisterView.as_view(), name='reg'), path('login', LoginView.as_view(), name='login'), path('logout', LogoutView.as_view(), name='logout'), path('info/<int:id>', MoreInfoView.as_view(), name='more_info'), path('profile', profileview, name='profile'), path('password-change', ChangePasswordView.as_view(), name='change_pass'), path('like/<int:pk>', LikeView, name='like_book'), path('info/<int:pk>', views.random_book, name='random_book'), -
i got decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
views.py @api_view(["POST", "GET"]) @permission_classes([IsAuthenticated]) def add_order(request, pk): print(request.user) customer = md.Customer.objects.get(pk=pk) if request.method == "POST": description = request.data['description'] price = request.data['price'] order = md.Order.objects.create(customer=customer, date_created=zt.now(), description=description, price=float(price), customer_total_when_created=customer.total_owe[0] ) try: is_paid = request.data['is_paid'] if is_paid == "on": who_paid = request.data['who_paid'] payment_method = request.data['payment_method'] who_took_money = request.user if who_paid == customer.name: order.who_paid = customer elif who_paid == customer.parent: order.who_paid = customer.parent order.payment_method = payment_method order.who_took_money = who_took_money order.date_paid = zt.now() customer.total = customer.total_owe customer.save() order.save() except: print("no payment succeed") order_api = OrderSerializer(order) return Response(order_api.data) customer_api = CustomerSerializer(customer) parent_api = CustomerSerializer(customer.parent) context = { "customer": customer_api.data, "parent":parent_api.data, "sample": [ {"description": "secreal", "price": "12.21", "is_paid": "on", "who_paid": "azra", "payment_method": "CARD"} ] } return Response(context) models.py class Order(models.Model): payment_method_list = [("CASH","CASH"),("CARD","CARD")] customer = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True,blank=True,) who_paid = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True,blank=True, related_name='%(class)s_requests_created') who_took_money = models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True, related_name='who_took_money') payment_method = models.CharField(choices=payment_method_list,max_length=4,default="CASH",blank=True,null=True) date_paid = models.DateTimeField(blank=True,null=True) date_created = models.DateTimeField(blank=True, null=True) date_modified = models.DateTimeField(blank=True, null=True, auto_now=True) is_paid = models.BooleanField(default=False, blank=True,null=True) customer_total_when_paid = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True) customer_total_when_created = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True) description = models.TextField(blank=True,null=True) price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True) def __str__(self): return self.description[0:12] from django.db.models.signals import post_save def update_total_owe_created_order(sender,instance,created,**kwargs): if created: order = instance customer = order.customer customer.total = customer.total_owe[0] customer.save() post_save.connect(update_total_owe_created_order,sender=Order) def update_total_owe_updated_order(sender,instance,created,**kwargs): if created==False: order = instance customer = order.customer customer.total = customer.total_owe[0] customer.save() post_save.connect(update_total_owe_updated_order,sender=Order) I have an … -
Django Gunicorn - Failed to find attribute 'application'
I had a Django/Gunicorn app running just fine, but after a code update it stopped working due to this gunicorn error. I don't think anything has changed regarding that setup, so I am at a loss as to why it won't work now. /etc/systemd/system/triform.service [Unit] Description=triform daemon Requires=triform.socket After=network.target [Service] User=django Group=www-data WorkingDirectory=/home/triform/django ExecStart=/home/triform/django/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ triform.wsgi:application [Install] WantedBy=multi-user.target /etc/systemd/system/triform.socket [Unit] Description=triform socket [Socket] ListenStream=/run/triform.sock [Install] WantedBy=sockets.target /home/triform/django/triform/wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'triform.settings') application = get_wsgi_application() in /home/triform/django/triform/settings.py: WSGI_APPLICATION = 'triform.wsgi.application' -
How to cache query data per request
I have a decorator that fetches some data from DB and modifies response context data. This decorator is applied to several views, the problem is that every time the decorator function is being executed it makes the DB query again. I would like to cache the result of a DB only per request, on page refresh/new request I would like to fetch data again. views.py def set_data(): def wrapper(request): # fetching data from db data = get_some_data_from_db() response = view(request) response.context_data["data"] = data return response.render() return wrap @set_data def view1(request): return TemplateResponse(request, "template1.httml", context) @set_data def view2(request): return TemplateResponse(request, "template2.httml", context) I've tried to use django-request-cache library, but this doesn't solve this problem. ANy idea how can i achieve it? -
How to Change django 404 error into own html design
File not found error come in django , i want to change into own html 404 code design page or replace it. What i do for change it? -
django using request in auth form(passwordchangeview)
class PasswordsChangeView( PasswordChangeView ): form_class = PasswordChangeForm success_url = reverse_lazy('password_success') ##admin filteration group = list(request.user.groups.values_list('name',flat = True)) the request in above is not defined , it works for my function which i have request, but in auth form i don't know how to pass the request, any idea role='admin' type = search( group ,role) extra_context={'t': type} -
Access decorators from multiple views in Django
As I am learning Django, I am running into this issue I have not found a solution for. Imagine I have 5 apps in my project: * project * accounts * profiles * products * services In my accounts project, I have all of the logic for authentication and have created a decorators.py file under accounts that I would like to check from any of the apps. Under accounts, in my views.py, I simply import the decorators.py as such: from .decorators import * At this point, however, I am not seeing how to import the same decorators.py from the views.py file in other apps. -
Save Django Model when list_editable fields are changed in Django Admin change_list view
I have a Django Model which I'm trying to update from the Admin change_list view when a field that is listed in list_editable has a change event fired. Right now the only way to save the updates is by clicking a "Save" button and then the page reloads. I don't want the page to reload at all. I just want it to update the model asynchronously. For example I have the following model. class Example(models.Model): name = models.CharField() hide = models.BooleanField(default=False) In the Admin Form I have class ExampleAdmin(admin.ModelAdmin): list_display = [ "name", "hide" ] list_editable = [ "name", "hide" ] When viewing the change list for Examples now I will see the values listed out with an editable text input for name and a checkbox for hide. I would like to listen for events on those inputs and when they are fired send an async request to update the specific model. -
Is this the correct way of making primary keys in django?
class profiles(models.model): customer_ID = models.IntegerField().primary_key Is this the correct way of making a primary key in django??