Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'BlogListView' object has no attribute 'object_list' in Django
I have a blog page with a list of posts that are paginated with ListView and on the same page I have a newsletter form where a uses can enter an email an be subscribed and I tried this in order to achive all this on the same page but I get this error and I don't know how to get rid of it. my view: class BlogListView(ListView): model = Post template_name = 'blog/blog.html' context_object_name = 'posts' ordering = ['-published_date'] paginate_by = 2 filterset_class = PostFilterForm post_search_title = None def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) email = request.POST.get('newsletter_email') if Newsletter.objects.filter(email=email).exists(): messages.warning(request, messages_text['email_exists']) else: Newsletter.objects.create(email=email) messages.success(request, messages_text['email_subscribed']) return redirect('blog') return render(request, self.template_name, context) def get_queryset(self): queryset = super().get_queryset() self.post_search_title = self.filterset_class(self.request.GET, queryset=queryset) return self.post_search_title.qs.distinct() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['post_search_title'] = self.post_search_title tags = Post.tags.most_common()[:8] context['banner_page_title'] = template_titles['blog_title'] context['page_location'] = template_titles['blog_path'] context['tags'] = tags return context the error AttributeError at /blog/ 'BlogListView' object has no attribute 'object_list' -
Django Rest Framework: append value to ListAPIView
Hello StackOverflow community, I've got following serializer and view: serializers.py class PricetrendSerializer(serializers.ModelSerializer): timestamp = serializers.DateTimeField() average_price = serializers.IntegerField() class Meta: model = Cars fields = ('timestamp', 'average_price') views.py class Pricetrend(generics.ListAPIView): queryset = Cars.objects.annotate(timestamp=TruncMonth('timestamp')).values('timestamp').annotate(average_price=Avg('price')) serializer_class = PricetrendSerializer filter_backends = (filters.DjangoFilterBackend, SearchFilter, OrderingFilter) filterset_class = PriceFilter search_fields = ['description'] ordering_fields = ['timestamp', 'average_price'] ordering = ['timestamp'] permission_classes = (permissions.IsAuthenticated,) Which is giving me the following output: { "count": 2, "next": null, "previous": null, "results": [ { "timestamp": "2020-04-01T00:00:00", "average_price": 90274 }, { "timestamp": "2020-05-01T00:00:00", "average_price": 99253 } ] } I would like to also aggregate the total average price and add it to the output, e.g.: { "count": 2, "next": null, "previous": null, "total_average_price": 125000, "results": [ { "timestamp": "2020-04-01T00:00:00", "average_price": 90274 }, { "timestamp": "2020-05-01T00:00:00", "average_price": 99253 } ] } Unfortunately, I do not know how this could be done as adding it to the serializer will result in having the total_average_price in every json object. I also tried to override the ListAPIView (get function) but this killed the built-in pagination :( I hope that somebody is able to help me find a neat way to solve this. -
querying between multiple django models
I have 3 models categories, badges, and reward. The users are awarded badges and are stored under reward. The user model is the default model provided by django. class BadgeCategory(models.Model): name = models.CharField(max_length=30) class Badge(models.Model): points = models.IntegerField(default=1) title = models.CharField(max_length=30) category = models.ForeignKey(BadgeCategory,on_delete=models.SET_NULL,null=True) class Reward(models.Model): awarded_by = models.CharField(max_length=30) user = models.ForeignKey(User, on_delete=models.CASCADE) badges = models.ForeignKey(Badge, on_delete=models.CASCADE) BadgeCategory refers to the category under which the badge falls, Badge refers to various badges. and reward contains all the various badges given to users. I am looking to find a query such that I get the following format of the output Username category 1 category 2 user 1 count(category 1) count(category 2) user 2 count(category 1) count(category 2) here count(category k) refers to the number of rewards that user has received having category k, If no reward is received it should be zero and username column should contain all the users. I have tried and reached to this query Reward.objects.all().values('user__username','badges__category__name') \ .order_by().annotate(Count('badges__category__name')) This gives the output having the users that have received at least one reward and only the category of which the badge has been received and the corresponding count of badges with that category, Let's say my database has 2 … -
Re-evaluate class OR make meta inner class lazy
I genuinely can't figure this out - been working on it for days. In django I have: globalvariablename = "tablename" class foo (models.Model): # Some attributes I don't care about class Meta: db_table = globalvariablename Now it's pretty obvious both foo and Meta will be evaluated once the class is imported / server is instantiated. Problem: I want db_table to be reassigned once I change globalvariablenamevalue My question: Is there anyway to make the Meta inner class lazy i.e. for it not to be evaluated until the model is used (e.g. when data is fetched from the database)? Alternatively, is there any way to re-evaluate Meta's db_table attribute once the globalvariablename has changed? Any help is appreciated. I'm literally pulling my hair out I've experimented lots with decorators i.e. for the Meta inner class to be added dynamically. This doesn't work because db_table is already assigned automatically as soon as the model is created and decorating it will just create additional duplicate values of db_table. -
Can Django serve different domains inside one single project?
I know about the sites framework but it requires to split the setting files and I'm not sure how to handle that in Apache properly. I'm also trying out all the request object attributes to determine what the host is like request.get_host() or request.site of the CurrentSiteMiddleware, I'm also trying the get_current_site method like this get_current_site(request) and I even address the .domain attribue itself. However I never reliably seem to be recognize the actual domain being called by the browser, like it always refers to the SITE_ID attribute of my settings.py It seems the sites framework is not so useful other than for model association. I'm not using subdomains, they're completely different domains. Can anybody please direct me to some proper and secure (not easily spoofable) procedures that I could deploy on a VPS to handle a few domains that will have a lot of content in common? -
How to pass ModelForm data from GET to POST?
On my app users can write reviews for novels. When a user clicks the Create Review button that is displayed on the page of every novel, he should be brought to a page were he can write a review for that given novel, also the reviewer is the current request.user, so I would like to set those two things for that review. Currently I've resolved this issue by doing this in novels.html: <form action="{% url 'create-review' %}" method="get"> <button type="submit" class="btn btn-primary">Write Review</button> <input type="hidden" name="novel_id" value="{{ novel.id }}"> </form> Now in my views.py file I have the following: class ReviewForm(ModelForm): class Meta: model = Review fields = ['reviewer', 'novel', 'content', 'rating'] widgets = { 'reviewer': HiddenInput(), 'novel': HiddenInput(), } def create_review(request): if request.method == "POST": form = ReviewForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: review = Review( reviewer=request.user, novel=Novel.objects.get(pk=request.GET['novel_id']) ) form = ReviewForm(instance=review) return render( request, 'app/create_review.html', {'form': form} ) The data is passed along inside hidden input fields. This works just fine. However, what I'm wondering is if there is a better way to do it. As well as how to prevent the user from just going to app/create-review because then he would have not chosen a novel … -
Django field not appearing in validated data but it's in request
I have these serializers: class OneSerializer(serializers.ModelSerializer): class Meta: model = OneModel fields = ['time_column', 'event_column'] class TwoSerializer(serializers.ModelSerializer): survival_columns = OneSerializer(many=True, required=False) class Meta: model = UserFile fields = ['id', 'name', 'survival_columns'] Now in the create method I'm trying to retrieve survival_columns values from validated_data but it's not present! If I print the POST data the field and values appear correctly: def create(self, validated_data): print(self.context['request'].POST) # <QueryDict: {'name': ['Datos Clinicos de prueba.csv'], 'survival_columns': ['{"event_column":"Prueba","time_column":"prueba"}']}> print(validated_data) # {'name': 'Datos Clinicos de prueba.csv'} Why is the field survival_columns being filtered from the request? -
How to dynamically add django objects to a queryset
This is my models.py class Article(models.Model): title = models.CharField(max_length=100) #The title of the article # This is to count the number of users who have viewed the article viewed_user = models.ManyToManyField(User,related_name='viewed_user',blank=True) I'm trying to add the logic in the views.py in that when a user visits the particular article, if the user is not in the viewed_user list, that user is added there. This is what I have tried in the views.py article = get_object_or_4040(Article,id=id) if user in article.viewed_user.get_queryset(): print("User has already viewed the article") else: article.viewed_user.create(user=user) # THrows an error but I have gotten very many types of errors when I tried, update, create, set, append .... Any help would be appreciated THANKS. -
Resetting Django Migrations in a Production System
I have been through a lot of posts/articles/trial-and-error involving Django Migrations since I started working with the framework a few years ago, so I decided I would post a self-answered question notating the proper way to accomplish the clean reset of migrations in a Production Database leaving you with the same database structure you left with, but a fresh start with initial migrations. Overall the issue is this: When you have a larger project you start to accumulate a large number of migrations for a system built with Django. This isn't normally an issue, but when you start accumulating upwards of 50-100 migration files (where a lot of them are the addition and removal of the same fields) it is nice to have a "cleaning" option as it should be well understood that if you alter migration history incorrectly, you will be left with a system that is more-or-less frozen in a previous database state where the only way to fix the issue is manual sql-based migration changes. -
Django Login_Required decoration using If condition
I have multiple links on my page which redirects user to take quiz. Some quiz requires user to login or create an account and some does not. If I use method decorator all quiz requires login and works as expected def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied try: self.logged_in_user = self.request.user.is_authenticated() except TypeError: self.logged_in_user = self.request.user.is_authenticated if self.logged_in_user: self.sitting = Sitting.objects.user_sitting(request.user, self.quiz) else: self.sitting = self.anon_load_sitting() if self.sitting is False: if self.logged_in_user: return render(request, self.single_complete_template_name) else: return redirect(settings.LOGIN_URL) return super(QuizTake, self).dispatch(request, *args, **kwargs) However, I would like user to redirect like how method decorator does login/?next=/quiz/f506cb92-ccca-49ff-b2e5-730bbfea6a5a/take/ but instead I get /login/ how can I use method decorator here ? Also, I would like my user to come back to the page instead of going to "/dashboard" which is my LOGIN_REDIRECT_URL. My Third requirement is that I am creating a session for anonymous quiz takers and storing all their activities in session which expires in 3 days. Incase the anonymous user decides to create an account, I would like to map his session data. Is this feasible ? Please suggest/advice. -
Reason for overflow error when saving form input to model?
I'm trying to save input from a simple form to create a new "Post" object. Models.py: class Post(models.Model): Author = models.ForeignKey(User, on_delete=models.CASCADE) Topic = models.ForeignKey(Topic, on_delete=models.CASCADE, blank=True, null=True, default=uuid.uuid1, related_name="Topic") Group = models.ForeignKey(User_Groups, on_delete=models.CASCADE, blank=True, null=True, default=uuid.uuid1, related_name="User_Groups") Content = models.TextField(max_length=100) Created = models.DateTimeField(default=timezone.now) def __str__(self): return self.Content Views.py: form = PostForm(request.POST) if request.method == 'POST': if form.is_valid(): new = form.save(commit=False) new.Topic = form.cleaned_data.get('Topic') new.Content = form.cleaned_data.get('Content') new.save() The code I have now which gives me the error: Python int too large to convert to SQLite INTEGER Other variations I have tried: form = PostForm(request.POST) if request.method == 'POST': if form.is_valid(): new = form.save(commit=False) new.Topic = form.cleaned_data.get("Topic") new.Content = form.cleaned_data.get("Content") new.save() form = PostForm(request.POST) if request.method == 'POST': if form.is_valid(): new = form.save(commit=False) new.Topic = form.cleaned_data('Topic') new.Content = form.cleaned_data('Content') new.save() After searching for similar questions, it seems that I may not be correctly creating a new instance of the form, but I am not entirely sure that is the only issue here. I am very new to Django forms, so I apologize for my lack of understanding. Any nudge in the right direction would be greatly appreciated, thanks. -
WebSocket for django rest framework
i am starting learning about web sockets with django and found Django-Channels to create a chat application, but i want to create a chat app with django Rest, wich other alternatives is there to make this? i would apreciate a guide to start learning -
How to check if the current user is the same as the foreign key in a model,
I'm trying to create a link that allows updating a model called tribe but the only person who is allowed to update the model is a foreign key called a chieftain. I'm trying to get a link to appear only when the chieftain or a superuser is currently logged in and looking at the tribe page. But I'm getting a "could not parse the remainder error" and I can't see what's wrong. models.py class Tribe(TimeStamped): name = models.CharField(max_length=200,unique=True) chieftain = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) tribe_members = models.ManyToManyField(Member) def __str__(self): return self.name[:80] def is_chieftain(self,request): if (self.chieftain == request.user): return True else: return False tribe.html {% block content %} <div class="row"> <div class="col-md-10"> {% if tribe.is_chieftan() %} <p><a href="{% url 'app:update-tribe' %}">Update tribe</a></p> {%endif%} </div> </div> ... views.py def tribeview(request, tribe_id): tribe = get_object_or_404(Tribe,pk=tribe_id) playlist = tribe.playlist_set.all() context = { 'tribe': tribe, 'playlists':playlist } return render(request, 'app/tribe.html', context) class update_tribe(UpdateView): template_name='app/update_tribe.html' form_class = UpdateTribeForm model = Tribe def get_object(self, queryset=None): return Tribe.objects.filter(chieftain=self.request.user).first() def form_valid(self, form): instance = form.instance instance.cheiftain = self.request.user instance.save() return super(update_tribe, self).form_valid(form) def get_success_url(self): return reverse('app:tribe-view', args={self.object.id}) urls.py app_name = 'app' urlpatterns = [ path('', views.index, name='index'), path('tribe/<int:tribe_id>',views.tribeview,name='tribe-view'), path('tribe/<int:tribe_id>/playlist/<int:playlist_id>',views.playlistview,name='playlist-view'), path('new_tribe', login_required(create_tribe.as_view()), name="new-tribe"), path('update_tribe', login_required(update_tribe.as_view()), name="update-tribe"), ] -
Django registration form not changing and saving to database
I'm trying to create a custom form where the user can also enter his name for instance but I am facing an issue, when the registration is done the name is not saved and I can't show it on the template. here is the code: views.py def sign_up(request): form = forms.SignUpForm() if request.method == 'POST': form = forms.SignUpForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email').lower() user = form.save(commit=False) user.username = email user.save() login(request, user) return redirect('/') return render(request, 'sign_up.html', { 'form': form }) forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=250) first_name = forms.CharField(max_length=150) last_name = forms.CharField(max_length=150) class Meta: model = User fields = ('email', 'first_name', 'last_name', 'password1', 'password2') def clean_email(self): email = self.cleaned_data['email'].lower() if User.objects.filter(email=email): raise ValidationError("This email address already exists.") return email sign_up.html <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <button type="submit" class="btn btn-warning btn-block">Sign Up</button> <p class="text-center mt-3" > Already have an account? <a href="/sign-in/?next={{ request.GET.next }}"><b>Sign In</b></a> </p> </form> The html is showing me also the username, which i wanted to remove and login with email address. But nothing gets saved in database... -
How can I create an object in another model based off parent model?
I'm having trouble trying to implement (and really map out) a new model object based off a parent model. The Bucket model below has a category field based off two category_options. class Bucket(models.Model): category_options = ( ('personal', 'Personal'), ('social', 'Social'), ) class BucketObjects(models.Manager): def get_queryset(self): return super().get_queryset() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='buckets') admin_user = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='admin_user') guest_user = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='guest_user', blank=True) category = models.CharField(max_length=30, choices=category_options) ... objects = models.Manager() bucketobjects = BucketObjects() class Meta: ordering = ('-created',) def save(self, *args, **kwargs): if self.stock_list: self.stock_count = len(self.stock_list) super().save(*args, **kwargs) else: super().save(*args, **kwargs) I would like to create a new object in a completely different model, SocialBucket, when the Bucket model instance is selected as a social category based off the category field above: class SocialBucket(models.Model): bucket = models.ForeignKey(Bucket.objects.id, on_delete=models.CASCADE, related_name='social_buckets) How can I go about populating my SocialBucket model with new objects based off it's parent, Bucket, model? -
How to use python-socketio with django and reactjs?
I am getting this error Not Found: /socket.io/ HTTP GET /socket.io/?EIO=4&transport=polling&t=NSwqecY 404 [0.02, 127.0.0.1:51874] What should I do? Or any other library/method recommended. Thanks in advance.. -
Creating view with foreign key model django restframework
I'm fairly new with the django restframework. I am trying to create a serializer and a view for a model that has a foreignKey. Models.py class Job(models.Model): """A Job used to create a job posting""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) description = models.TextField() job_type = models.CharField(max_length=12, choices=JOB_TYPE_CHOICES, default='Full-Time') city = models.CharField(max_length=255) state = models.CharField(max_length=255) created_date = models.DateField(auto_now=False, auto_now_add=True) salary = models.CharField(max_length=255) position = models.CharField(max_length=255) employer = models.CharField(max_length=255) is_active = models.BooleanField(default=True) def __str__(self): return self.description[:50] class Applicant(models.Model): """A applicant that can apply to a job""" job = models.ForeignKey(Job, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(max_length=254) phone_number = PhoneNumberField() resume = models.FileField(upload_to=resume_file_path, validators=[validate_file_extension]) def __str__(self): return self.first_name The idea is that Applicant will be able to apply to Job. I can't seem to figure out how to get the Job id when a Applicant is applying to job. serializers.py class JobSerializer(serializers.ModelSerializer): """Serializer for tag objects""" class Meta: model = Job fields = ('id', 'description', 'job_type', 'city', 'state', 'salary', 'position', 'employer', 'created_date', 'is_active') read_only_fields = ('id',) def create(self, validated_data): """Create a job posting with user and return it""" return Job.objects.create(**validated_data) class ApplyJobSerializer(serializers.ModelSerializer): """Serializer for applying to jobs""" class Meta: model = Applicant fields = ('id', 'first_name', 'last_name', 'email', 'phone_number', … -
Access the object created with Creatiview
I need to access a newly created object with CreateView to be able to display it in a pdf. The user must complete a form and that form after being created must be shown in pdf. I need to know how to pass the data of the newly created form to be able to pass it to pdf. This is the code to generate the pdf def render_presupuesto_pdf(request,*args, **kwargs): template_path = 'systemapp/x.html' context = {'myvar': 'pdf content'} # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') #if donwnliad: # response['Content-Disposition'] = 'attachment; filename="report.pdf"' #if show pdf response['Content-Disposition'] = 'filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF(html, dest=response) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response And this is my code to create the form class AddPresupuestoCreateView(CreateView): '''Formulario para agregar presupuesto''' model = Presupuesto fields = ('cliente','vehiculo','fecha_entrada','fecha_entrega','precio', 'descuento','iva_porcentaje','total','sub_total','obs','comision',) template_name = 'systemapp/content/add_presupuesto.html' def get_context_data(self, **kwargs): # Sobreescribimos get_context_data para asegurarnos de que nuestro # formset sea renderizado data = super().get_context_data(**kwargs) if self.request.POST: data["add_trabajo"] = AddJobFormset(self.request.POST) data["add_material"] = AddMaterialesFormset(self.request.POST) else: data["add_trabajo"] … -
Python: errno2 no such file or directory in google colab
pip install django !django-admin startproject PyShop !python manage.py runserver ----:In the last line of code, I should be getting some kind of a web link as an output but i get this location error. Is there any syntax error -
How to filter REST API urls via date range?
How can I filter dates by selecting buttons on my frontend(vue.js), like if I select January 2020, it will display it january. or else if I select June 2020, it will display my data from June 2020. How to query it on django.objects.filter and call it on the rest api? Thanks! @views.py class RainfallView(generics.ListCreateAPIView): current_year = datetime.now().year serializer_class = RainfallSerializer queryset = Rainfall.objects.filter(date_year=current_year, date_month='01') def get(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = RainfallSerializer(queryset, many=True) return Response(serializer.data) @models.py class Rainfall(models.Model): level = models.CharField(max_length=10, blank=True, default='') amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) -
How to store data and display them in another view? Django
I have a simple sport events app. I log in as an user and I have a list of events I can join. When i join event, member value current_member is incremented. I have another view which contain list of events created by currently logged user. What I want to do more in this view is display also joined events. In my_events.hmtl (code below) i want to display in loop those events. How can I do it? models.py class Event(models.Model): SPORT = ( ('Football', 'Football'), ('Volleyball', 'Volleyball'), ('Basketball', 'Basketball'), ('Futsal', 'Futsal'), ('Tennis', 'Tennis'), ('Handball', 'Handball'), ('Ice Hockey', 'Ice Hockey'), ('Paintball', 'Paintball') ) creator = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) sport = models.CharField(max_length=20, null=True, choices=SPORT) event_name = models.CharField(max_length=30) event_date = models.DateTimeField(default=date.today()) end_event_date = models.DateTimeField(default=date.today()) current_members = models.IntegerField(default=1) total_members = models.IntegerField(default=0) event_location = models.CharField(max_length=50) cost = models.FloatField(default=0, max_length=5) description = models.CharField(max_length=300, blank=True) views.py @login_required(login_url='login') def join_event(request, pk): event = Event.objects.get(id=pk) if request.method == "POST": event.current_members += 1 if event.current_members <= event.total_members: event.save() return redirect('/') else: messages.error(request, 'Event is full!') context = {'event': event} return render(request, 'events/join_event.html', context) @login_required(login_url='login') def my_events(request): events = request.user.event_set.all() print('EVENTS', events) context = {'events': events} return render(request, 'events/my_events.html', context) my_events.html {% extends 'events/main.html' %} {% block content %} <div class="row"> … -
How can i redirect to next url via POST method with Django generic.CreateView?
Pseudocode: 1.User Signup via following class-based view. 2.If signup success,then auto login and redirect to next url(enrollment) via GET method. My problem is here. how can i redirect to next url(enrollment) via POST method? class StudentRegisterView(generic.CreateView): form_class = StudentRegisterForm template_name = 'attendance_system/register.html' success_url = reverse_lazy("enrollment") def form_valid(self,form): valid = super(StudentRegisterView,self).form_valid(form) username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username,password=password) login(self.request,user) return valid -
Django - joining a nested group_by
I want to aggregate data from 2 tables (A, B) which are linked via a 3rd table (KeyModel). I know about the use of Django's queryset methods 'values' and 'annotate', and managed to create complex queries with it, but this one I got stuck with: model A key = ForeignKey(KeyModel) value_1 = IntegerField() model B key = ForeignKey(KeyModel) value_2 = IntegerField() model KeyModel <some irrelevant fields> data - model/ table A key_id | value_1 4711 | 100 data - model/ table B key_id | value_2 4711 | 100 4711 | 100 4711 | 100 I like to achieve this result: -- key_id | sum_value_1 | sum_value_2 -- 4711 | 100 | 300 The following django/ python code generates the wrong SQL: qs = table_a.objects.filter(key_id=4711) qs = qs.values('key_id') qs = qs.annotate(sum_value_1=SUM(value_1)) qs = qs.annotate(sum_value_2=SUM(KeyModel__table_b__value_2)) will generate SELECT A.key_id, SUM(A.value_1) AS sum_value_1, SUM(B.value_2) AS sum_value_2 FROM table_a A JOIN table_b B ON B.key_id=A.key_id WHERE A.key_id=4711 GROUP BY A.key_id; But this is not what I need. The join triples the rows from table A, so the result is key_id | sum_value_1 | sum_value_2 4711 | 300 | 300 A 'slightly' changed SQL is doing what I want: SELECT A.key_id, SUM(A.value_1) AS sum_value_1, V.sum_value_2 … -
Django get data on a condition in django Admin
I'm working on a project using Django(3) in which I have created a model that has various ForeignKey fields. Now in the admin, I want to check if these ForeignKey fields are None or not, How can I do that? Here's what I have tried: From models.py: class ReportsModel(models.Model): cdr_report = models.OneToOneField(CurrencyDistributionModel, on_delete=models.CASCADE, null=True, default=None) cme_report = models.OneToOneField(CurrencyManagementExpenditureModel, on_delete=models.CASCADE, null=True, default=None) cps_report = models.OneToOneField(CurrencyProcessingStorageModel, on_delete=models.CASCADE, null=True, default=None) cma_report = models.OneToOneField(CurrencyManagementAssetsModel, on_delete=models.CASCADE, null=True, default=None) def __str__(self): if self.cdr_report is not None: return self.cdr_report.RequestId elif self.cme_report is not None: return self.cme_report.RequestId elif self.cps_report is not None: return self.cps_report.RequestId elif self.cma_report is not None: return self.cma_report.RequestId From admin.py: class ReportAdmin(ReverseModelAdmin): report = None if ReportsModel.cdr_report is not None: report = 'cdr_report' elif ReportsModel.cme_report is not None: report = 'cme_report' elif ReportsModel.cps_report is not None: report = 'cps_report' elif ReportsModel.cma_report is not None: report = 'cma_report' search_fields = ['name'] inline_reverse = [report] # inline_reverse = ['cdr_report', 'cme_report', # 'cps_report', 'cma_report'] inline_type = 'stacked' admin.site.register(ReportsModel, ReportAdmin) But in admin, it didn't work, it only shows the correct value for cdr_report not for others. I want to display only the report which is not None. How can I achieve that? -
Django: how to increase object value
I'm trying to implement a simple 'like' button, however, the value of the object is not changing. I have only a week of experience with django, any help is appreciated! model> class Mainnews(models.Model): author = models.ForeignKey(Author, on_delete=models.DO_NOTHING, default= True) title = models.CharField(max_length=200) description = models.TextField() image = models.ImageField(upload_to = 'photos/%Y/%m/%d/') is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) views_counter = models.IntegerField(default=0) likes = models.IntegerField(default=0) def __str__(self): return self.title html> <form action = "{% url 'like' %}" method = "POST"> {% csrf_token %} <input name = 'like' type = 'number'> <button type ='submit'>submit</button> </form> view> def like(request): if request.method == 'POST': likes = request.POST['like'] likes += 1 theLike= Mainnews.likes(likes = likes) theLike.save() url> on like redirect to homepage path('', like, name = 'like'),