Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework nested serializer gives attribute error
I am trying to setup a nested serializer below I've posted the models and serializer. why am I getting the below error ? Got AttributeError when attempting to get a value for field `balance_sheet` on serializer `StockSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Stock` instance. Original exception text was: 'Stock' object has no attribute 'balance_sheet'. serializers.py class StockSerializer(serializers.ModelSerializer): income_statement = IncomeStatementSerializer(many=True) balance_sheet = BalanceSheetSerializer(many=True) cashflows_statement = CashflowsStatementSerializer(many=True) def create(self, validated_data): temp_income_statement_data = validated_data.pop("income_statement") temp_balance_sheet_data = validated_data.pop("balance_sheet") temp_cashflows_statement_data = validated_data.pop("cashflows_statement") new_stock = Stock.objects.create(**validated_data) for i in temp_income_statement_data: IncomeStatement.objects.create(**i, ticker=new_stock) for x in temp_balance_sheet_data: BalanceSheet.objects.create(**x, ticker=new_stock) for y in temp_cashflows_statement_data: CashflowsStatement.objects.create(**y, ticker=new_stock) return new_stock IncomeStatementSerializer, BalanceSheetSerializer and CashflowsStatementSerializer are all typical ModelSerializer's models.py class Stock(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) ticker = models.CharField(max_length=10, unique=True, primary_key=True) slug = models.SlugField(default="", editable=False) def save(self, *args, **kwargs): value = self.ticker self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) def __str__(self): return self.ticker class Meta: verbose_name = "stock" verbose_name_plural = "stocks" ordering = ["ticker"] IncomeStatement, BalanceSheet and CashflowsStatement are all typical models.Model with a ForeignKey relationship to Stock views.py class StockList(generics.ListCreateAPIView): queryset = Stock.objects.all() serializer_class = StockSerializer lookup_field = "slug" -
Redirect problems with django form in a modal
I am trying to implement a form in a modal which is focused on modifying a comment in a post, the way i did it everything works, the problem is when I click on the submit button it sends me to the html in which I have the modal and there I edit the comment. when I try to delete the url in the action form that takes me to the second page of my form it throws the error "local variable 'form' referenced before assign", also if I put for example in form action the url of the login sends me towards There but the comment is not updated or edited. My idea is simply that when I submitting the form, the modal closes, and the page where the modal was opened from the beginning, reload or simply the comment already edited appears. if you need more information I can add it. views.py @need_analyst_role def comment_modify(request, comment_id): if 'comment_edit' in request.POST: form_comment = FormComment(request.POST) if form_comment.is_valid(): comment_text = form_comment.cleaned_data['text'] comment = ModelRiskTracking.objects.get(id=comment_id) comment.comment = comment_text print(comment.comment) comment.save() else: messages.error(request, 'Error!', extra_tags="danger") context = {} context['comment'] = ModelRiskTracking.objects.get(id=comment_id) return render(request, 'analyst_pages/comment_edit.html', context = context) modal.html <div class="modal-dialog modal-dialog-centered modal-lg" role="document"> … -
The current path, {% url 'requirement_post_vote' post_id=page_obj.pk vote_now='like' %}, didn't match any of these
I am learning Django and am currently trying to use a like and dislike buttons in my blog. I get the error "The current path, {% url 'requirement_post_vote' post_id=page_obj.pk vote_now='like' %}, didn't match any of these." urls.py from django.urls import path from .views import ( Requirement, UpdatePost ) from . import views urlpatterns = [ path('', Requirement.as_view(), name='flash-home'), path('requirement/<int:post_id>/<str:vote_now>', UpdatePost.as_view(), name='requirement_post_vote'), ] here is html code {% if request.user in page_obj.dis_likes.users.all %} <!-- already liked--> <a href="{% url 'requirement_post_vote' post_id=page_obj.pk vote_now='like' %}"> <i data-toggle="tooltip" data-placement="bottom" title="i dislike this" class="fa fa-thumbs-down pr-2"> <span>{{ page_obj.get_total_dis_likes }}</span> </i> </a> {% else %} <!-- not liked--> <a href="{% url 'requirement_post_vote' post_id=page_obj.pk vote_now='dis_like' %}"> <i data-toggle="tooltip" data-placement="bottom" title="i dislike this" class="fa fa-thumbs-down pr-2"> <span>{% if page_obj.get_total_dis_likes %}{{page_obj.get_total_dis_likes}} {% else %} 0 {% endif %} </span> </i> </a> {% endif %} please help am real have a big trouble because my day wasn't end well -
Retrieve an html code from database and store it in a javascript variable (with no escaping)
An html code is stored in database; for example: <p>django is <strong>good</strong></p> In the template when I want to store it in a javascript variable, it store with escaped mode and the javascript "unescape" function is not helpful. -
Django URL order
iam stuck again I hope I will get useful help this time too. Iam trying to run the app but it gives me URL configuration error something like this: Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order: admin/ products/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I see a similar query in this platform but I couldn't find my answer Iam using Django version 2.1 My code in pyshop.urls is: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('products/', include('products.urls')) ] -
Django: How to make custom ordering for this Django queryset?
I have a model called 'Format', and another called 'Department' in my Django project. I also have this model: class DepartmentFormat(models.Model): department = models.ForeignKey(Department, on_delete=models.CASCADE) format = models.ForeignKey(Format, on_delete=models.CASCADE) status = models.ForeignKey(FormatStatus, on_delete=models.CASCADE, null=True, default=None) This object may or may not exist for every specific Format object. Not always will there be a DepartmentFormat object which has assigned every existing Format. The FormatStatus class looks like this: class FormatStatus(models.Model): STATUS_CHOICES = ( (0, 'Received'), (1, 'Accepted'), (2, 'Rejected') ) status = models.IntegerField(choices=STATUS_CHOICES, default=0) description = models.TextField(max_length=80, blank=True, null=True) date = models.DateTimeField(auto_now=True) I want to order all of the Format objects like this: First, all Format objects for which there isn't a DepartmentFormat object that has them, or all those who do have one, and the status in FormatStatus is 0. The order here doesn't matter. Finally, those Format objects for which there is a DepartmentFormat object whose status is either 1 or 2. I don't know how to do this. I know the department I'm searching, but not which DepartmentFormat objects exist for each Format object. I tried this in my view: def get_queryset(self, **kwargs): qs = super(ReviewedTableView, self).get_queryset() department = self.request.user.department dpt_fmt = DepartmentFormat.objects.filter(department=department) format_ids = [] for obj … -
How to filter using gte of a attribute of corresponding model object in django
bar_1 = models.IntegerField() bar_2 = models.IntegerField() Filter all values where bar_1<=bar_2 -
How can I get the authorized user on vaild?
How can I get the authorized user on vaild? It all happens in the forms.py file. I need to verify an authorized user with his mail. self.request.user - not working. I get this error: object has no attribute 'request' def clean_email(self): email = self.cleaned_data["email"] try: User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError("error") -
Form is not saving
Hello I have form and I can fill it but when I submit it nothing happens, I can add or edit the form in the admin panel but on the normal page as I said nothing happens. Can you please help me. this is my template where you at the bottom see my form. {% extends "base.html" %} {%block content%} {% load crispy_forms_tags %} <div class="container"> {% for i in distribution%} <div class='img1'> <img name="pic" src="{{ i.distribution.url }}"> <p style="text-align:center;">{{i.lecture}} | {{i.semester}}</p> </div> {% endfor %} </div> <div class="container"> <table class="table table-hover results"> <thead> <tr> <th >Kullanıcı</th> <th >Yorum</th> </tr> </thead> <tbody> {% for j in commentmodel_list%} <tr> <th>{{j.author}}</th> <th>{{j.comment}}</th> </tr> {% endfor %} </tbody> </table> </div> <div class="container"> <button style="margin-bottom:10px;float:right;"type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Yorum Ekle</button> </div> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Yorum</h5> </div> <div class="modal-body"> <form method="post" style="margin-top: 1.3em;"> {% csrf_token %} {{ form|crispy }} <div class="modal-footer"> <button type="submit" class="btn btn-primary">Submit</button> <button type="submit" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </form> </div> </div> </div> </div> this is my view class LecturerDistribution(FormMixin, generic.DetailView): model = Lecturer template_name = 'lecturer.html' context_object_name = 'post' form_class = CommentForm def get_context_data(self, **kwargs): context = … -
How can I install Ubuntu production server in Godaddy hosting server
So I tried my best to create a full-stack app with Django & React and I built it. And I did want to learn how to deploy the application to Linux/Ubuntu server and wanted to fallow this article. Godaddy provides a Cpanel, not a Ubuntu server. So I was wondering how can I install the Ubuntu production server in Godaddy hosting server. I don't have any experience with Linux or Cpanel or any hosting service (it is my first time buying the domain and hosting server) it would be nice to have a detailed answer. I am open to any kind of advice. Thank you for reading. -
How to write a funtion that will check for the empty room in hotel in django
I am building a Hotel management system and I have writing a check_availability function that will check if a room is not empty depending of the category required by the client but it turns out that the database is ignore by the function cause it just care about the existing one not the added one. here is the code: from django.db import models from django.contrib.auth.models import User class RoomCategory(models.Model): name = models.CharField(max_length=59) price = models.IntegerField() beds = models.PositiveIntegerField() capacity = models.PositiveIntegerField() size = models.CharField(max_length=59) def __str__(self): return self.name class Room(models.Model): room_number = models.CharField(max_length=60) room_category = models.ForeignKey(RoomCategory, on_delete=models.CASCADE) def __str__(self): return f"The room {self.room_number} {self.room_category} has a maximum of {self.room_category.capacity} person and cost {self.room_category.price}/night " class Booking(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) check_in = models.DateTimeField() check_out = models.DateTimeField() def __str__(self): return f"{self.customer} has booked for a {self.room} room from {self.check_in} to {self.check_out}" from django.shortcuts import render from .forms import BookingForm from .models import Booking, RoomCategory, Room from django.views.generic import FormView from Hotel.Availabililty.Available import check_availability from django.http import HttpResponse # Create your views here. class BookingFormview(FormView): form_class = BookingForm template_name = 'Hotel/bookingformview.html' def form_valid(self, form): data = form.cleaned_data roomlist = Room.objects.filter(room_category__name=data['room']) for room in roomlist: booked_room = Booking.objects.filter(room__room_number=room.room_number) available_rooms … -
Define variable on django project startup
I am trying to make one variables.py (reusbale module that can be used by other py files in the app) in my django project which should be set only once when the runserver command is executed. ex. reading a csv file using pd.read_csv once at the startup of the project so that every time an API call is made, variable should not load csv file instead it should already have the dataframe value already in the variable. How can this be achieved? Python version - 3.6 Django - 2.1 -
How do I see the value of a field belonging to my model with the method I defined in restapi?
I can access the foreground in my model with "Advertising.frontal.get". But how can I see this in restapi. The value of the frontal area in restapi appears numerical. Because of the way I describe this area. This is normal. But I know the method I should use when viewing (this method: Advertise.frontal.get). How do I view it in restapi with this method. ## Serializer.py ## class AdvertiseMainSerializer(ModelSerializer): class Meta: model = Advertise fields = '__all__' ## views.py## class advertise(ListAPIView): serializer_class = AdvertiseMainSerializer queryset = Advertise.objects.all() ## model.py## class Advertise(models.Model): owner = models.ForeignKey(to="user.User", on_delete=models.CASCADE, null=True) title = models.CharField(max_length=100, verbose_name="ilan başlığı") frontal = models.ManyToManyField(to="advertise.Frontal") -
How to integrate a typeform like experience for CRUD website
I'm building a web app and I want to have a typeform like flow to create and edit entities on my website. As far as I know, I can't use typeform itself, as they don't allow for edits. Is there a tool/snippet/package to create good looking forms, without refresh between pages, include animations, skip logic etc.? I'm using django for my website. Thanks! -
Can't delete post Django delete_post() missing 1 required positional argument: 'post_slug'
When i hit on my Delete button i get delete_post() missing 1 required positional argument: 'post_slug' I made a DeleteForm too, but im really not understanding how to delete things, i was trying to make the same that i did to edit_post. views.py: def edit_post(request, post_slug): """Edit an existing entry.""" post = get_object_or_404(Post, slug=post_slug) context = {} form = EditPostForm(request.POST or None, instance=post) if form.is_valid(): form.save() return HttpResponseRedirect(post.get_absolute_url()) context["form"] = form return render(request, 'blog/post/edit_post.html', context) def delete_post(request, post_slug): post = get_object_or_404(Post, slug=post_slug) if request.method == 'POST': post.delete() context = {'post': post} return render(request, 'blog/post/delete_post.html', context) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.post_list, name='post_list'), path('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'), path('new_post/', views.new_post, name='new_post'), path('<slug:post_slug>/', views.post_detail, name='post_detail'), path('<slug:post_slug>/share/', views.post_share, name='post_share'), path('edit_post/<slug:post_slug>/', views.edit_post, name='edit_post'), path('delete_post/<slug:post_slug/', views.delete_post, name='delete_post'), ] delete_post.html {% extends 'blog/base.html' %} {% block title %}{{ post.title }}{% endblock %} {% block content %} <div class="main"> <!-- Create a Form --> <form method="POST" action="{% url 'blog:delete_post' post.slug %}" class="form"> {% csrf_token %} Are you want to delete this item ? <input type="submit" value="Yes" /> <a href="/">Cancel </a> </form> </div> {% endblock content %} forms.py from django import forms from .models import Comment, Post class EmailPostForm(forms.Form): … -
Django rest-auth PUT method returning JSON Unexpected token
I've been trying to try to do this for a couple of days for now. I am trying to update the user's data through put method in Django using rest framework. However, I've been receiving this error message in the console. This is the fetch function that is used to send the data to the backend. As it's shown, I'm even trying to compare it to other fetch methods and I think nothing is wrong with the body of the fetch. Below are my codes used to update the data. views.py serializers.py urls.py -
Storing the data into SQLiteStudio database when any data is entered in front end
How to store data into database using Django framework and python. -
How to use Django to make a dependent dropdown list from a database I would like to write to as well
I have seen many tutorials of how to pull information using a foreignKey in the models for a dropdown list, but I'd like to keep everything on the same table if possible. First I use AddAreaForm to add the Area, then AddMachineForm, using the Area(in a dropdown) and Machine being typed in. As detailed below this gets me to the point where I have Area and Machine drop downs in the AddTasksForm, but I'd like to make the Machine dropbox dependent on the Area using the SOME VARIABLE(Line 5 in Forms Codeblock and it is defined as area_id on line 4 in Views Codeblock). MODEL class Tasks(models.Model): area = models.CharField(max_length=500) machine = models.CharField(max_length=500, null=True, blank=True) task = models.CharField(max_length=500, null=True, blank=True) interval = models.IntegerField(null=True, blank=True) def _str_(self): return self.area FORMS #Call's the area and machine from the database, lists all unique choices as i'll be adding only to existing data-points AREA_CHOICES_UNSORTED = list(Tasks.objects.values_list('area', flat=True)) AREA_CHOICES = list(dict.fromkeys(zip(AREA_CHOICES_UNSORTED[0::1], AREA_CHOICES_UNSORTED[0::1]))) MACHINE_CHOICES_UNSORTED = list(Tasks.objects.values_list('machine', flat=True).filter(area='%s'% '**SOME VARIABLE**')) MACHINE_CHOICES = list(dict.fromkeys(zip(MACHINE_CHOICES_UNSORTED[0::1], MACHINE_CHOICES_UNSORTED[0::1]))) class AddAreaForm(forms.ModelForm): class Meta: model = Tasks fields =( 'area', ) class AddMachineForm(forms.ModelForm): area = forms.CharField(widget=forms.Select(choices=AREA_CHOICES)) class Meta: model = Tasks fields =( 'area', 'machine', ) class AddTasksForm(forms.ModelForm): area = forms.CharField(widget=forms.Select(choices=AREA_CHOICES)) machine = … -
How can I prepopulate a form in class based views with url variable <str:>
As the question says,I'm trying to prepopulate a form with a url varible, by this I mean that the form fills with the variable that is in the url. I was trying to use the get initial function, but it's not working, so I will share my code so you can see what's going on and what mistakes I'm doing views.py class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'app1/createpost.html' def get_initial(self, **kwargs): #Returns the initial data to use for forms on this view. initial = super().get_initial() initial['stock'] = self.kwargs.get('sym') return initial def form_valid(self, form, sym): form.instance.author = self.request.user return super().form_valid(form) models.py class StockNames(models.Model): name = models.CharField(max_length=255) symbol = models.CharField(max_length=255) def __str__(self): return self.symbol class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank = True, upload_to = 'images/') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank = True, null = True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name = 'blog_posts') stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE) def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('app1:article-detail', args=(self.id,)) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = … -
Can we use django as a front end?
I Have Confusion for Django as it is mostly use for back end support but can we use it as front end also? I have to go for something else for front end or only html and CSS is fine. -
Should extra fields be an extension of User or Profile in Django?
I am beginner in Django and currently practising by building a calorie counter website where users can register. When they register, I want to ask them for some mandatory fields such as their goal weight, activity level, current weight, current height, etc. Do I add them to a class called Profile(models.Model) such as : class Profile(models.Model): user = models.OneToOne(User, on_delete=models.CASCADE) bio = models.CharField(max_length=500) image = models.ImageField(default="", upload_to="profile_pics") weight = models.FloatField(min_value=1.0) #metric tbd height_metric = models.FloatField(min_value=1.0) #in cm goal_weight = models.FloatField(min_value=1.0) or should I create a custom User model that extends the default User model provided by Django? (or a third option) Thanks -
How to add an extra parameter to a Django object when creating it?
I have a Django model that has many parameters, amongst which is one called 'system' which is a reference to an object of type 'System'. class Format(models.Model): system = models.ForeignKey(System, on_delete=models.SET_NULL, null=True) petition_date = models.DateField(auto_now=True) resolution_date = models.DateField(null=True, default=None) ... other fields ... The system may be null, but I'd want this field to be the same as the user that creates the Format object. My user object is like this: class CustomUser(AbstractUser): current_system = models.ForeignKey(System, on_delete=models.SET_NULL, null=True, default=None) department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, default=None) I have a form which successfully creates the Format objects. However, I'd like to know a way to do something like this in my CreateView: class FormatCreateView(LoginRequiredMixin, CreateView): """ -----------------------Vista de crear nuevos articulos-------------------------- """ template_name = 'format_form.html' model = Format success_url = reverse_lazy("formats:formats") form_class = FormatUpdateForm def post(self, request, *args, **kwargs): form = FormatUpdateForm(request.POST) if form.is_valid(): user = User.objects.get(id=self.request.user.id) format = self.object # I'm pretty sure this is wrong and doesn't get the Format object that was just created format.system = user.current_system format.save(update_fields=['system']) return HttpResponseRedirect(reverse('formats:formats')) This, however, doesn't work. Any suggestions would be appreciated. -
How to sort models into categories django
I have an article model and I want to make that so when the user clicks he has drop-down menu so he chooses a category and then it registers it in this category in the database. -
Foreign key values do not appear in related rendered table using accessor (django-tables2)
I am trying to display a table with a Tool model as well as a publication DOI model that has the tool as a foreign key. Django (django-tables2) is just not having it and displays - instead of actual values. There are no shortages of examples (Django-tables2: How to use accessor to bring in foreign columns?, Django Tables 2 Field Accessor backward relationship, Accessing related models with django-tables2) and it seems simple, but I cannot get it to work. Here is a bit of code... models.py class DOI(models.Model): """Model representing a doi model.""" doi = models.URLField(verbose_name='DOI', max_length=300, default='', blank=True) tool = models.ForeignKey('Tool', on_delete=models.SET_NULL, null=True) ... class Tool(models.Model): tool_name = models.CharField(verbose_name='Package Name', max_length=200) release_date = models.DateField(verbose_name='Release Date', null=True, blank=False) ... tables.py class ToolTable(tables.Table): tool_name = tables.Column(linkify=True) doi = tables.Column(accessor='doi.doi', linkify=True) id = tables.Column(linkify=True, orderable=False) ... Any assistance is greatly appreciated. -
Django save image locally as well as s3
An image file is being uploaded from a POST REST API call and I want to do the following save the file locally also save it in an s3 bucket after saving the file, get the URL of the saved object How can I do this in Django?