Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Distinguish which link-button clicked in django
I have that html code: <form id="my-form" method="POST" action="{% url 'my_view' %}"> {% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="md-form mb-1"> <textarea id="message" name="message" rows="2" class="form-control md-textarea"></textarea> </div> </div> <div class="col-md-6"> <div class="md-form mb-1"> <textarea id="message_then" name="message_then" rows="2" class="form-control md-textarea"></textarea> </div> </div> </div> <div class="text-center text-md-left"> <a class="btn btn-primary" onclick="document.getElementById('my-form').submit();" style="width: 78px;" name="name1">Click1</a> </div> <div class="text-center text-md-left"> <a class="btn btn-primary" onclick="document.getElementById('my-form').submit();" style="width: 78px;" name="name2">Click2</a> </div> </form> Now I would like to get to know which "button" was clicked. Unfortunately request.POST doesn't have that information. -
Why this form doesn't change the language of the website?
This is my language-switching form. {% get_current_language as lang_code %} {% get_available_languages as languages %} {% get_language_info_list for languages as langs %} <form action="{% url 'set_language' %}" method="POST"> {% csrf_token %} <select name="language" title="{% translate 'Language' %}"> {% for lang in langs %} <option value="{{ lang.code }}"{% if lang.code == lang_code %} selected{% endif %}> {{ lang.name_local }} ({{ lang.name_translated }}) </option> {% endfor %} </select> <input type="submit" value="OK" /> </form> I include this in the footer of my base template. Then, here is my courses/urls.py (app urls). from django.contrib import admin from django.urls import path from django.utils.translation import gettext_lazy as _ from . import views admin.site.site_header = _("FilFak administration") admin.site.site_title = _("FilFak admin") admin.site.index_title = _("Manage FilFak") urlpatterns=[ path("courses/", views.CourseList.as_view(), name="course_list"), path("professors/", views.ProfessorList.as_view(), name="professor_list"), path("exams/", views.ExamList.as_view(), name="exam_list"), path("courses/<slug:slug>", views.CourseDetails.as_view(), name="course_details"), path("professors/<slug:slug>", views.ProfessorDetails.as_view(), name="professor_details"), path("exams/<slug:slug>", views.ExamDetails.as_view(), name="exam_details"), path("", views.Index.as_view(), name="index"), ] And lastly filfak/urls.py (project urls.py). from django.contrib import admin from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static from django.conf import settings from django.utils.translation import gettext_lazy as _ urlpatterns = [ path("admin/", admin.site.urls), path("lang/", include("django.conf.urls.i18n")), ] urlpatterns += i18n_patterns( path("", include("courses.urls")), prefix_default_language=False ) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I click OK … -
Making readonly() field on modelform in Django 3.2.8
I'm trying to clon a form from a model and I want one specific field to be readonly but this field must POST the data to the DB as usual(it will initated with a pre-selected value).. All the SO questions that I've read were about old versions of Django and major part of them are mentioning about the leak with readonly(). So far I tried to implement idea's from old SO posts but I didn't succeed. Help please.. views.py class HairRequestFormView(FormView): template_name = 'request_templates/hair_request.html' form_class = HairRequest_form success_url='/thanks/' def form_valid(self, form): form.save() form.send_email() return super().form_valid(form) forms.py class HairRequest_form(forms.ModelForm): class Meta: model = Offline_User fields = "__all__" #pre-selected element block def __init__(self, *args, **kwargs): super(HairRequest_form, self).__init__(*args, **kwargs) self.fields['Request'].initial = Request(1) so I want that pre-selected field should be also readonly. Since readonly() func. will cause leaks is there any other approaches? Thanks -
Creating a multiplechoice field using many to many relationship
Im trying to add a field called, interested_fields inside my personalInfo model which users can choose from and the choices themselves come from another models' objects with the help of ManyToMany relation between the two models. Here are my models.py codes(I simplified my personal model by removing some other fields like name, age, etc in order to make it more readable for you): class Field(models.Model): id = models.AutoField(primary_key=True) slug = models.CharField(max_length=16, default='default') title = CharField(max_length=32) class PersonalInfo(models.Model): id = models.AutoField(primary_key=True) interested_fields = models.ManyToManyField(Field, blank=True) then, I created a ModelForm like this: class InterestedFieldsForm(forms.ModelForm): interested_fields = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=Field.objects.all(), required=False) class Meta: model = PersonalInfo fields = ['interested_fields'] and created a get and post functions inside my views like this: class PersonalView(View): template_name = 'reg/personal.html' def get(self, request, *args, **kwargs): context = {} context['fields'] = Field.objects.all() return render(request, self.template_name, context=context) def post(self, request, *args, **kwargs): user = request.user if request.method == 'POST': form = InterestedFieldsForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() else: form = InterestedFieldsForm() return render(request, 'reg/done.html', context={'form': form}) and finally in template, inside the form I added this for loop: {% for field in fields %} <label class="containerq ant-col ant-col-md-6 ant-col-xs-8" > <span> <input type="checkbox" name="interested_fields" {% … -
Traverse multiple manytomany relationship, without iterating
class ModelA(models.Model): # ... class ModelB(models.Model): my_model_a = models.ManyToManyField(ModelA, blank=True) my_model_c = models.ManyToManyField(ModelC, blank=True) class ModelC(models.Model): # ... Suppose that I have an instance of ModelA in a variable myModelA. I would like to have a queryset with all ModelC instances associated to it, if any. def solution(myModelA): result = [] for model_b in myModelA.modelb_set.all(): result.append(model_b.my_model_c.all()) return set(result) This solves the problem, but requires iterations in Python. Is this doable solely with the ORM, without iterating in Python? -
Template Inheritance Does Not Work - Django Tutorial
I am following Corey Schafer' Django tutorial. I have reached where I have to create a base.html template inheritance. After adjusting everything according to my project and running the server, my webpage presents itself as a source code in html format. click to see the page after server run. My views.py code: from django.shortcuts import render from django.http import HttpResponse from django.template import loader # Create your views here. def index(request): text = "welcome to the website - python" posts = [ { 'title': 'The Fault in Our Stars', 'price': '3.0 BD', 'post_date': '24-10-2021' }, { 'title': 'The Black Swan', 'price': '3.5 BD', 'post_date': '23-10-2021' }, { 'title': 'Watchmen', 'price': '5.0 BD', 'post_date': '22-10-2021' } ] context = { 'text': text, 'posts': posts } return render(request, 'blog/index.html', context, {'title': 'Bookish Bahrain - Home'}) My base.html code: <!DOCTYPE html> <html lang="en"> <head> {% if title %} <title> {{ title }} </title> {% else %} <title> Bookish Bahrain </title> {% endif %} </head> <body> {% block content %}{% endblock %} </body> </html> My index.html code: {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <p> {{post.title}} </p> <p> {{post.price}} </p> <p> {{post.post_date}} </p> {% endfor %} {% … -
How to filter category wise product in Django using generic class view
I am making a POS system where there would be customers and each customer would have there own transactions. I can show all the transactions but having tough time figuring out how to filter transactions based on customer only. In models.py class Customer(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() address = models.CharField(max_length=200) number = models.IntegerField(null=True, blank=True) class AccountHolder(models.Model): customer = models.ForeignKey(Customer, on_delete=CASCADE) date = models.DateTimeField(default=timezone.now, auto_created=True) share_deposit = models.IntegerField(blank=True, null=True) share_return = models.IntegerField(blank=True, null=True) share_total = models.IntegerField(blank=True, null=True) I want to use generic classes in order do the filtration. Inside views.py class CustomerDetail(ListView): model = AccountHolder context_object_name = 'customers' template_name = 'customertransaction.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['customers'] = context['customers'].filter(customer=self.request.customer) -
Django: How to convert string and int into variable
I have declared a variable as" a1 = 10 Now in a function I need to call this variable by adding "a"+"1". However result is a1 in string and not above declared variable. Here is the code: a1 = 10 b = "a"+"1" print(b) a1 when I print b, answer is a1, instead of 10. How can I change this concatenate to declared variable? -
How to create test case with Factory boy? Django
I am trying to test my code using factory boy, but i am still getting errors like "django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username " or "The row in table 'analytics_event' with primary key '1' has an invalid foreign key: analytics_event.created_by_id contains a value '7' that does not have a corresponding value in auth_user.id." my model: class Event(models.Model): name = models.CharField('the name of the event', max_length=255) created_at = models.DateTimeField(default=timezone.now, validators=[LessThanNowValidator()]) additional_data = models.CharField(max_length=300, blank=True, default='') created_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.name}" class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) api_token = models.CharField(max_length=100, blank=True, null=True, unique=True) def __str__(self): return f"{self.user.username}" I am trying to test with factory boy: class EventFactory(factory.django.DjangoModelFactory): class Meta: model = Event created_by = None class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = factory.Sequence(lambda n: "User %d" % n) @factory.post_generation def user_related_models(obj, create, extracted, **kwargs): if not create: return EventFactory.create( created_by=obj ) john = UserFactory.create() class EventTestCase(TestCase): def test_post(self): self.assertEquals( Event.objects.count(), 0 ) Event.objects.create( name='event1', created_by=john ) self.assertEquals( Event.objects.count(), 1 ) -
Django how to output value list to html for 'for loop' in my case?
I want to know how I can ouput something like [value1, value2, value3] from Django, the Chart.js use data format like this. In my understanding, the counts_data=...aggregate(..., ..., ...) is a list similar to value list (value1, value2, value3), but then when I return, it must to be a dict, so I turn it context = {"counts_data", counts_data}, which is similar to {counts_data1: (value1, value2, value3), counts_data2:(value1, value, value3),...}, so I'm not sure how I can output data like [value1, value2,value3], I tried to put them into one queryset, but a queryset can only get or filter one status, I have 3 status, so I'm confused, it would be great if anyone could explain a little bit? Cheers views.py ''' def visualisation(request, project_id): project = Project.objects.get(id=project_id) counts_data = Todo.objects.aggregate( to_do_count=Count('id', filter=Q(status='to_do')), in_progress_count=Count('id', filter=Q(status='in_progress')), done_count=Count('id', filter=Q(status='done')) ) return render(request, 'todo_lists/progress.html', {"counts_data":counts_data}) ''' html ''' $(document).ready(function() { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'doughnut', data: { // labels format ['label1', 'label2', 'label3', ] // you can choose to have a static labels if you are sure that // there is always a specific number of labels labels: [{% for label in counts_data %} '{{ label }}', {% … -
Multiplying three models in django and getting the result in views
My model: class VisData(models.Model): visdata_id = models.AutoField(primary_key=True,blank=True) user_name = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL,blank=True) title = models.CharField(max_length=200, null=True,blank=True) buy_sell = models.CharField(max_length=1, null=True,blank=True) date = models.DateField(auto_now_add=False,null=True,editable=True,blank=True) hour = models.TimeField(auto_now=False, auto_now_add=False,null=True,editable=True,blank=True) shares_number = models.DecimalField(decimal_places=0,default=0,max_digits=999,null=True,blank=True) course = models.DecimalField(decimal_places=2,default=0,max_digits=999,null=True,blank=True) fare = models.DecimalField(decimal_places=2,default=0,max_digits=999,null=True,blank=True) def __str__(self): return self.title and I want to assign: total_value = (shares_number * (course - fare)) and just print it in terminal my views: def summaryPage(request): visdata = VisData.objects.all() #print(visdata) context = {} return render(request, 'smth/homepage.html', context) I found some close answers but I couldn't understand the solution and use them in my code -
How to store only the desired values in Django View
I'm a student learning Django for the first time. I want to save only the values I want in Django's View, but I don't know what to do. Below are Models.py and Views.py, forms.py. I want to save it by entering only one without entering second_value and third_value in value_name. Please help me a lot. def product_upload(request): current_category = None categories = Category.objects.all() products = Product.objects.all() photos = Photo.objects.all() designated_object = Designated.objects.all() options = Option.objects.all() slug = Product.slug if request.method == "POST": form = ProductForm(request.POST, request.FILES) if form.is_valid(): product = Product() product.name = form.cleaned_data['name'] product.benefit = form.cleaned_data['benefit'] product.detail = form.cleaned_data['detail'] product.target_price = form.cleaned_data['target_price'] product.start_date = form.cleaned_data['start_date'] product.due_date = form.cleaned_data['due_date'] product.category_code = form.cleaned_data['category_code'] product.image = request.FILES['photo'] product.username = request.user product.slug = slug product.kakao_link = form.cleaned_data['kakao_link'] product.save() for img in request.FILES.getlist('image'): photo = Photo() photo.product_code = product photo.photo = img photo.save() if request.method == "POST": form = OptionForm(request.POST) if form.is_valid(): option = Option() option.name = form.cleaned_data['option_name'] option.product_code = product option.save() if request.method == "POST": form = ValueForm(request.POST) if form.is_valid(): value = Value() value.name = form.cleaned_data['value_name'] value.option_code = option value.product_code = product value.extra_cost = form.cleaned_data['option_price'] value.save() if request.method == "POST": form = ValueForm(request.POST) if form.is_valid(): value = Value() value.name = form.cleaned_data['second_value'] value.option_code = … -
{"user":["This field is required."]} in Django REST Framework
Where does Django get the User from in self.request.user? When executing a GET request, Django sees the User, and when executing a POST request, he does not see it and throws such an error. User information is transmitted in the cookie from the frontend. views.py from rest_framework import generics from rest_framework.permissions import IsAuthenticated from rest_framework import pagination from rest_framework.response import Response from api.models.notes import Notes from api.serializers.notes import NotesSerializer class FilterNotes(generics.ListCreateAPIView): serializer_class = NotesSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): return Notes.objects \ .filter(user=self.request.user.id) \ .order_by('-time') -
Show products based on category slug in Django 3
I have created a category and subcategory in a project and it is showing as I wanted, but now having a little difficulty in getting the products to the category page. I have a parent category and sub-category but not in all cases will the parent category have a subcategory. #models.py #Category Model class Category(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(max_length=25) parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) class Meta: verbose_name_plural = 'Categories' ordering = ('name',) def __str__(self): return self.name #Product Model class Product(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=110) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) #views.py def home(request): products = Product.objects.all().order_by('?') categories = Category.objects.all() featured_products = Product.objects.filter(is_featured=True) context = { 'products':products, 'category':categories, 'featured_products':featured_products } return render(request, "store/home.html", context) Below is my HTML code <div class="container"> <nav class="main-nav"> <ul class="menu sf-arrows"> <li class=""><a href="{% url 'home-page' %}">Home</a></li> <li class=""><a href="{% url 'about-page' %}">About</a></li> <li class=""><a href="{% url 'home-page' %}">Services</a></li> {% for category in category %} {% if category.parent == None %} {% if category.parent.children %} <li><a href="{{category.get_absolute_url }}" class="sf-with-ul">{{category.name}}</a> {% else %} <li><a href="{{category.get_absolute_url }}" class="">{{category.name}}</a> {% endif %} <ul> {% for subcategory in category.children.all %} <li><a href="{{sucategory.slug}}">{{subcategory.name}}</a></li> {% endfor %} </ul> </li> {% endif %} {% endfor %} <li … -
Django: Save method to save total of 3 columns in another model
I have 2 models as follow: class particulars(models.Model): reportref = models.ForeignKey(reportname,on_delete=models.CASCADE) year = models.CharField(max_length=250) sales = models.FloatField(blank=True,null=True,default=0) profit = models.FloatField(blank=True,null=True,default=0) def save(self, *args, **kwargs): self.profit = round((self.sales-self.depreciation),2) super(particulars, self).save(*args, **kwargs) def __str__(self): return str(self.year) class depreciation(models.Model): reportn = models.ForeignKey(reportname,on_delete=models.CASCADE) asset = models.CharField(max_length=250) cost = models.FloatField(blank=True,null=True,default=0) rate = models.FloatField(blank=True,null=True,default=10) depreciation_1 = models.FloatField(blank=True,null=True) wdv1 = models.FloatField(blank=True,null=True) depreciation_2 = models.FloatField(blank=True,null=True) wdv2 = models.FloatField(blank=True,null=True) depreciation_3 = models.FloatField(blank=True,null=True) wdv3 = models.FloatField(blank=True,null=True) depreciation_4 = models.FloatField(blank=True,null=True) wdv4 = models.FloatField(blank=True,null=True) depreciation_5 = models.FloatField(blank=True,null=True) wdv5 = models.FloatField(blank=True,null=True) def save(self, *args, **kwargs): self.depreciation_1 = round((self.cost*self.rate/100),2) self.wdv1 = round((self.cost-self.depreciation_1),2) self.depreciation_2 = round((self.wdv1*self.rate/100),2) self.wdv2 = round((self.wdv1-self.depreciation_2),2) self.depreciation_3 = round((self.wdv2*self.rate/100),2) self.wdv3 = round((self.wdv2-self.depreciation_3),2) self.depreciation_4 = round((self.wdv3*self.rate/100),2) self.wdv4 = round((self.wdv3-self.depreciation_4),2) self.depreciation_5 = round((self.wdv4*self.rate/100),2) self.wdv5 = round((self.wdv4-self.depreciation_5),2) super(depreciation, self).save(*args, **kwargs) def __str__(self): return str(self.asset) I have written save method to update depreciation for each year whenever a user put cost for assets. However I need to also update particulars model with depreciation for each year. What I am trying to get is total the depreciation of each asset for every year and put it in particulars table. Any way to do that? -
No "Authorization" header, how to access authorization header? Django
I need to check the Authorization HTTP Header of every incoming request. First i have implemented Middleware. Now on website in devtools (when i post something) i see authorizational header with token. class MyMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user_id = request.POST.get('created_by', False) try: api_token = CustomUser.objects.get(user=user_id).api_token except CustomUser.DoesNotExist: api_token = '' response = self.get_response(request) response['Authorization'] = "Bearer " + api_token return response and now im trying to access Authorization HTTP Header of every incoming request to validate it but there is no Authorization Header class EventApiView(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = Event.objects.all() serializer_class = EventSerializer @action(methods=['POST'], detail=False) def post(self, request): print(request.META['HTTP_AUTHORIZATION']) **#keyerror** print(request.META['Authorization']) **#keyerror** print(request.headers.items()) **#no authorization header** tutorial_serializer = EventSerializer(data=request.data) if tutorial_serializer.is_valid(): tutorial_serializer.save() return Response(tut`enter code here`orial_serializer.data, status=status.HTTP_201_CREATED) return Response(tutorial_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django; update products but preserve purchase history
TLDR: How to edit products without changing the history of order/purchases wherein that product has been bought? I want to incorporate the option to do purchases in my website. I have a backend with django-drf and frontend react. In the frontend I want to be able to add, edit, and remove products. To create a consistent database I see two things being done on stack: copy all relevant fields from the product table over to the purchase table upon edit of a product create a new product instead of actually updating, and upon removal of a product flag it as deleted instead of actually deleting I am inclined to favor the second option, since it keeps the database easier to understand and maintain. However, it makes the update and removal logic harder. My toughts for implementation are roughly this: models.py from django.db import models class Product(models.Model) : name = models.CharField(max_length=120) price = models.DecimalField(max_digits=10, decimal_places=2) has_been_removed = models.BooleanField(default=False) ... class Purchase(models.Model) : product = models.ForeignKey(Product, related_name="purchases", on_delete=models.PROTECT) quantity = models.IntegerField(max_length=120) total = models.DecimalField(max_digits=10, decimal_places=2) ... serializer.py from django.db import models from .models import Product, Purchase class ProductSerializer(models.Serializer): ... def update(self, instance: Product, validated_data): has_associated_purchases = Purchases.objects.filter(product=instance).exists() if has_associated_purchases: new_product = Product(**validated_data) … -
How to handle a formset in function based view
I'm trying to implement a formset in function create based view to allow users to create their own course model, somehow when i try posting the data to the database only the course model data get sent to the database leaving the module data not persisted to the data base. why is function create view not persisting the data, Of my module to the model data base and how best can i do this. I know of the class create view solution but it actually doesn't help in my user case. and so i think using a function create view will be much favorable to my case. Here my function create view. def course_create(request): Formset = formset_factory(CreateCourse, extra=2) if request.method =="POST": formset_data = Formset(request.POST, request.FILES) sub = request.POST.get('subject') course = request.POST.get('title') overview = request.POST.get('overview') slug = request.POST.get('slug') pic = request.FILES['c_pic'] owner = Account.objects.get(username=request.user.username) sub,create = Subject.objects.get_or_create(title=sub) data = Course(title=course,owner=owner, pic=pic, subject=sub, slug = slug, overview=overview) data.save() if formset_data.is_valid(): data = formset_data.save(commit=False) data.course = data formset_data.save() return redirect('courses:main') Here is my Forms.py class CreateCourse(forms.ModelForm): class Meta: model = Module fields = ['title', 'description'] def save(self,commit=True): module = super(CreateCourse, self).save(commit=False) module.title = self.cleaned_data["title"] module.description = self.cleaned_data['description'] if commit: module.save() return module model.py … -
Django form with model choice filed
i have a problem with form in django. I was create a model form but he not save choicefield to database.Form save only a title(CharField).I was create a function that solving problem but i think its bad and can be write much better. Any help? class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) TOPIC_CAT=[ ('WEL', 'Spawlnictwo'), ('DIY', 'Majsterkowanie'), ('ELE', 'Elektryka'), ('IT', 'Informatyka'), ('CAT', 'Stolarstwo'), ] categories = models.CharField(max_length=3, choices=TOPIC_CAT) def __str__(self): return self.text FORM class NewTopic(forms.ModelForm): class Meta: model = Topic fields = ['text', 'categories',] labels = {'text':'Nazwa tematu', 'categories': 'Kategoria'} FUNCTION def new_topic(request): if request.method != 'POST': form = NewTopic() else: form = Search(data=request.POST) if form.is_valid(): new_topic = form.save(commit=False) cat = request.POST.get('categories') new_topic.categories = cat new_topic.save() return redirect('forum:topics_in_category', category=cat) context = {'form': form} return render(request, 'forum/new_topic.html', context) Second problem is a search form.I want the search field to be visible all the time like in stackoverflow website but i dont have idea how.Already did a button that open a new website with form -.- -
is it ok to create ManyToMany with no through Field?
so in Django models documentation when I have to add extra data to ManytoMany fields, the django documentation recommend I use 'through' like this example class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) in the admin panel this is good but when I try to use it on views.py to create API I get many problems that I can't get Membership fields info from Group model but when I created model like that it became possible: class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField('Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) not following docs makes me feel I'm doing it wrong since I'm a beginner I don't know if the way I did is good or not? like is it bad to create a model like that? if I should go back to using 'through' then is there a possible way to get Membership fields from the Group model? -
Why the translate tag doesn't work outside a block?
I have a base template... {% load static %} {% load i18n %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> {# Translators: The title of the website #} {% translate "FilFak" as the_title %} {# Translators: The description and subtitle of the website #} {% translate "Appointments, tasks and much more" as the_description %} <meta name="title" content="{{ the_title }}" /> <meta name="description" content="{{ the_description }}" /> <meta property="og:title" content="{{ the_title }}" /> <meta property="og:description" content="{{ the_description }}" /> <title>{% block title %}{{ the_title }}{% endblock title %}</title> <link href="{% static 'css/style.css' %}" rel="stylesheet" type="text/css" /> </head> <body> <header> <h1><a href="{% url 'index' %}">{{ the_title }}</a></h1> <p>{{ the_description }}</p> </header> <main> {% block content %} {% endblock content %} </main> <footer> {% include "courses/lang_form.html" %} </footer> </body> </html> And I have a few templates extending the base templates. Here's an example. {% extends "courses/base.html" %} {% load i18n %} {% translate "List of professors" as page_title %} {% block title %}{{ page_title }} | {{ block.super }}{% endblock title %} {% block content %} {% for professor in professor_list %} <article> <header> <h3 class="title"><a href="{% url 'professor_details' professor.slug %}">{% if professor.title %}{{ professor.title }} {% endif %}{{ professor.name }}</a></h3> </header> <p><span … -
Why Django ORM multiplies my results as many times as many users I have?
Im working on a project where I need to query some stuff but I'm not familiar with Django ORM. My query works fine but it multiplies the result as man time as my user related to a project and I can't figure it out how to limit it. In raw query I usually do it with inner join but this works not in this case. views.py def projects(request): jogosult = Projekt.objects.filter(jogosult_01_id=request.user) jog_projekt = Projekt.objects.filter(jogosult_01=request.user).order_by('-date') context = { 'jogosult': jogosult, 'jog_projekt': jog_projekt, } return render(request, 'stressz/projects.html', context) html {% for j in jogosult %} {% if request.user == j.jogosult_01 %} {% for jp in jog_projekt %} <a href="/mpa/project_details/report/{{ jp.id }}">{{ jp.projekt }}</a> {% endfor %} {% else %} You have no projets {% endif %} {% endfor %} models.py class Projekt(models.Model): def __str__(self): return str(self.projekt) projekt = models.TextField(max_length=150) company_name = models.ForeignKey('Company', on_delete=models.CASCADE, default=1) jogosult_01 = models.ForeignKey(User, on_delete=models.CASCADE, default=1) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) -
Connecting locally to online db mysql server with django
I have made a database on an online server http://remotemysql.com/ with the remote access on https://www.webphpmyadmin.com/ I am making my first web app in django and I wanted to connect to that server locally. Is it possible? I tried using these settings: but I have been getting this error: I have also tried using my ip adress instead of 'remotemysql.com' host, but again - I got other error: The localhost doesn't work too even with having apache and mysql running on xampp (it doesn't work both with these two running and stopped): The same with: I literally had already tried everything that I found on stackoverflow and any other forums, but nothing worked for me. That's why I decided to post a question myself. My requirements.txt: Do I have to have this database copied locally to use it in my app or is it really possible to connect it by settings.py? -
How to fix OSError: [WinError 2] The system cannot find the file specified
I tried installing Fastapi framework dependencies using the pip install Fastapi[all] command. The packages were downloaded but during installation, I got this error. Using legacy 'setup.py install' for python-multipart, since package 'wheel' is not installed. WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution - (c:\python39\lib\site-packages) Installing collected packages: sniffio, idna, colorama, typing-extensions, h11, click, anyio, websockets, watchgod, uvicorn, urllib3, starlette, six, pyyaml, python-dotenv, pydantic, MarkupSafe, httptools, dnspython, charset-normalizer, certifi, ujson, requests, python-multipart, orjson, jinja2, itsdangerous, fastapi, email-validator WARNING: Failed to write executable - trying to use .deleteme logic ERROR: Could not install packages due to an OSError: [WinError 2] The system cannot find the file specified: 'c:\\python39\\Scripts\\watchgod.exe' -> 'c:\\python39\\Scripts\\watchgod.exe.deleteme' WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution - (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution - (c:\python39\lib\site-packages) Python version: Python 3.10.0 pip version: pip 21.3 from c:\python39\lib\site-packages\pip (python 3.9) -
Django - Query 10 table objects before or after a date?
I was reading this blog on pagination, but I'm trying to do quick queries by create date time. So for example if I get a request and one of the parameters is a date time I want a quick way to get the next 10 posts created in order. The reason I can't use this blog post is because the table could be updated by the time the user tries to request older or newer posts as it gets updated quite frequently. So in a simple toy example: If I have a list of dates [1-01-2021, 1-05-2021, 1-06-2021] and I already sent 1-01-2021 to the user and the user sends me that date and expects the next single date it should return 1-05-2021 and not return dates it already has. How can I do this quickly and efficiently? I imagine it might be tricky, because I have to order my table first. I'd like to be to do this in 2 directions as in forward and backward in times. So if someone gives me a date to one endpoint will return the 10 posts that came after that and another endpoint if given a date it will return the 10 …