Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework, creating a model, (serializer and view) with oneToMany field to users
I am trying to create a rather simple model, all the model holds is a week number (as the primary key), and a oneToMany field with a list of users. The idea is that it should function like a schema, where you can see which users is attached to a specific week number. My problem is currently getting the serializer to work with the oneToMany field. Model: class Schema(models.Model): week = models.PositiveIntegerField(primary_key=True, unique=True, validators=[MinValueValidator(1), MaxValueValidator(53)], ) users = models.ForeignKey(MyUser, null=True, on_delete=models.SET_NULL) class Meta: ordering = ('week',) Serializer: class SchemaSerializer(serializers.Serializer): class Meta: model = Schema fields = ('week', 'users') def create(self, validated_data): answer, created = Schema.objects.update_or_create( week=validated_data.get('week', 1), defaults={'users', validated_data.get('users', None)} ) return answer View: class SchemaView(APIView): permission_classes = (IsAuthenticated, IsAdminUser) def get(self, request): schemas = Schema.objects.all() serializer = SchemaSerializer(schemas) return Response(serializer.data) def post(self, request): data = request.data serializer = SchemaSerializer(data=data) serializer.is_valid() serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) I get the following error TypeError: cannot convert dictionary update sequence element #0 to a sequence. As I interpret that error, something is wrong with the first element (week number) when trying to do serializer.save(). -
django TimeField getting saved with wrong time zone
I have a simple Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) start_time = models.TimeField(null=True) end_time = models.TimeField(null=True) email_list = ArrayField( models.CharField(max_length=255, blank=True), blank=True, default=list, ) When Users create a Group, they are required to choose a start time. I have this celery periodic task that runs every minute, checking if a Group is 30 minutes from starting to send notifications to everyone on the email_list. The issue I'm having is that the time the User inputs is always off. If the User wants their Group to start at 9:00AM, it gets saved on the database at 13:00, and the celery task gets sent out at the wrong time. I have UTC set to true in my settings file so I assumed that it's universal, as in whatever the time the User chooses will be saved in UTC time which may look different, but is still synced up. Here's my beat schedule: app.conf.beat_schedule = { 'start_group_notification': { 'task': 'start_group_notification_task', 'schedule': crontab(), } } and here's the task: @shared_task(name='start_group_notification_task') def start_group_notification_task(): thirty_minutes_from_now = datetime.datetime.now() + datetime.timedelta(minutes=30) chaburahs = Group.objects.filter( start_time__hour=thirty_minutes_from_now.hour, start_time__minute=thirty_minutes_from_now.minute ).prefetch_related("joined") for group in groups: for email in group.email_list: send_mail … -
Postpone django dunction until after login/signup
I am looking for a way to let unauthenticated users to click a button, that will act after the user has signed up or logged in. To be more specific, unauthenticated users can view the page of a group, and I want to let them press the "Join" button, which will redirect them to the login/signup page, and after they log in or sign up, the action of the button is performed automatically (they automatically join the group where they pressed the button). I suspect this might be done with signals? I have not used signals before and am not sure if they can actually fulfill this task. P.S. I am using django-allauth for authentication. -
django+celery autodiscover_tasks doesn't load my tasks until I open a PeriodicTask in admin
I have a django (4.0.1) project - 'myproj', with an app - 'myapp'. I have myproj/celery.py taken from celery's doc, with: app.autodiscover_tasks() I have myapp/tasks.py with: @shared_task def debug(): ... When I start the server, and a view is trying to run the debug task, I get celery.exceptions.NotRegistered: 'myapp.tasks.debug'. At this point, if I go to a PeriodicTask page in admin (like http:.../admin/django_celery_beat/periodictask/1/change/), all the tasks are listed under Task (registered). Now, if I call the View again, it runs the debug task with no problem. Am I missing some import? Why are my tasks loaded only after I go in to admin? I've tried playing with the args to autodiscover_tasks, like force and ['myapp.tasks'], nothing worked. -
How to get one or more dynamic field values in django method passing as dynamic parameter/arguments
I am new in django i am in stuck in getting dynamic field values from django method. i understand php well. in php i have made functions to pull one or more dynamic field data for my project purpose. my php function is as belows: function dynamicData($id,$table,$columns_to_get){ include 'connect.php';//connection file $sel=$connect->query("SELECT $columns_to_get FROM $table WHERE id='$id'"); $data=$sel->fetch_assoc(); return $data; $connect->close(); } Now i can use above function like $data=dynamicData(12,'users_table','name,id,age,gender'); or $data=dynamicData(12,'users_table','name,gender'); But in django i do not get such thought like above php function. in django i make below function but i am in stuck ``` def commonSingleFullNormal(identity,app,model,**kwargs): now_model=apps.get_model(app_label=app, model_name=model) data=now_model.objects.filter(identity=identity).values(**kwargs) return data[0] ``` It does not work why? Can anybody help please? -
DRF is taking too much time to return nested serialized data
We are having too many models which are related, While returning queryset serializing the data is too slow(serializer.data). Below are our models and serializer. Why django nested serializer is taking too long to return JSON response. What are we doing wrong here? models.py class Doctor(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(_("first_name"), max_length=255, null=False) last_name = models.CharField(_("last_name"), max_length=255, null=False) full_name = property(lambda self: "{} {}".format(self.first_name, self.last_name)) email = models.EmailField(_("email"), max_length=255, unique=True, null=False) password = models.CharField(_("password"), max_length=128, null=False) country_code = models.CharField( _("country_code"), max_length=10, null=False, blank=False ) phone_number = models.CharField( _("phone_number"), max_length=50, null=False, blank=False ) full_phone_number = models.CharField( _("full_phone_number"), max_length=60, unique=True, null=False ) is_otp_verified = models.BooleanField(_("is_otp_verified"), default=False) gender = models.CharField( _("gender"), max_length=50, choices=choices.gender_choices, blank=True, null=False ) image = encrypt(models.ImageField(upload_to=userProfilePictureDirectoryPath, default=None, null=True, blank=True)) is_active = models.BooleanField(_("is_active"), default=True) is_verified = models.BooleanField(_("is_verified"), default=False) national_medical_id = models.CharField(max_length=100, null=True, unique=True) numeric_id = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(_("created_at"), auto_now_add=True) updated_at = models.DateTimeField(_("updated_at"), auto_now=True, blank=True, null=True) username = None USERNAME_FIELD = "full_phone_number" REQUIRED_FIELDS = [] objects = CustomUserManager() class Meta: unique_together = ( "country_code", "phone_number", ) def __str__(self) -> str: return self.phone_number class Specialties(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name_en = models.CharField(_("name_en"), max_length=255, blank=True, null=True) name_ro = models.CharField(_("name_ro"), max_length=255, blank=True, null=True) name_ar = models.CharField(_("name_ar"), max_length=255, blank=True, null=True) priority … -
creating a search bar using Django
I have a list of markdown pages displayed on the index page. I want to make a search bar using django that displays the searched items of the list so I have written this code in order to make the search bar get a certain query in views.py: def index(request): x = util.list_entries() for entryy in x: if 'q' in request.GET: q = request.GET['q'] data = x.entryy.filter(entryy__icontains = q) else: data = x return render(request, "encyclopedia/index.html", { "entries": data }) in urls.py: urlpatterns = [ path("", views.index, name="index")] in layout.html: <form action="{% url 'index' %}" method = "get"> {% csrf_token %} <input class="search" type="search" name="q" placeholder="Search Encyclopedia"> </form> util.list_entries() fuction: def list_entries(): """ Returns a list of all names of encyclopedia entries. """ _, filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename) for filename in filenames if filename.endswith(".md"))) when I enter anything in the search bar this appears to me : enter image description here so what is the problem?? -
How to make such a category page?
Who can help make such a category page? Category page example I googled a lot and did not find worthwhile information on the implementation of such functionality. I need at least some implementation explanation with a few examples, mostly "views.py" and template tags. I would be extremely grateful for any help and hints in the implementation. At the moment I have this code: views.py def show_category(request, hierarchy=None): ''' Link hierarchy ''' hierarchy = (hierarchy or "").strip("/") # Remove stray slashes if hierarchy: category_slug = hierarchy.split('/') parent = None for slug in category_slug[:-1]: parent = Categories.objects.get(parent=parent, slug=slug) category = Categories.objects.get(parent=parent, slug=category_slug[-1]) else: category = None if category: return render(request, 'shop/categories.html', {'instance': category}) # No category, show top-level content somehow category = Categories.objects.all() return render(request, 'shop/category.html', {'instance': category}) models.py class Categories(MPTTModel): title = models.CharField(max_length=250, db_index=True) slug = models.SlugField(max_length=250, unique=True) imagePath = models.ImageField(upload_to='images/categories/', blank=True, verbose_name='Изображение категории') parent = TreeForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class MPTTMeta: order_insertion_by = ['title'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i + 1])) return slugs def __str__(self): return self.title Template files … -
Django filterset and Django rest framework not working as expected
I have created a Django filter set to filter data, some fields are filtered with relationships. When I never filter with the endpoint, it just returns all data instead of filtered data, what could be wrong here? This is my endpoint filterer : http://127.0.0.1:5000/api/v1/qb/questions/?paper=26149c3b-c3e3-416e-94c4-b7609b94182d&section=59bdfd06-02d4-4541-9478-bf495dafbee1&topic=df8c2152-389a-442f-a1ce-b56d04d39aa1&country=KE Below is my sample : from django_filters import rest_framework as filters class QuestionFilter(filters.FilterSet): topic = django_filters.UUIDFilter(label='topic', field_name='topic__uuid', lookup_expr='icontains') sub_topic = django_filters.UUIDFilter(label='sub_topic', field_name='topic__sub_topic__uuid', lookup_expr='icontains') paper = django_filters.UUIDFilter(label='paper', field_name='paper__uuid', lookup_expr='icontains') section = django_filters.UUIDFilter(label='section', field_name='section__uuid', lookup_expr='icontains') subject = django_filters.UUIDFilter(label='subject', field_name="paper__subject__id", lookup_expr='icontains' ) year = django_filters.UUIDFilter(label='year', field_name='paper__year__year', lookup_expr="icontains") country = django_filters.CharFilter(label='country', field_name="paper__exam_body__country", lookup_expr='icontains') class Meta: model = Question fields = ['topic', 'section', 'paper', 'sub_topic', 'subject', 'year', 'country'] Then my view is like this : class QuestionView(generics.ListCreateAPIView): """Question view.""" queryset = Question.objects.all() serializer_class = serializers.QuestionSerializer authentication_classes = (JWTAuthentication,) filter_backends = (filters.DjangoFilterBackend,) filterset_class = QuestionFilter Then the models attached to the filter are as below : class Question(SoftDeletionModel, TimeStampedModel, models.Model): """Questions for a particular paper model.""" uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) mentor = models.ForeignKey(User, related_name='question_mentor', null=True, on_delete=models.SET_NULL) paper = models.ForeignKey(Paper, max_length=25, null=True, blank=True, on_delete=models.CASCADE) question = models.TextField( _('Question'), null=False, blank=False) section = models.ForeignKey(QuestionSection, related_name='section_question', null=True, on_delete=models.SET_NULL) topic = models.ForeignKey(Course, related_name='topic_question', null=True, on_delete=models.SET_NULL) question_number = models.IntegerField(_('Question Number'), default=0, blank=False, … -
how to update model field data when Javascript event occurs
I'm doing on a Django Project. There is a post model, and the post has 'likes' field. When a user clicks the Like button on a post, I want to increase the number of the Likes of the post. I want to solve the problem only with Django without REST framework(DRF) what can I do? -
getting client ip in local network django framework
I'm using the following code in order to get the client ip: def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip the problem is im getting a localhost ip '127.0.0.1'. my client resides in the same network as the Django server but it runs from a different local ip address. any idea how to extract the specific ip of client? -
Django Gunicorn Nginx summernote image upload error
My problem make blog by summernote and use Nignx, Gunicorn but upload image use summernote error code apear this nginx_1 | 172.19.0.1 - - [14/Aug/2022:11:45:48 +0000] "POST /summernote/upload_attachment/ HTTP/1.1" 200 181 "http://127.0.0.1/summernote/editor/id_content/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36" "-" nginx_1 | 172.19.0.1 - - [14/Aug/2022:11:45:48 +0000] "GET /media/django-summernote/2022-08-14/76f471c6-b864-478a-a06b-4062b11c6ed8.png HTTP/1.1" 404 555 "http://127.0.0.1/summernote/editor/id_content/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36" "-" nginx_1 | 2022/08/14 11:45:48 [error] 22#22: *1 open() "/usr/src/app/_media/django-summernote/2022-08-14/76f471c6-b864-478a-a06b-4062b11c6ed8.png" failed (2: No such file or directory), client: 172.19.0.1, server: , request: "GET /media/django-summernote/2022-08-14/76f471c6-b864-478a-a06b-4062b11c6ed8.png HTTP/1.1", host: "127.0.0.1", referrer: "http://127.0.0.1/summernote/editor/id_content/" I want know meaning of this error message -
I want to make full stack socail media app in django, is it a good solution to call Django api (made in the same project) from template?
and then use AJAX to render that data in template? I also don't want the whole page to refresh when someone likes a post or sends a follow request etc... -
should i user celery or multiprocessing?
I use Django to implement my server, I have a task to parse data on an api request which takes a lot of time to execute I'm thinking of implementing it using a background function, but would like an advice on whether to use celery or multiprocessing and what's the difference between them? -
The field 'task' clashes with the field 'task'
I am working on my django app. I have a bese time class and I want to use this class in all models/ class TimeBase(models.Model): created_at = models.DateTimeField(auto_now_add=True) class Task(TimeBase): """parsing task""" search_query = models.CharField(max_length=2000,) class SearchRequest(TimeBase): task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="search_requests") How can I fix error? parser_app.SearchRequest.task: (models.E006) The field 'task' clashes with the field 'task' from model 'parser_app.timebase'. I understand that the reason is ForeingKey relation between Task and SearchRequest -
Django count and store values in models
I have multiple Models which look like this class Classes(models.Model): User = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) A1 = models.IntegerField(default=0) B1 = models.IntegerField(default=0) etc A2 = models.IntegerField(default=0) B2 = models.IntegerField(default=0) etc A3 = models.IntegerField(default=0) B3 = models.IntegerField(default=0) etc A4 = models.IntegerField(default=0) B4 = models.IntegerField(default=0) etc Sum_of_1 = models.IntegerField( blank=True, null=True) Sum_of__2 = models.IntegerField( blank=True, null=True) Sum_of__3 = models.IntegerField( blank=True, null=True) Sum_of__4 = models.IntegerField( blank=True, null=True) its a bit bigger, anyways, I want A and B etc sum together and save the result in sum of 1 etc. First I thought that a form would be good for that but the sum fields should always have the sum they never should be updated so then I thought rewriting the save method in models, I got this but it just gives me an recursion error I know why but have no solution for that super().save(*args, **kwargs) if self.Sum_of__1 or self.Sum_of__2 or self.Sum_of__3 or self.Sum_of__4 is None: self.Sum_of__1 = self.A1 + self.B1 + self.C1 + self.D1 + self.E1 self.Sum_of__2 = self.A2 + self.B2 + self.C2 + self.D2 + self.E2 self.Sum_of__3 = self.A3 + self.B3 + self.C3 + self.D3 + self.E3 self.Sum_of__4 = self.A4 + self.B4 + self.C4 + self.D4 + self.E4 self.save() any ideas ? -
How to HyperlinkedRelatedField into a model from different app?
bellow is urls.py of users app. from django.urls import path from . import views app_name = 'users' urlpatterns = [ path('', views.UserList.as_view(), name='user-list'), path('<int:id>', views.UserDetail.as_view(), name='user-detail'), ] url conf of snippets app: from django.urls import path from . import views app_name = 'snippets' urlpatterns = [ path('', views.SnippetList.as_view(), name='snippet-list'), path('<int:pk>/', views.SnippetDetail.as_view(), name='snippet-detail'), path('<int:pk>/highlight/', views.SnippetHighlight.as_view(), name='snippet-highlight'), ] and here's SnippetSerializere from rest_framework import serializers from . import models class SnippetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Snippet fields = ['id', 'owner', 'title', 'code', 'highlight', 'linenos', 'language', 'style'] highlight = serializers.HyperlinkedIdentityField(view_name='snippets:snippet-highlight', format='html') owner = serializers.HyperlinkedRelatedField( read_only=True, view_name='users:user-detail' ) The error I got ImproperlyConfigured at /snippets/ Could not resolve URL for hyperlinked relationship using view name "users:user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. -
add more model info to the JWT token
i'm creating a messaging app. i have 3 models in my backend djago. i have a profile model that stores user & which room they are connected with(so that everytime they log in, their rooms will pop up in side bar like whatsapp). in profile model i have a many to many relationship with Room model that stores rooms list. as i'm using JWT web token for authentication, i want users profile model/rooms like of that user to be added in the token. so that i can fetch the info from token directly but i don't know how to add that fields info into the token views. i've already customised my token obtain view where i added users name as extra but i need to add the list of rooms too. thanks in advance for helping... #model.py from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.contrib.auth.models import User # Create your models here. class Room(models.Model): name = models.CharField(max_length=100,blank=True,null=True) class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) rooms = models.ManyToManyField(Room) class Message(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,blank=False,null=True) message = models.TextField(max_length=500,blank=False,null=True) name = models.CharField(max_length=100,blank=True,null=True) room = models.ForeignKey(Room,on_delete=models.CASCADE,null=True) time = models.DateTimeField(auto_now_add=True) received = models.BooleanField(default=False,null=True) #views.py from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView … -
Django - How to Manually update/set/Reset password
I tried to reset password manually by passing key But it always says AttributeError : 'str' object has no attribute 'get' I googled many times even if i saw Manual Password with hiding password field Django but no luck favor me. // In my form #forms.py class UserResetPasswordForm(forms.Form): new_password1 = forms.CharField( label=_("New Password"), widget=forms.PasswordInput(attrs={"autocomplete":"off"}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New Password Confirmation"), strip=False, widget=forms.PasswordInput(attrs={"autocomplete":"off"}), ) In Url path('password-reset/confirm/<str:reg_key>/', accounts_view.myreset_password_confirm, name='myreset_password_confirm'), In View #views.py def myreset_password_confirm(request, reg_key): user = User.objects.filter(activate_key=reg_key).first() if user is not None: if request.method == 'POST': form = UserResetPasswordForm(request.POST) if form.is_valid(): #password1 = form.cleaned_data.get('new_password1') #password2 = form.cleaned_data.get('new_password2') password1 = request.POST['new_password1'] password2 = request.POST['new_password2'] if password1 and password2: if password1 != password2: raise ValidationError("Your password didn't match.") password_validation.password_validators_help_text_html() return password2 print(password2) user.activate_key = '' user.set_password(password2) user.save() print("Print User") print(type(user)) messages.success(request, f"Your password for {user.email} has been reset successfully!") return HttpResponseRedirect('/') else: form = UserResetPasswordForm() return render(request, 'reset_password_confirm.html', {'form':form}) else: print("U R Boomed") messages.error(request, "Your requested URL is not Valid, Please try with valid URL.") return HttpResponseRedirect('/') Please help, how to solve it? -
How to prevent Modal from hiding when submitting if there is an error in the form?
when I click the Add User button the modal is hiding even if the form has errors. If I reopen the modal the error messaged are there, I need to show the error messaged and not close the modal if the there is an error message. I think I can use the {{form.errors}} to verify if there is an error message. But I don’t know how? <div class="card-body d-flex justify-content-between"> <h4 class="box-title">Users</h4> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#add_user" data-whatever="" >Add a user</button> <div class="modal fade" id="add_user" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h1 class="h3 mb-3 fw-normal text-center" id="exampleModalLabel">Create Account</h1> </div> <div class="modal-body"> <form action="" method="POST"> {% csrf_token %} <div class="form-floating"> {{ form.username }} <span class="text-danger">{{ form.errors.username }}</span> </div> <div class="form-floating"> {{ form.email }} <span class="text-danger">{{ form.errors.email }}</span> </div> <div class="form-floating"> {{ form.password1 }} <span class="text-danger">{{ form.errors.password1 }}</span> </div> <div class="form-floating"> {{ form.password2 }} <span class="text-danger ">{{ form.errors.password2 }}</span> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button class=" btn btn-primary" type="submit" >Add User</button> </div> </div> </form> </div> </div> </div> I used to the Django form for validation and error messages. from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class CustomUserCreationForm(UserCreationForm): … -
How display html content into div element by clicking on a href="" link, in django and django-messages?
I am trying to display HTML file into div element. I tried a few examples from js to jquery, but nothing seems to work. I am also using django-message. In inbox.html I am trying to display message content into a div element after clicking on a link. Message contact needs to change after clicking on another link. This needs to be displayed on the same page. inbox.html: {% extends "user_dashboard_page.html" %} {% load static %} {% block content %} {% if user.is_authenticated %} <link rel="stylesheet" type="text/css" href="{% static 'css/inbox.css' %}"> <script src="{% static 'js/inbox.js' %}"></script> {% load i18n %} {% if message_list %} <section class="sidebar"> <div class="sidebar--inner"> <div class="is-settings--parent"> <div class="sidebar-menu"> <ul> <li class="inboxItem isActive"><a href="#0">Inbox (<span class="numCount"></span>) </a></li> <li class="sentItem"><a href="{% url 'messages_outbox' %}">Sent</a></li> <li class="spamItem"><a href="#0">Spam</a></li> <li class="trashItem"><a href="{% url 'messages_trash' %}">Trash</a></li> </ul> </div> </div> </div> </section> <section class="view"> <section class="emails is-component"> <div class="emails--inner"> <div> <h1 class="email-type">Inbox</h1> <!-- inbox email cards --> {% for message in message_list %} <div class="inbox"> <div class="email-card"> <div class="is-email--section has-img"> <div class="sender-img" style=""> </div> </div> <div class="is-email--section has-content"> <div class="sender-inner--content"> <p class="sender-name">From: {{ message.sender.username }}</p> **a link elements!!!** <p class="email-sum">Subject: <a href="{{ message.get_absolute_url }}">{{ message.subject }}</a></p> <p class="email-sum">Time: {{ message.sent_at|date:_("DATETIME_FORMAT") }}</p> </div> </div> … -
Django rest framework get data from foreign key relation?
I have a models like this: class Author(models.Model): name = models.CharField(max_length=150, blank=False, null=False) dob = models.DateField(null=True, blank=True) description = models.TextField(max_length=2000, blank=False, default="This author doesn't have any description yet!") image = models.ImageField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['created'] def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200, blank=False, null=False) author = models.CharField(max_length=200) genres = models.ManyToManyField(Genre, related_name='genre', blank=True) author = models.ForeignKey(Author, related_name='author', blank=True, on_delete=models.CASCADE) description = models.TextField(max_length=1200, blank=False, default="This book doesn't have description yet!") image = models.ImageField(default="") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['created'] def __str__(self): return self.title class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) book = models.ForeignKey(Book, on_delete=models.CASCADE) title = models.CharField(max_length=100, null=False, blank=False, help_text="Title overall of your review") rating = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(5)], help_text='Rating in range 0-5') description = models.TextField(max_length=1000, null=False, blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) I want to get Book data response in json with my reviews of the book from my Review table but don't know how. I am not getting any useful solution from documentation and Google, please help. -
How do I update my list data when data is already sent in the backend? (VUE/DJANGO)
I'm new to vue and trying to work it with django. I have a field called status that uses boolean field and set the default=False. I'm trying to update the data in the backend by onclick. When i click the div, data will emit to parent and update the status to !status. Child: <div @click="$emit('update-status', this.task)">{{ task.status}} </div> Parent: <Task v-for="task in tasks" :key="task.slug" :task="task" :slug="task.slug" @update-status="updateStatus"/> async updateStatus(task) { let endpoint = `/api/v1/tasks/${task.slug}/`; const response = await axios.put(endpoint, { status: !task.status, }); } It updates once and it keeps returning the same value True when I keep on clicking (it should always return opposite of status). I have to manually refresh my browser, so when I click it again it will return False. -
Display sum value of nested object in serializer
I have an app where users enters their daily expenses and incomes. The API data looks like this [{ "id": "07cf140c-0d4d-41d7-9a31-ac0f5f456840", "owner": 2, "entry": [ { "id": 1, "owner": 1, "title": "aa", "amount": 22, "description": "za pizze", "entry_type": "income", "date_added": "2022-08-13", "entry_category": 1 } ], "viewable": [ 1, 2 ], "name": "as", "date_added": "2022-08-13" }, { "id": "d458196e-49f1-42db-8bc2-ee1dba438953", "owner": 1, "entry": [ { "id": 1, "owner": 1, "title": "aa", "amount": 22, "description": "za pizze", "entry_type": "income", "date_added": "2022-08-13", "entry_category": 1 }, { "id": 2, "owner": 1, "title": "sas", "amount": 323, "description": "stacja", "entry_type": "expenses", "date_added": "2022-08-13", "entry_category": 5 } ], "viewable": [], "name": "dsdsds", "date_added": "2022-08-13" }] And I know how to sum the amount field to get sum of income/expenses def get_queryset(self): user_id = self.request.user.id available = BudgetEntry.objects.filter( Q(owner=user_id) ) a = available.filter(entry_type='income').aggregate(Sum('amount'))['amount__sum'] print(a) return available but how can I get this data to be display directly in the JSON? In a way that is reusable because I want also to get top categories where user spends or saves the most Serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('name',) class BudgetEntrySerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.id') class Meta: model = BudgetEntry fields = '__all__' class WalletInstanceSerializer(serializers.ModelSerializer): owner = … -
I am getting an unexpected keyword argument error in a function I didn't call
I am building a online exam system where in exam cohorts there will be exams. I have created Models for cohort and exams and questions. Now I am trying to put a foreign key exams in questions model where there is a cohort in exams models as foreign key. Here is the code views.py def addCohort(request): if request.method == 'POST': form = createCohortForm(request.POST) if form.is_valid(): u = request.user name = form.cleaned_data['name'] chrt = cohort(CohortName = name , Admin = u.email) chrt.save() chrtInfo = cohortInfos(cohort = chrt, Member = u, MemberStatus = 'admin') chrtInfo.save() return HttpResponseRedirect('/dashboard') else: form = createCohortForm() return render(request, 'cohort/createcohort.html', {'f': form}) def cohortIndex(request,cID): chrt = cohort.objects.get(CohortID = cID) cohortInformation = cohortInfos.objects.get(cohort = chrt , Member = request.user) exams = ExamInfo.objects.filter(cohort = chrt) if request.user.email == cohortInformation.cohort.Admin: return render(request, 'cohort/cohortIndexAdmin.html',{'Info':cohortInformation, 'exams': exams}) else: return render(request, 'cohort/cohortIndexExaminee.html',{'Info':cohortInformation, 'exams': exams}) def addMember(request,cID): chrt = cohort.objects.get(CohortID = cID) cohortInformation = cohortInfos.objects.get(cohort = chrt, Member = request.user) if request.method == 'POST': form = addMemberForm(request.POST) messages.success(request, 'Examinee added successfully') if form.is_valid(): email = form.cleaned_data['memberEmail'] member = User.objects.get(email__exact = email) cohortadd = cohortInfos(cohort = chrt, Member = member, MemberStatus = "examinee") cohortadd.save() form = addMemberForm() else: form = addMemberForm() memberlist = cohortInfos.objects.filter(cohort = chrt) …