Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF_TOKEN Validation Failed in Django even it is included in form
Hi im new to Django and struggling with Django and csrf_token is getting 403 forbidden error even its included in the form template can some one explains me what's the issue here i have searched for answers but none worked for me when i inspect i can see the csrf token in the form Thanks In advance teplate.html {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} <form action="{% url 'newPage'%}" method="post"> {% csrf_token %} {{form}} <br> <input type="submit" value="Save"> </form> {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.title, name="title"), path("search/", views.search , name="search"), path("NewPage/", views.newpage, name="newPage") ] views.py def newpage(request): if request.method == 'POST': form = request.POST() print(form.is_valid()) if form.is_valid(): title = form.cleaned_data.get('title') content = form.cleaned_data.get('content') util.save_entry(title, f'# {title}\n\n{content}') return HttpResponseRedirect(reverse('encyclopedia:title')) else: form = newEntry() return render(request, "encyclopedia/newentry.html", { "form": form }) else: form = newEntry() return render(request, "encyclopedia/newentry.html", { "form": form }) -
Bootstrap modal dialog not displayed when click button or link in Django template
I am trying to get a button in a django view to display a model dialog to request delete confirmation of a list item. When I click the button I cannot get the modal dialog to display. Any ideas? Dialog (included from Django Template) <div id="confirmModal" class="modal fade" tabindex="-1" role="dialog" caller-id="" aria-labelledby="confirmModal" aria-hidden="true" > <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-body" id="modal-message"> Do you wish to proceed? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary" data-dismiss="modal" id="confirmButtonModal">Confirm</button> </div> </div> </div> </div> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', () => { var buttons = document.querySelectorAll("[data-target='#confirmModal']"); for (const button of buttons) { button.addEventListener("click", function(event) { // find the modal and add the caller-id as an attribute var modal = document.getElementById("confirmModal"); modal.setAttribute("caller-id", this.getAttribute("id")); // extract texts from calling element and replace the modals texts with it if ("message" in this.dataset) { document.getElementById("modal-message").innerHTML = this.dataset.message; }; if ("buttontext" in this.dataset) { document.getElementById("confirmButtonModal").innerHTML = this.dataset.buttontext; }; }) } document.getElementById("confirmButtonModal").onclick = () => { // when the Confirm Button in the modal is clicked var button_clicked = event.target var caller_id = button_clicked.closest("#confirmModal").getAttribute("caller-id"); var caller = document.getElementById(caller_id); // open the url that was specified for the caller window.location = caller.getAttribute("href"); }; }); </script> base.html <!DOCTYPE … -
Best framework to build a dev log website?
this is not be a technical question but my research on the internet has not answered my questions, so I would like to ask here. I have a few projects that I am working on that I would like to write about in a dev log fashion. Sort of like progress report. However, I would like for users to leave a like, or comment under a thread that I (and only I) post. However, I do not want to use WordPress, or anything like it, because I would like to build something from scratch. This is because I am interested as to how it all works, and it will be a good resume project. Is Django a good fit for this? Django has a cool admin panel built in that I can use to add content, I believe. What about Next.js? What are some suggestions? Thank you -
Assign database value to Django variable
Looking to do something like this is Django: $price = mysql_query("SELECT price FROM products WHERE product = '$product'"); $result = mysql_fetch_array($price); If $result['price'] == 1: do something My thought was something like below but seems to be way off: Item = Products.objects.get(product=pk) price = item.price status = item.status if price == 2: Do Something please note this is not being used to output to a template, as I already know how to do that. -
Calculate sum of model objects in django serializers
In my app, each user has his wallets in which he can save his daily expenses. How can I get sum of money for each instance of wallet with many expenses saved to it? I've tried serializers.SerializerMethodField() from django.db.models import Sum from django.db.models import Q class WalletInstanceSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.id') entry = BudgetEntrySerializer(many=True, read_only=True) expense_sum = serializers.SerializerMethodField() class Meta: model = WalletInstance fields = '__all__' def get_expense_sum(self, obj): return WalletInstance.objects.filter(Q(id=obj.id)|Q(entry__entry_type='income')).aggregate(Sum('entry__amount'))['entry__amount__sum'] And this gives me data in the correct format but the sum is wrong, for example [ { "id": "d458196e-49f1-42db-8bc2-ee1dba438953", "owner": 1, "entry": [ { "id": 3, "owner": 1, "title": "dsfdsf", "amount": 7, "description": "sdfdsf", "entry_type": "income", "date_added": "2022-08-13", "entry_category": { "id": 2, "name": "Transport" } }, { "id": 4, "owner": 1, "title": "fesfvsdfgvbtdg", "amount": 12, "description": "efesf", "entry_type": "income", "date_added": "2022-08-13", "entry_category": { "id": 2, "name": "Transport" } } ], "viewable": [ "admin@gmail.com" ], "expense_sum": 83, "name": "dsdsds", "date_added": "2022-08-13" } ] Expense_sum is 83 but amount fields are 7 and 12 so that's equal to 19 How can i get the correct number? Models class BudgetEntry(models.Model): STATE= [ ('income','income'), ('expenses','expenses'), ] owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='owner_of_entry', on_delete=models.CASCADE) title = models.CharField(max_length=20) amount = models.IntegerField() description = models.CharField(max_length=60, null=True) entry_type = … -
Django Custom Login
I want a Loginpage which redirects User based on groups AND their username pk. Like Staff has a dashboard which they can see all the work from employees while employees are redirected to their own page based on their pk I made something with class based views and it works. But Staff are redirected to an empty page where they can click on a dashboard button which redirects them there. This dashboard button shows only if they are in a specific group restricted by a for loop in the template. And when employers try to go manually to that dashboard they see an empty page bc of the for loop for staff member but besides the horrible security I know that it must be somehow possible to do an if condition. But no matter where I look or what I try thats the only result I have. Does anybody has an idea ? template: {% for group in request.user.groups.all %} {% if group.name == 'Personalverwaltung' %} <li><a href="{% url 'Dashboard' %}">dashboard</a></li> {% endif %} {% endfor %} {% for group in request.user.groups.all %} {% if group.name == 'Personalverwaltung' %} html {% endif %} {% endfor %} View: class Einloggen(LoginView): template_name … -
SMTPServerDisconnected even though it was working properly a few days ago
I am using Django and I'm trying to send a verification email (with gmail) when the user registers, this was working fine some days ago, but then it suddenly stopped working. I have already created a new Google Application password and it is still not working. When the site tries to send the email it raises "SMTPServerDisconnected at /register/Connection unexpectedly closed". This are my settings for email. # EMAIL CONFIG DEFAULT_FROM_EMAIL = 'mymail@gmail.com' EMAIL_FROM_USER= 'mymail@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mymail@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_PORT = 587 And this is my view: def send_action_email(user,request): current_site = get_current_site(request) email_subject = 'Activa tu cuenta' email_body = render_to_string('users/activate.html',{ 'user':user, 'domain':current_site, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token': generate_token.make_token(user) }) email = EmailMessage(subject=email_subject,body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email] ) email.send() def activate_user(request,uidb64,token): try: uid=force_text(urlsafe_base64_decode(uidb64)) user= User.objects.get(pk=uid) except Exception as e: user=None if user and generate_token.check_token(user,token): user.email_is_verified=True user.save() messages.success(request, 'Se ha verificado tu email, ya puedes inciciar sesion!') return redirect('login') return render(request,'appName/activation_failed.html',{"user":user}) Might it be that google is not allowing me to login to the mail? -
Do I need to import class on it's own file?
Ok so, I have created 2 model classes for my Django Rest application and am trying to use foreign key to join both models. Here's my code: from django.db import models from . import Author class Article(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Author(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=100) The thing is, this line from . import Author is kind of annoying, and when I remove it Pylance puts a warning message in the Author parameter at the Article class ("Author" is not defined). My question is, do I really need to import the class in the same file it is being used? -
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.