Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get max score of answers to a question by each user
I have these 2 models: class Question(models.Model): title = models.CharField(max_length=200) # other fields class Answer(models.Model): user = models.ForeignKey(User) question = models.ForeignKey(Question) score = models.IntegerField() each user can answer a question multiple times. Imagine I have these answers: { "user": 1, "question": 1, "score": 50 }, { "user": 1, "question": 1, "score": 100 }, { "user": 2, "question": 1, "score": 100 }, { "user": 2, "question": 1, "score": 200 }, { "user": 2, "question": 2, "score": 100 }, { "user": 2, "question": 2, "score": 200 } I want a query to give me this result: { "user": 1, "question": 1, "max_score": 100 }, { "user": 2, "question": 1, "max_score": 200 }, { "user": 2, "question": 2, "max_score": 200 } I want all of the max scores of each user to each answer. -
Django DRF Custom user model field "updated" (last login) is not being updated upon login
I have a problem with the user fields "created" and "updated". First of all, there's a "Last login" field (I assume this represents "updated") in admin which is always empty. There's no field for "created" it seems. Secondly, Created and updated do get initiated with the account creation datetime, however it is not updated upon login. I'm using Django 4.0 RegisterSerializer class RegisterSerializer(UserSerializer): password = serializers.CharField(max_length=128, min_length=8, write_only=True, required=True) email = serializers.EmailField(required=True, write_only=True, max_length=128) class Meta: model = User fields = ['id', 'username', 'email', 'password', 'is_active', 'created', 'updated', 'testfield'] def create(self, validated_data): try: user = User.objects.get(email=validated_data['email']) except ObjectDoesNotExist: user = User.objects.create_user(**validated_data) return user User model class User(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True) username = models.CharField(db_index=True, max_length=255, unique=True, blank=True) email = models.EmailField(db_index=True, unique=True, null=True, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) testfield = models.CharField(max_length=255, blank=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return f"{self.email}" UserSerializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'is_active', 'created', 'updated'] read_only_field = ['is_active', 'created', 'updated'] I followed this guide for the user setup https://dev.to/koladev/build-a-crud-application-using-django-and-react-5389 -
How to migrate all the data of an sqlite database to cockroachdb (for a django project)
I created a Django application and deployed it for testing purposes. I now have data which i would not like to lose, but i want to use cockroachDB for storing the web-app data. The SQLite database is the one django creates automatically while applying migrations. Is there a way to move all that data to my cockroachDB cluster? I will be using cockroachDB for my database. Thank you for your time -
Can you connect Django and React JS to the servers and SQL databases?
I have been recently working on my note-taking app. I wanted to build it in Django and React JS. Backend and front end. The question is can I connect all of this to the SQL databases and connect it to servers where will be stored data of the users? -
How to reduce for loops in html in Django?
I tried the following for loops and if statements in django html, but it takes so long to load one page. First, here is the html: {% for time in TIME_CHOICES %} <h1>{{time}}</h1> {% for each_date in dates_in_month %} {% if each_date not in weekends %} {% for class in classes %} {% if class.date == each_date and class.time == time %} <h1>{{class}}</h1> {% endif %} {% endfor %} {% else %} <h1>weekday</h1> {% endif %} {% endfor %} {% endfor %} I think this is because I have too many for loops and if statements happening in my html. Is there anyway I can increase the speed? Or is there any way I can do the same thing in django views(I am using generic list view, so I need some code for the get_context_data)? Thank you, and please leave any questions you might have. -
Django: Best way to render model instances based on authorization
I want to ask you about a recommendation how to solve this issue I'm struggling right now. My objective is to have a simple page which renders my model instances one after another, but based on the user it should skip certain instances. models.py class Item(models.Model): creator= models.ForeignKey(User,null=True, on_delete=SET_NULL) title = models.CharField(max_length=200) private = models.BooleanField(null=False, blank=True, default=False) views.py def topics(request): items=Item.objects.all() context={'items' : items} return render(request, 'items.html', context) main.html {% for item in items %} <div> <p>{{item.title}}</p> </div> {% endfor %} Question: If 'private' is true I want to skip that item if the user is not staff. This way I can separate the items based on this boolean. What is the recommended/best way to do that? I don't want a if/else statement in html and then repeat the code. It's getting a messy as the project grows. Thanks in advance! -
Why Django's OneToOneField returns 500 if relation aready exists
In a Django REST Framework POST view, is there any way to avoid an HTTP 500 if the OneToOneField relation already exists? Instead, it would be great to get an HTTP 400. Thanks. -
How to solve PUT method is not allowed in drf?
I've a model: class ListingPrice(Timestamps): price = models.ForeignKey("Price", on_delete=models.CASCADE) location = models.ForeignKey("location", on_delete=models.CASCADE) class Meta: unique_together = ["price", "location"] class Price(Timestamps): package = models.ForeignKey("products.Package", on_delete=models.CASCADE) locations = models.ManyToManyField("location", through="ListingPrice") price = models.DecimalField(max_digits=11, decimal_places=3) with a serializer: class LocationSerializer(serializers.ModelSerializer): name = LocalizedField() class Meta: model = location fields = ['id', 'name'] class PriceSerializer(serializers.ModelSerializer): locations = LocationSerializer(many=True, read_only=True) class Meta: model = Price fields = ['package', 'locations', 'price'] def create(self, validated_data): print("validated_data, validated_data) and viewset: class PriceViewSet(ModelViewSet): queryset = Price.objects.all() serializer_class = PriceSerializer ordering = ['id'] permissions = { "GET": ["view_minimum_listing_price", ], "POST": ["add_minimum_listing_price", ], 'PUT': ['update_minimum_listing_price', ], 'DELETE': ['delete_minimum_listing_price', ], } In testing I'mm using the following: data = { "price": 15, } response = self.client.put(path=self.url, data=data, format='json', args=[1]) I'm trying to update the price in the instance with id 1, but neither put or update is not allowed? How to overcome this and update it? edit: urls.py router = SimpleRouter() router.register('listing_price', PriceViewSet, basename='listing_price') -
Page not found (404) The current path, register/register, didn’t match any of these
on running server browser show I am trying to save the the data into database on submitting the form the browser show page not found error and and same wrong address. http://127.0.0.1:8000/register/register while i am rendering the homepage on submitting the form. views.py file from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth.models import User def homePage(request): return render(request,"index.html") def register(request): if request.method=='POST': firstname = request.POST.get('fname') lastname = request.POST.get('lname') email = request.POST.get('email') password = request.POST.get('password') username = request.POST.get('uname') user = User(first_name=firstname,last_name=lastname,email=email,password=password,username=username) user.save() return redirect('/') return render(request,"register.html") def course(request): return HttpResponse("welcome to my 2nd page") def courseDetail(request,courseid): return HttpResponse(courseid) urls.py file from django.urls import include, path from django.contrib import admin from django.urls import path from name import views import name urlpatterns = [ path('admin/', admin.site.urls), path('',views.homePage), path('register/',views.register), path('course/',views.course), path('course/<courseid>',views.courseDetail), ] -
I want to link 2 models like a field abc linked to abcd model is in mymodel and a field in mod linked to mymodel is in abcd django
I want to link 2 models like a field abc linked to abcd model is in mymodel and a field in mod linked to mymodel is in abcd but shows mymodel isn't define because it is written after abcd model but if I replace the place of both model mymodel written above and abcd written after then mymodel shows that abcd isn't define... -
Django GraphQL subscriptions using websockets within the dockerized API works fine locally but fails in production
I have a Django GraphQL API and an Angular 12 UI that uses Apollo to interface with GraphQL. The Django app is dockerized and uses NGINX. These are my files:- settings.py (only relevant sections pasted below) INSTALLED_APPS = [ 'channels', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # This is for altering the domain name in the migration 'app', 'graphene_django', 'graphql_jwt.refresh_token.apps.RefreshTokenConfig', 'graphql_auth', 'rest_framework', 'django_filters', ] GRAPHENE = { 'SCHEMA': 'project.schema.schema', 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware', ], "SUBSCRIPTION_PATH": "/ws/graphql" } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'common.utils.UpdateLastActivityMiddleware' ] AUTHENTICATION_BACKENDS = [ 'graphql_auth.backends.GraphQLAuthBackend', 'django.contrib.auth.backends.ModelBackend', ] GRAPHQL_AUTH = { "ALLOW_LOGIN_NOT_VERIFIED": False } GRAPHQL_JWT = { "JWT_ALLOW_ANY_CLASSES": [ "graphql_auth.mutations.Register", "graphql_auth.mutations.VerifyAccount", "graphql_auth.mutations.ResendActivationEmail", "graphql_auth.mutations.SendPasswordResetEmail", "graphql_auth.mutations.PasswordReset", "graphql_auth.mutations.ObtainJSONWebToken", "graphql_auth.mutations.VerifyToken", "graphql_auth.mutations.RefreshToken", "graphql_auth.mutations.RevokeToken", ], 'JWT_PAYLOAD_HANDLER': 'common.utils.jwt_payload', "JWT_VERIFY_EXPIRATION": True, "JWT_LONG_RUNNING_REFRESH_TOKEN": True, 'JWT_REUSE_REFRESH_TOKENS': True, # Eliminates creation of new db records every time refreshtoken is requested. 'JWT_EXPIRATION_DELTA': timedelta(minutes=60), # Expiry time of token 'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7), # Expiry time of refreshToken } ROOT_URLCONF = 'project.urls' WSGI_APPLICATION = 'project.wsgi.application' ASGI_APPLICATION = 'project.router.application' REDIS_URL = env('REDIS_URL') hosts = [REDIS_URL] if DEBUG: hosts = [('redis', 6379)] CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": hosts, }, }, } router.py @database_sync_to_async def get_user(token_key): try: decodedPayload = jwt.decode( token_key, key=SECRET_KEY, … -
Getting NoReverseMatch___ Reverse for 'for_user' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['/(?P<username>[-\\w]+)/$']
I'm sorry if I'm repeating an already answered question. I have tried to look this up but can't seem to get a way around this bug. NoReverseMatch at /groups/ Reverse for 'for_user' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['posts/by/(?P[-\w]+)/$'] models.py ''' enter code here from groups.models import Group # Create your models here. from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable='False') group = models.ForeignKey(Group,related_name='posts', null=True,blank=True,on_delete=models.CASCADE) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html = misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse( 'posts:single', kwargs={'username':self.user.username, 'pk':self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['user','message'] ''' Views.py ''' enter code here class PostList(SelectRelatedMixin,generic.ListView): model = models.Post select_related = ('user','group') class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" def get_queryset(self): try: self.post_user = User.objects.prefetch_related("posts").get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.post_user return context class PostDetail(SelectRelatedMixin,generic.DetailView): model = models.Post select_related = ('user','group') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user__username__iexact=self.kwargs.get('username')) class CreatePost(LoginRequiredMixin,SelectRelatedMixin,generic.CreateView): fields = ('message','group') model = models.Post def form_valid(self,form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class DeletePost(LoginRequiredMixin,SelectRelatedMixin,generic.DeleteView): model = models.Post select_related = ('user','group') success_url = … -
Django get a value for annotated field based on condition?
I have a couple simple models and want to annotate query with field which value based on condition. class Book(models.Model): price = models.DecimalField('Price', null=True, default=None, max_digits=32, decimal_places=2) ... class Config(models.Model): city_prices = models.JSONField(default={"Paris": 10, "London": 15}, null=True) ... I've try to query this model like that: from django.db.models import F, When, Case, Subquery config = Config.objects.first() Book.objects.annotate(custom_price=Case( When(price__isnull=False, then=F('price')), When(price__isnull=True, then=Subquery(config.city_prices.get(F('city')))) ) the first "When" works good but the second one gets me an error. AttributeError: 'NoneType' object has no attribute 'all' I've tried to get rid of "F()" on second "When" and hardcore city name, but gets another error. When(price__isnull=True, then=Subquery(config.city_prices.get('London'))) AttributeError: 'int' object has no attribute 'all' This error shows that I get a value of "London" but Subquery try to query it. So I made a conclusion that when in previous query I've tried to use "F('city')" it got back None, and I think this because of F('city') refer to Config model rather than the Book. I've tried different approach but it's unsuccessful either. >>>from django.db.models.expressions import RawSQL >>>Books.objects.annotate(custom_price=RawSQL('SELECT d.city_prices ->> %s FROM CONFIG_CONFIG d WHERE d.id = 1', (F('price'),))) ProgrammingError: can't adapt type 'F' I read somewhere here that F() can't collaborate with RawSQL. Think the … -
How to get m2m field in validated_data?
I've a model: class ListingPrice(Timestamps): price = models.ForeignKey("Price", on_delete=models.CASCADE) location = models.ForeignKey("location", on_delete=models.CASCADE) class Meta: unique_together = ["price", "location"] class Price(Timestamps): package = models.ForeignKey("products.Package", on_delete=models.CASCADE) locations = models.ManyToManyField("location", through="ListingPrice") price = models.DecimalField(max_digits=11, decimal_places=3) with a serializer: class LocationSerializer(serializers.ModelSerializer): name = LocalizedField() class Meta: model = location fields = ['id', 'name'] class PriceSerializer(serializers.ModelSerializer): locations = LocationSerializer(many=True, read_only=True) class Meta: model = Price fields = ['package', 'locations', 'price'] def create(self, validated_data): print("validated_data, validated_data) and viewset: class PriceViewSet(ModelViewSet): queryset = Price.objects.all() serializer_class = PriceSerializer ordering = ['id'] permissions = { "GET": ["view_minimum_listing_price", ], "POST": ["add_minimum_listing_price", ], 'PUT': ['update_minimum_listing_price', ], 'DELETE': ['delete_minimum_listing_price', ], } In testing I'mm using the following: data = { "price": 12, "package": self.package.id, "is_enabled": False, "location": self.location } response = self.client.post(path=self.url, data=data, format='json') locations doesn't appear in validated_data? How to get it to assign locations to the instance with post requests? I also tried to send it with as ids list, but non works. I only field price, package, is_enabled in validated}_data, but location doesn't appear! -
Django admin drop down with very long description/text
just like the pic in admin panel when creating some post: that basically one of dropdown menu options, it is so long, is there any idea on how i can change it to be multi-line? or maybe change the drop down menu to a "select table", the admin in this case need to read the description, so it is unwise for it to be formatted like that. I have a code example: models.py class CreatePost(models.Model): subject = models.CharField(max_length=99) desc = models.TextField(max_length=9000) isSolved = models.BooleanField(default=False) # a button user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="user_post") def __str__(self): return format_html('SUBJECT : {} <br/> DESCRIPTION : {} <br/> Email : {} <br/> ',self.subject, self.desc, self.user.username) # remember to show the name of ticket sender class RespondToPost(models.Model): ticket = models.ForeignKey(CreatePost,on_delete=models.CASCADE) to = models.EmailField(max_length=320) content = models.TextField() def __str__(self): return format_html('SUBJECT : {} <br/> DESCRIPTION : {} <br/> EMAIL : {} <br/> ',self.post.subject, self.post.desc, self.post.user.username) admin.py class CreatePostAdmin(admin.ModelAdmin): list_display = ('id', '__str__') class Meta: model = models.CreatePost class RespondToPostAdmin(admin.ModelAdmin): list_display = ('id', '__str__', 'to', 'content') class Meta: model = models.RespondToPost any idea? -
Django: UserAuthentication | ModuleNotFoundError: No module named 'userAuthentication'
I've been trying to create a user login and logout with django's bulid-in authenticated views. I changed the project-level URL pattern urlpatterns = [ path('admin/', admin.site.urls), path('accounts/',include('django.contrib.auth.urls')), path('', include('home.urls')), ] added template registration/login.html enter image description here and updated LOGIN_REDIRECT_URL in settings.py but still getting ModuleNotFoundError: No module named 'userAuthentication'.i dont know if iam missing anything in these it would be appreciated if anyone can give the heads up. note: i was trying the recreate exactly this go to :https://docs.djangoproject.com/en/4.0/topics/auth/default/ ctrl+f : Authentication Views -
React Django CSRF token missing or incorrect
In action file the code: ... const config = { headers:{ 'Content-type': 'application/json' } } const {data} = await axios.post('http://localhost:8000/api/register/', {'email':email, 'password':password}, config) ... It's working; then localhost:8000 put to package.json as a proxy, after that got an issue CSRF token missing or incorrect, how to fix that, thanks. Application was restarted with no changes. -
How to ADD for loop result in templates
views.html {% for products in product %} <tr> <td>{{ products.quantity_deliver1 }}</td> <td>{{ products.quantity_deliver2 }}</td> <td>{{ Code Here }}</td> </tr> {% empty %} <tr> <td colspan="3" class="text-center bg-warning">No Products</td> </tr> {% endfor %} How do I add products.quantity_deliver1 + products.quantity_deliver2 and output the sum in the 3rd data cell. -
News API in django python?
Iam Using a newsapi key in my website, when I try to access only one news I having trouble? How can I access Only one Particular news in my page? (not whole news using loop) views.py API_KEY = '1099d3305d5c43f0ba9706b17dd1fe1c' def sports(request): url = f'https://newsapi.org/v2/top-headlines?language=en&category=sports&apiKey={API_KEY}' url2 = f'https://newsapi.org/v2/top-headlines?language=en&apiKey={API_KEY}' response = requests.get(url) response2 = requests.get(url2) data = response.json() data2 = response2.json() articles = data['articles'] articles2 = data2['articles'] context = { 'articles' : articles, 'articles2' : articles2 } return render(request, 'app/sports.html', context) -
Invalid literal for int() with base 10 in my views after it worked a while
I'm keep getting this error Invalid literal for int() with base 10 from the views in my django project after it worked for a while , Traceback (most recent call last): File "/srv/cc/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/srv/cc/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/cc/env/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "./core/views.py", line 133, in send_message if int(uid2) == uid: Exception Type: ValueError at /msg/new Exception Value: invalid literal for int() with base 10: '4,016' Here is My views.py looks like def chat_detail(request, pk): chat = Chat.objects.get(pk=pk) added, lm = chat.new(request.user) if lm: lm.msg = chat.current_last_msg lm.save() recepient = chat.recepient(request.user) return render(request, 'core/chat.html', {'chat': chat, 'recepient': recepient}) def chat_with_user(request, uid): chat = Chat.get_or_create(request.user.id, int(uid)) return redirect(f'/chat/{chat.id}') def chats(request): user_chats = [] for c in Chat.of_user(request.user): user_chats.append({'rec': c.recepient(request.user), 'unread': len(c.new(request.user)[0]), 'chat': c}) return render(request, 'core/chats.html', {'user_chats': user_chats}) def send_message(request): if request.method == 'POST': m = Message() uid = request.user.id uid2 = request.POST.get('uid2', None) if uid2 is None: return {} if int(uid2) == uid: return {} m.chat = Chat.get_or_create(uid, int(uid2)) m.sender = request.user m.text = request.POST.get('text') m.save() return redirect(f'/chat/{m.chat.id}') else: return {} And here all the message models.py class LastMessage(models.Model): chat … -
how to use @property in Django models? how to get the details of company models and futsalusers in to single table?
class FutsalUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField( _('staff status'), default=True, help_text=_('Designates whether the user can log into this admin site.'), ) objects = FutsalUserManager() USERNAME_FIELD = 'email' def __str__(self): return self.email @property def company_details(self): company_data = Company.objects.filter(user= self) if company_data : company_data.name return company_data else: return None class Company(TimeStampedModel): name = models.CharField(max_length=200) hr_name = models.CharField(max_length=200) hr_email = models.CharField(max_length=200) user = models.ForeignKey( settings.AUTH_USER_MODEL, models.DO_NOTHING) hr_verified = models.BooleanField(default=False, blank=True) primary_phone = models.CharField(null=True, max_length=200) followed_by = models.CharField(max_length=200,default="Not assigned") comments = models.TextField(default="") def __str__(self): return self.name -
Django add new line (break line) to display list of some foreign key
This is what i have done so far to break a line: class CreatePost(models.Model): subject = models.CharField(max_length=99) desc = models.TextField(max_length=9000) user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="user_post") def __str__(self): return format_html('SUBJECT : {} <br/> DESCRIPTION : {} <br/> Email : {} <br/>', (self.subject, self.desc, self.user.username)) for admin.py class CreatePostAdmin(admin.ModelAdmin): list_display = ('id', 'subject', 'desc') class Meta: model = models.CreatePost class RespondToPostAdmin(admin.ModelAdmin): list_display = ('id', 'post', 'to', 'content') class Meta: model = models.RespondToPost I am dealing with RespondToPostAdmin and i am getting error regarding the formatting in string dunder method: Exception Type: IndexError Exception Value: Replacement index 1 out of range for positional args tuple ``` i am not sure why, any help is appreciated, if there is better solution to format my string dunder method to add breaklines/new lines, please suggest me -
Multiple image upload in Django admin
I am having a lot of trouble trying to code the correct model to upload multiple images to my Django app. I want to be able to upload these images via the django admin. I have tried using ImageField but it only allows one pic at a time and I also want to be able to resize the image. Here is my models.py: class Lesson(models.Model): DRAFT = 'draft' PUBLISHED = 'published' CHOICES_STATUS = ( (DRAFT, 'Draft'), (PUBLISHED, 'Published') ) ARTICLE = 'article' QUIZ = 'quiz' CHOICES_LESSON_TYPE = ( (ARTICLE, 'Article'), (QUIZ, 'Quiz') ) course = models.ForeignKey(Course, related_name='lessons', on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() short_description = models.TextField(blank=True, null=True) long_description = models.TextField(blank=True, null=True) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=PUBLISHED) lesson_type = models.CharField(max_length=20, choices=CHOICES_LESSON_TYPE, default=ARTICLE) Serializer.py: class LessonListSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ('id', 'title', 'slug', 'short_description', 'long_description') Admin.py: class LessonAdmin(admin.ModelAdmin): list_display = ['title', 'course', 'status', 'lesson_type'] list_filter = ['status', 'lesson_type'] search_fields = ['title', 'short_description', 'long_description'] inlines = [LessonCommentInline] -
Django Ajax jquery 404 (Not Found)
could someone help me find a way to make my ajax request work? I found some of the same questions on this site but didn't solve them. I want to Ajax the process to show modal I'm using the latest Django version. I have never used ajax, so I don't really know what I'm doing. Please help What should I specify for the url? Url to display Ajax? Url to process Ajax? app.urls.py urlpatterns = [ path('admin/', admin.site.urls), path('test/', include('test.urls')), ] test/urls.py urlpatterns = [ path('rex/', IndexView.as_view(), name='rex_index'), ] test/templates/test/rex.html {% extends 'main/layout.html' %} {% block content %} {% load crispy_forms_tags %} <!--modal--> <script> $(function(){ $('#edit_foo').on('click', function () { console.log("test") $.ajax({ type: 'POST', url: '/rex_index/', data: { html: '<form id="form_foo"><textarea></textarea><input type="submit"></input></form>', delay: 1, }, success: function (data, textStatus, jqXHR) { $('#foo_modal').find('.modal-body').html(data); $('#foo_modal').modal('show'); }, }); }); }); // Handle submit. Here we return an error regardless of the // input given: $("#foo_modal").on('submit', '#form_foo', function (e) { $.ajax({ type: 'POST', url: '/rex_index/', data: { html: '<form id="form_foo_2"><span class="error">You must write something silly here:</span><textarea></textarea><input type="submit"></input></form>', delay: 0, }, success: function (data, textStatus, jqXHR) { $('#foo_modal').find('.modal-body').html(data); }, }); e.preventDefault(); return false; }); // Handle second submit. Here we close the modal. // In a … -
Django: how to make other changes when I am deleting an object?
I did some searching and knew there is something like post_delete signal I can play with. But are there any other ways to do the same thing like the save() function in a Model but in the other way round? Something like this, probably? class MyModel(models.Model): my_field = models.CharField() def delete(self, *args, **kwargs): # instead of save() # do something here return super(MyModel, self).delete(*args, **kwargs): # instead of save()