Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error while exporting excel file using Django and xlwt
Working with the xlwt library for exporting Excel docs using the Django framework, the following problem appeared: invalid literal for int() with base 10: 'Name of product' I tried to use different conversions in data types, but it didn't help. I would like to know how to solve this problem, thank you for any advice. models.py: class Product(models.Model): name = models.CharField(max_length=100, null=True) quantity = models.PositiveIntegerField(null=True) category = models.CharField(max_length=50, choices=CATEGORY, null=True) def __str__(self): return f'{self.name}' views.py: def export_excel(request): response=HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment: filename=Expenses' + \ str(datetime.datetime.now())+'.xls' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Expenses') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns= ['Name of product', 'Category', 'Quantity'] for col_num in range(len(columns)): ws.write(row_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = Product.objects.filter(owner=request.user).values_list( 'name', 'quantity', 'category') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, str(row[col_num]), font_style) wb.save(response) return response -
How to update image fields using Django forms
I am attempting to create a blogging application and in it I have 2 forms, one for editing pre-existing posts, and the other for creating them. However, I am unable to get updated images, when the edit form is submitted. All textual data goes through... Models.py: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_posts') short_description = models.TextField() updated_on = models.DateTimeField(auto_now=True) content = RichTextUploadingField() created_on = models.DateTimeField(auto_now=True) status = models.IntegerField(choices=Status, default=0) cover_image = models.ImageField(upload_to = 'coverimages', null =True, blank = True) captioned_image = models.ImageField(upload_to = 'captionedimages', null=True, blank = True) caption = models.CharField(max_length=300) featured = models.IntegerField(choices=Featured, default=1) category = models.ForeignKey(PostCategory, on_delete=models.CASCADE, null=True, blank=True) embedded_code = models.TextField(blank=True, null=True, default='null') tags = models.ManyToManyField(Tag, blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title forms.py: class EditForm(forms.Form): title = forms.CharField(max_length=100, label='Post Title') short_description = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":100})) content = forms.CharField(widget=CKEditorUploadingWidget()) status = forms.NullBooleanField(label='Ready to Publish?') image = forms.ImageField(label='Select a cover image:', required=False) captioned_image = forms.ImageField(label='Select a captionable image:', required=False) caption = forms.CharField(max_length=200) try: category = forms.ModelChoiceField(queryset=PostCategory.objects.all()) except: category = forms.ChoiceField(choices= ('default')) embed = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":100})) tags = forms.CharField(widget=forms.Textarea(attrs = {"rows":1, "cols":150})) editpost.html: {% load widget_tweaks %} <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.media }} <legend>Edit … -
How to save updated text input in django?
I'm new to django and want to create a to do site. I currently am able to add a new task and show all the tasks in one page (the tasks are in text inputs). However, I am unable to figure out how to change and save the text input. I would like to be able to change the text in the text input and somehow save it without having to go to another page (ex: press an edit button that goes to a new url to edit and save the text). Views.py class TaskCreate(CreateView): model = Task fields = ['user', 'title'] template_name = 'todo_list/task_list.html' success_url = reverse_lazy('tasks') def get_context_data(self, **kwargs): list = super(TaskCreate, self).get_context_data(**kwargs) list["tasks"] = self.model.objects.all() return list task_list.html <html> <h1>Today</h1> <form method="POST"> {% csrf_token %} {{form.as_p}} <input type='submit'/> </form> <table> {% for task in tasks %} <tr> <td> <input type="text" name="task-value" value="{{task.title}}"> </td> </tr> {% empty %} <h3>No tasks for today</h3> {% endfor %} </table> </html> Models.py class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['complete'] -
How to make a verification in an argument passed to a periodic task in django celery beat
I have a periodic task in django celery beat, which needs an argument (an IP address) to be given in the django admin. What I need to do is to check if that argument is correct once I save the periodic task. If it is, save it normally. If it isn't raise some kind of error. I tried to import the PeriodicTask model and edit the save function like this (I did this in celery.py): from django_celery_beat.models import PeriodicTask def save(self, *args, **kwargs): #code to check if the arg is correct #if incorrect, raise error else super(PeriodicTask, self).save(*args, **kwargs) But that didn't work. Any ideas? -
Why should i use separate table for maintain roles?
Am creating a project which has multiple roles, so initially i thought of adding a Colum named "role" in user table and maintain the roles. But later on i got a requirement like to add staffs under each role. Lets say Agent & Institution are two primary roles. And agent and Institution may contain one or more staffs under them and those staff has many categories like admin staff or sales staff etc. ( this categories will be maintained by groups & permissions of Django ). So to differentiate the categories of the staff i thought of adding extra roles like "admin_staff" or "sales_staff" but i think its not scalable ? And so again i thought of creating a roles table to maintain this. Am bit confused on how to handle this situation I have two apprroaches : Approach 1 : Now my user table has these, Class User: name, email, ..... role And thought of adding a extra field named: "role_name" and make "role" as numeric and then keep track the categories of staff using the role_name example: role == 1 // agent and role_name == "admin_staff" And my second approach: create a new role table and have extra … -
Django: NOT NULL constraint failed: appname_post.user_id
I have the following django rest framework serializer and view for a model Post, and the models defined for the app are as following. Now I wanted to test the API, so tried to "create" a new post from the API page, but then I got an error IntegrityError at /api/posts/ NOT NULL constraint failed: appname_post.user_id. So then I tried to debug and checked its request.data value, it says it only has title and content but not user_id, as I could expect from the error above. But now I have no idea how to tell the API automatically relate the user_id field to request.user.id. Isn't not enough to just add the user_id = serializers.ReadOnlyField(source='user.id') line? I could do "retrieve", "update", "patch" etc but just cannot "post" (create). Thanks for your help. serializer and view class DevPerm(permissions.BasePermission): def has_object_permission(self, request, view, obj): return True def has_permission(self, request, view): return True class PostSerializer(serializers.HyperlinkedModelSerializer): user_id = serializers.ReadOnlyField(source='user.id') class Meta: model = Post fields = ('url', 'id', 'title', 'content', 'created_at', 'voters', 'comments', 'user_id', ) read_only_fields = ( 'id', 'created_at', "voters", "comments", # "user_id", ) class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticated, DevPerm,] models class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts', … -
Saving the time in Django and running tasks later
I have a Django website where I store some data and will have to have certain tasks performed at a specific time. I've done this before with model that looked like this: start_at = models.DateTimeField(...) and when user created an object the current time would be deducted from the start_at and sent off to django background-tasks with schedule being the difference in seconds (done with datetime and pytz because of timezones). Now I'm curious about having something like start_at = models.FloatField(...) And here I would store the the value that I get from user (turned into unix time) and schedule it pretty much the same just without worrying about timezones and just doing the start_at - current_time for schedule. Now, in my opinion this could help me with displaying the different timezones to different users easier and the whole scheduling part is much simpler, but I'm not sure how practical it is, if there are some limitations or something that I'm not familiar with. The second this would be scheduling it with something like django background-tasks which I'm familiar with or maybe Celery but I don't know too much about it and I'm not sure how the whole scheduling part … -
Why does my database lose recent data ? Django application deployed on Heroku
I have deployed a Django web application on Heroku and it has the data I have added in the development phase, still when I add new data, the website holds the data temporarily for some time ( I don't know how long ), and then the website resets to the state in which it was first deployed. I don't understand why this is happening and would appreciate the help. Here is the website if you want to try it for yourself https://help-er2.herokuapp.com/ As I said if you make changes ( you have to register first ) they will hold and be stored for some unknown time to me and after that time they will disappear. Thanks for your time and effort. -
creation time for django model instance
how to know when an instance of django model has been created inside sqlite? i tried many methods but i couldnt know or get when my db instance was created from datetime import datetime, timedelta time_threshold = datetime.now() - timedelta(hours=4) results = x.objects.filter(created__lt=time_threshold) i even tried this code but i got an error as below: Traceback (most recent call last): File "", line 1, in File "C:\Users\momeir\Anaconda3\envs\myEnv\lib\site-packages\django\db\models\query.py", line 941, in filter return self._filter_or_exclude(False, args, kwargs) File "C:\Users\momeir\Anaconda3\envs\myEnv\lib\site-packages\django\db\models\query.py", line 961, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "C:\Users\momeir\Anaconda3\envs\myEnv\lib\site-packages\django\db\models\query.py", line 968, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\momeir\Anaconda3\envs\myEnv\lib\site-packages\django\db\models\sql\query.py", line 1393, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\momeir\Anaconda3\envs\myEnv\lib\site-packages\django\db\models\sql\query.py", line 1412, in _add_q child_clause, needed_inner = self.build_filter( File "C:\Users\momeir\Anaconda3\envs\myEnv\lib\site-packages\django\db\models\sql\query.py", line 1286, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "C:\Users\momeir\Anaconda3\envs\myEnv\lib\site-packages\django\db\models\sql\query.py", line 1112, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "C:\Users\momeir\Anaconda3\envs\myEnv\lib\site-packages\django\db\models\sql\query.py", line 1539, in names_to_path raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'created' into field. Choices are: contact_name, email_name, id, message, subject -
Django: how to pass username to PasswordResetDoneView
PasswordResetView: The user enters his email to reset password. PasswordResetDoneView: The user gets a message "Email sent" I want to let the user what email he entered in the PasswordResetView. How can I pass the email entered (which is the username in my case) to the PasswordResetDoneView html template? path('reset-password/', auth_views.PasswordResetView.as_view(template_name='password_reset/password_reset.html', email_template_name='password_reset/password_reset_email.html', subject_template_name="password_reset/password_reset_asunto.txt"), name='password_reset'), path('reset-password-done', auth_views.PasswordResetDoneView.as_view( template_name='password_reset/password_reset_done.html'), name='password_reset_done'), -
App deployed on Heroku doesn't show data from MySql DB
On development, I set up a clever cloud MySQL database to my Django project with these settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db-name', 'HOST': 'db-name-mysql.services.clever-cloud.com', 'PORT': 3306, 'PASSWORD': 'password', 'USER': 'user' } } It worked normally, so I created some data on this DB for testing. I deployed this app on Heroku, and when I successfully deploy it, I realized that the data shown on Heroku, is not the same as my clever cloud DB. I don't know if Heroku is using another database or why is not using my database. -
Trying to add variant product to cart js Django
Trying to add variant product to cart js Django I just don't really know how to add it to my cart in js and get it in my utils.py the code works well before I added variants to my models.py I am really torn how to make it work what is the right idea to add it fo function addCookieItem in cart.js and render it in the utils.py models.py class Product(models.Model): VARIANTS_CHOICES = ( ('None', 'None'), ('Size', 'Size'), ('Color', 'Color'), ('Size-Color', 'Size-Color'), ) category = models.ForeignKey("Category", on_delete=models.SET_NULL, blank=True, null=True) title = models.CharField(max_length=300) description = models.TextField() image = models.ImageField(default="") price = models.FloatField(default=0) slug = models.CharField(max_length=300) variant = models.CharField(choices=VARIANTS_CHOICES, max_length=70, blank=True, null=True) def __str__(self): return self.title def imageURL(self): try: url = self.image.url except: url = "" return url def image_tag(self): if self.image.url is not None: return mark_safe('<img src="{}" height="50" />'.format(self.image.url)) else: return "" class Images(models.Model): product = models.ForeignKey("Product", on_delete=models.SET_NULL, blank=True, null=True) title = models.CharField(max_length=300) image = models.ImageField(default="") def __str__(self): return self.title def imageURL(self): try: url = self.image.url except: url = "" return url class Color(models.Model): name = models.CharField(max_length=500) code = models.CharField(max_length=300, blank=True, null=True) def __str__(self): return self.name def color_tag(self): if self.code is not None: return mark_safe('<p style="background-color:{}" > Color </p>'.format(self.code)) else: return … -
Django - images uploaded by user does not display and shows 404 when Debug = False
I am developing a Django and using ImageFiled attributes into models that I need to display later. When I run the website in dev (DEBUG = True) it works, but when I change it to False (Production) uplaoded images do not display anymore and the console shows: "GET HTTP/1.1" 200 As I saw in other open questionsI tried to add in settings: MEDIA_ROOT = os.path.join(BASE_DIR, 'images') and in urls urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But this doesn't work and even creates the same issue as in production. settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'gallery.apps.GalleryConfig', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DEBUG = False if not DEBUG: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_URL = 'static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) Update: The documentation says: URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be … -
How to display related information in two classes in django admin?
I'm working in django admin with two classes: Conference and Team. I created objects for both of them and I want them to be related. I created Conference North and South and I want to display the name of the teams that belong to each conference. But I also want to go to Teams and have a list of them and display to which conference they belong. Something like this (all in django admin. I'm not working with views): "App": Conferences North (and in another column "Team 1, Team 2") South ("Team 3", "Team 4") Teams Team 1 (North) Team 2 (North) Team 3 (South) Team 4 (South) I know I could set a ForeignKey to both of them but the goal is to create the Conference, add the teams and then on Teams having de conference display automatically. So that if I change something in one of the classes, it changes all automatically. Any idea how to do this? Thanks -
Django Rest Framework: QuerySet filtering not working as expected
I am using Django 3.2 and Django Rest Framework for an API. I am having difficulty getting it to work the way I would expect. I have a position table with sample data similar to this: [ { id: 1, position_date: '2022-01-01', symbol: 'AAPL', shares: 100 }, { id: 2, position_date: '2022-01-01', symbol: 'TSLA', shares: 100 }, { id: 3, position_date: '2022-01-01', symbol: 'GOOG', shares: 100 }, { id: 4, position_date: '2022-01-02', symbol: 'AAPL', shares: 200 }, { id: 5, position_date: '2022-01-02', symbol: 'TSLA', shares: 200 }, { id: 6, position_date: '2022-01-02', symbol: 'GOOG', shares: 200 }, { id: 7, position_date: '2022-01-05', symbol: 'AAPL', shares: 300 }, { id: 8, position_date: '2022-01-05', symbol: 'TSLA', shares: 300 }, { id: 9, position_date: '2022-01-05', symbol: 'GOOG', shares: 300 }, ] This data contains stock positions on a certain date. This daily snapshot position info is created only on weekdays/days the market is open, so there are gaps in the dates for weekends/market holidays. I want to query positions by position_date /api/v1/positions?position_date=<YYYY-MM-DD>, with the caveat that when you pass in a date that is not directly associated with a position, then you get the positions for the greatest date that is less than … -
Cannot Fill out form HTML
So I have a login screen that I have built, and I am using 3JS for the background animation. As of right now, I cannot actually click on the form to fill out the fields. When I hover my mouse over the Username input field, I can see that my mouse goes to the text input mode, but I cannot click on the element. Below is the HTML for this: {% extends "home/base.html" %} {% block title %} Login Page {% endblock title%} {% block content %} <main> <canvas id="bg" style="z-index: -1 !important; pointer-events: none !important"> </canvas> <div id='loginform' class="container-fluid fixed-top"> <div class="form-content my-3 p-3" style="z-index: 400"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-5"> <div class="card shadow-lg border-0 rounded-lg mt-0 mb-3"> <div class="card-header justify-content-center"> <h3 class="font-weight-light my-1 text-center">Sign In</h3> </div> {% if form.errors %} <div class="alert alert-danger alert-dismissible" role="alert"> <div id="form_errors"> {% for key, value in form.errors.items %} <strong>{{ value }}</strong> {% endfor %} </div> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %} <div class="card-body"> <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group"> <a href="{% url 'social:begin' 'github' %}" class="btn btn-link btn-lg active btn-block">Sign in with GitHub</a> <a href="{% url 'social:begin' 'google-oauth2' … -
How to test django apps when my authorization is remote?
Currently I am using some tests like this: @pytest.mark.django_db(databases=["default"]) def test_list_boards(api_client): baker.make(Board) baker.make(Board, name="new") url = reverse("v1:boards-list") response = api_client().get(url) assert response.status_code == 200 assert len(json.loads(response.content)) == 2 edit: since I'm not using django User, this is my custom User: class User: def __init__(self, token, name, user_id, email, is_mega_user, is_authenticated): self.token = token self.name = name self.user_id = user_id self.email = email self.is_mega_user = is_mega_user self.is_authenticated = is_authenticated But now, I've added new custom authorization and permission classes in my application, so currently my tests are failling because of it. And I was thiking: What about when I dont have internet connection? I will not be able to test? How can I handle it? -
Django: Why is the Image Field not working
Good day, I am testing some stuff with Django image Fields and the user model. The point is simply that any user can upload and update a profile picture. But when I select a picture and press upload, I get the message 'This field is required. So it's as if I haven't selected anything. \\photo.html <form method="POST"> {% csrf_token %} {{ form }} <button type="submit">Upload</button> </form> \\views.py def photo_view(request): try: profile = request.user.userimage except UserImage.DoesNotExist: profile = UserImage(user=request.user) if request.method == 'POST': form = UserImageForm(request.POST, instance=profile) if form.is_valid(): form.save() return redirect('/dashboard/user/profile') else: form = UserImageForm(instance=profile) return render(request, 'photo.html', {'form': form}) \models.py class UserImage(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE) photo = models.ImageField( upload_to='images/', height_field=None, width_field=None, max_length=100) def __str__(self): return str(self.user) \\settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I tried it with this one https://www.geeksforgeeks.org/imagefield-django-models/ Do someone know a solution? Or should I even use the ImageField when working with images? Thank you very much! :-) -
How do I store and retrieve user-defined rules in Django
I'm working on a requisition system using Django, and I want to implement a feature that allows the admin to set up rules. Instead of having to add a new feature for the tiniest of works, I want the admin to just add that as a rule, something similar to what Gmail does with filters. Basically a statement, condition, and action kinda pair. For example: FOR statement (all users, userId is less than, username starts with, etc.) WHERE condition (userID is equal to, date is less than, username starts with, etc.) PERFORM an action (delete user, assign user to new group, etc.) I am struggling with the logic for saving and retrieving this. Seeing that the statement, condition, and action pair will always change, how do I store these rules to DB and test against the rules while retrieving? Thanks -
When i go to add in the database on the admin panel, there is no input for username
Everytime i enter the admin panel and add a new account, each field allows me to enter a input except for the userID Model from asyncio import FastChildWatcher import email from pyexpat import model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class userCouncil(BaseUserManager): def create_user(self, userID, password=None): if not email: raise ValueError("Email is required") user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, userID, password): user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class sni(models.Model): SNI = models.CharField(max_length=10, primary_key=True) # USERNAME_FIELD = 'SNI' def __str__(self): return self.SNI class Account(AbstractBaseUser): userID = models.EmailField(max_length=80, unique=True) name = models.CharField(max_length=100) dateOfBirth = models.DateField(max_length=8, null=True) homeAddress = models.CharField(max_length=100, null=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) sni = models.OneToOneField(sni, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'userID' objects = userCouncil() def __str__(self): return self.userID def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Admin from statistics import mode from attr import field from .forms import createUserForm from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Account, sni class AccountAdmin(UserAdmin): list_display = ('userID', 'is_staff', 'is_admin') search_fields = ['userID'] readonly_fields = ('id','userID') add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('userID','name','password1','password2','dateOfBirth','homeAddress', 'is_staff', 'is_admin', 'sni' ), … -
Class Based View - Fields aren't created in database (python Inherits\django cbv)
I'm trying create a model inherit following this tutorial: https://www.digitalocean.com/community/tutorials/understanding-class-inheritance-in-python-3 Everything work. Can access FirstName property in child and show in view but when I run makemigration/migrate,inheriteds fields aren't created in table in database. (core-shark / core-trout) What's Can I doing wrong? Is possible, using python inherits and CBV, to create fields in database by makemigration/migrate? Thanks in advanced model.py class Fish(models.Model): def __init__(self, first_name, last_name="Fish"): self.first_name = first_name self.last_name = last_name def swim(self): print("The fish is swimming.") def swim_backwards(self): print("The fish can swim backwards.") class Meta: verbose_name = 'Fish' abstract = True def __str__(self): return self.first_name class Shark(Fish): def __init__(self, first_name, last_name="Shark", skeleton="cartilage", eyelids=True): self.first_name = first_name self.last_name = last_name self.skeleton = skeleton self.eyelids = eyelids def swim_backwards(self): print("The shark cannot swim backwards, but can sink backwards.") class Trout(Fish): def __init__(self, water ='', price = 0): self.water = water self.price = price super().__init__(self) class Meta: verbose_name = 'Trout' view.py class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) sammy = Shark("Sammy") terry = Trout() terry.first_name = "Terry" context['sammy'] = sammy context['terry'] = terry return context index.html ... <body style="color:red"> <h1>Fish Name: {{sammy.first_name}}</h1> <h1>Fish Name: {{terry.first_name}}</h1> </body> ... [2 project git -
Django aggregate field, but filtered by date
I,m trying to annotate a sum of another model, but filtered by date. I have the models Employee and Shift, the Shift one has a DecimalField called dur, a DateTimeField start and a foreign key employee. class Employee(models.Model): name = models.CharField(max_length=64) class Shift(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) start = models.DateTimeField() dur = models.DecimalField(max_digits=4, decimal_places=2, default=0) With Employee.objects.all().annotate(Sum('shift__dur')) I could add the total of all shifts, but how can I filter these shifts, e.g. to sum just the shifts in a given date range? Thanks in advance! -
Django self.groups.add(group) not adding group
I have a User model with role field. I want each user to be in one Group that corresponds to their role. So I try to set their group everytime user is saved. The problem is that user is not in any group after save. The important part of User model ... role = models.CharField('Rola', max_length=32, choices=RoleChoices.choices, null=True, blank=True ) def save(self, *args, **kwargs): self._set_role_stuff() super().save() self._set_group() pass def _set_role_stuff(self): if self.role and not self.role == RoleChoices.CLIENT: self.is_staff = True else: self.is_staff = False def _set_group(self): self.groups.clear() group = Group.objects.get(name='Fotograf') self.groups.add(group) How can I make it work? -
How can I resolve the 404 error in the product page here?
I'm making a website with a store. It looks like this: store -> catalog -> all products - > single product. When I going to a page with a single product, i get 404 error. views.py def product_view(request: WSGIRequest, product_slug: str): try: product = ( Product.objects .prefetch_related('productimage_set') .filter(slug=product_slug) .first() ) is_in_cart = CartProduct.objects.filter( product=product, cart__user=request.user, cart__active=True).first() context = { 'product': product, # 'is_in_cart': is_in_cart, } except Product.DoesNotExist: raise Http404 return render( request, 'shop/product.html', context) def category_list(request: WSGIRequest, category_slug: str): try: category: Category = ( Category.objects .prefetch_related("product_set") .get(slug=category_slug)) except Category.DoesNotExist: raise Http404 return render( request, 'shop/category.html', {"category": category}) urls.py path('', views.CatalogList.as_view(), name='shop'), path('<slug:category_slug>/', views.category_list, name='category'), path('<slug:product_slug>/', views.product_view, name='product') base urls path('admin/', admin.site.urls), path('shop/', include('page.shop.urls')), templates {% if product.productimage_set.all %} {% for image in product.productimage_set.all %} <div> <img src="{{ image.image.url }}" alt="{{ product.name }}"> </div> {% endfor %} {% endif %} -
Django displaying related objects
I have models for ProjectNotes and for ProjectNotesComments. ProjectNotesComments have a foreign key that is the ProjectNotes id. I am able to save comments on notes. I can see them in the admin panel. However I have not been able to figure out how to display the comments on the notes. Here are the models: class ProjectNotes(models.Model): title = models.CharField(max_length=200) body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True) project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes') def __str__(self): return self.title class ProjectNoteComments(models.Model): body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True) projectnote = models.ForeignKey(ProjectNotes, default=0, blank=True, on_delete=models.CASCADE, related_name='comments') Here is the view: class ProjectNotesDetailView(DetailView): model = ProjectNotes id = ProjectNotes.objects.only('id') template_name = 'company_accounts/project_note_detail.html' comments = ProjectNotes.comments This is the template I am currently using to test getting the comments to display: {% extends 'base.html' %} {% block content %} <div class="section-container container"> <div class="project-entry"> <h2>{{ projectnotes.title }}</h2> <p>{{ projectnotes.body | safe }}</p> </div> <div> </div> {% for comment in comments %} <div class="comments" style="padding: 10px;"> <p class="font-weight-bold"> {{ comment.body | linebreaks }} </div> {% endfor %} <h2><a href="{% url 'add_project_note_comment' projectnotes.pk %}">add note</a></h2> {% endblock content %}