Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: ZipFile does not recognize file as zip: raised BadZipFile or AttributeError
I am trying to handle ZipFile. I have archived 6 images as "images.zip". >>> zf=zipfile.ZipFile('images.zip') >>> zipfile.is_zipfile(zf) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 183, in is_zipfile result = _check_zipfile(fp=filename) File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 169, in _check_zipfile if _EndRecData(fp): File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 241, in _EndRecData fpin.seek(0, 2) AttributeError: 'ZipFile' object has no attribute 'seek' Also when I try to open my file as File in django I get an error. from django.core.files import File f = File(open('images.zip')) >>> zip=ZipFile(f) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 1100, in __init__ self._RealGetContents() File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 1168, in _RealGetContents raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file It seems that with the file all is fine, I can unpack it, all images are fine. I can also access other zipfile atributes and functions eg. >>> zf <zipfile.ZipFile filename='images.zip' mode='r'> >>> zf.namelist() ['img6.jpg', 'img5.jpg', 'img4.jpg', 'img4.jpeg', 'img3.jpg', 'img2.jpg', 'img1.jpg'] >>> zf.infolist() [<ZipInfo filename='img6.jpg' compress_type=deflate filemode='-rw-rw-r--' file_size=97335 compress_size=97217>, <ZipInfo filename='img5.jpg' compress_type=deflate filemode='-rw-rw-r--' file_size=83314 compress_size=83030>, <ZipInfo filename='img4.jpg' compress_type=deflate filemode='-rw-rw-r--' file_size=133511 compress_size=132992>, <ZipInfo filename='img4.jpeg' compress_type=deflate filemode='-rw-rw-r--' file_size=154011 compress_size=153871>, <ZipInfo filename='img3.jpg' compress_type=deflate filemode='-rw-rw-r--' file_size=119871 compress_size=119024>, <ZipInfo filename='img2.jpg' compress_type=deflate filemode='-rw-rw-r--' … -
Django Rest Framework is detecting AnonymousUser on PUT requests
I have this viewset class OrderItemViewSet(viewsets.ModelViewSet): serializer_class = OrderItemSerializer def get_queryset(self): print('Current User', self.request.user) return OrderItem.objects.filter(order__owner=self.request.user.profile) take note of the print('Current User', self.request.user) I have used that to identify the root of the problem. urls.py router.register('order_items', shopping_api.OrderItemViewSet, 'order_items') So far so good... But when I make a PUT request; const response = await fetch(api.authurl+'/order_items/'+order_item.id+'/', { method: 'PUT', headers: api.httpHeaders, body: JSON.stringify(order_item) }); This error shows up AttributeError: 'AnonymousUser' object has no attribute 'profile' The print statement identifies these for a GET then a POST request respectively: [19/Jun/2020 20:17:22] "GET /sellers/3/ HTTP/1.1" 200 196 Current User AD [19/Jun/2020 20:17:30] "GET /order_items/ HTTP/1.1" 200 1060 Current User AnonymousUser So I have reason to believe that when I make a get request, the authenticated user is detected, but with a PUT it's suddenly Anonymous. I doubt I have to make frontend authentication right? e.g having Authorization with a token in my headers in the request. Since I have that GET request doing fine. -
Need to get all permissions for groups assigned to a custom table
We are using the standard contrib auth app in Django, which, of course, allows permissions to be assigned directly to users, and/or to groups, with the groups then being assigned to users. Before I knew about the get_all_permissions() method of the User object, I had my own method that returned all permissions for a user using this statement: user_permissions = Permission.objects.filter(Q(user=user) | Q(group__user=user)).all().distinct() I'm sure I found that code after searching about how to get all permissions, and just copy/pasted it into my code. We now want to add groups at a different level in our site. We assign users to projects via the ProjectUser model, which essentially has foreign keys to project and user. We want to add group to that model so that, for example, a user (developer) could be "project lead" on one project, but just a "contractor" on another. I added a many-to-many field named "groups" to the ProjectUser model, but now I'm not sure what the statement equivalent to the one shown above would be to get all project-level permissions. -
Can't create object in django
I'm trying to make django app somthing like instagram where you can post images. I have my code with no errors but can't create object post. I can display template in html but after i fill the fields and click button submit nothing happend besides reloading site. models.py: from django.db import models from django.contrib.auth import get_user_model import datetime # Create your models here. User = get_user_model() class Post(models.Model): author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) image = models.ImageField(upload_to='media') caption = models.TextField(blank=True, null=True) date_of_publication = models.TimeField(blank=True, default=datetime.datetime.now()) forms.py: from django.forms import ModelForm from .models import Post #POST FORMS.PY class PostForm(ModelForm): class Meta: model = Post fields = ['user', 'image', 'caption'] exclude = ['user'] views.py: from django.shortcuts import render from .forms import PostForm from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect # Create your views here. @login_required def create_post(request): if request.user.is_authenticated: if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save(commit=False) form.user = request.user form.save() return HttpResponseRedirect('/about/') else: form = PostForm() return render(request, 'posts/create_post.html', {'form':form}) -
Getting an error: got an unexpected keyword argument 'version'
I was doing the Django haystack tutorial, and when I run the search query, I get the error __call__() got an unexpected keyword argument 'version'. This error is coming from Django. I am fairly new to Django, and I'm not sure what all to add to help debug this. Also, in engine, I am using haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine, and am using ElasticSearch v7 -
How can I access another field of a related ManyToMany table?
Let's say I have the following models: class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) upload = models.ForeignKey(related_name='x1', Uploads) class Uploads(models.Model): topic = models.CharField(max_length=100) I want to select all the Articles of a specific upload topic along with their Publication title. So my output should be: <QuerySet [{'id': 1, 'headline': 'headline1', 'publications': 'publication title 1'}, {'id': 2, ''headline': 'headline2', 'publications': 'publication title 2'},] Currently I have this: Dataset.objects.filter(upload__topic='sports').values('id', 'headline', 'publications') which gives me the following: <QuerySet [{'id': 1, 'headline': 'headline1', 'publications': 1}, {'id': 2, ''headline': 'headline2', 'publications': 2},] I know I can loop over the QuerySet and for each publication fire another DB query towards the Publication table to get the relevant title, but I'm wondering if there's a better way to do that. Perhaps with a single query? -
Circular Dependency between Form and Model
Here is a form: class ToDoItemModelForm(forms.ModelForm): class Meta: from ToDoDashboard.models import ToDoItem model = ToDoItem fields = ['description', 'label', 'comment', ('start_date', 'due_date', 'time_estimate_hours')] def clean(self): start_date = self.cleaned_data.get('start_date') end_date = self.cleaned_data.get('due_date') if start_date > end_date: raise forms.ValidationError("Dates are incorrect") return self.cleaned_data and here is a model: class ToDoItem(models.Model): dashboard_column = models.ForeignKey(DashboardColumn, on_delete=models.CASCADE) description = models.TextField() label = models.CharField(max_length=128) start_date = models.DateTimeField(null=True) due_date = models.DateTimeField(null=True) from ToDoDashboard.forms.ToDoItemForm import ToDoItemModelForm form = ToDoItemModelForm Now it says ImportError: cannot import name 'ToDoItem' from partially initialized module 'ToDoDashboard.models' (most likely due to a circular import) How to solve the problem? -
URL Routing trouble in React + Django
I have the following urlpatterns configured for my Django app. This rule will route to http://localhost:8000/profile/. urlpatterns = [ path("profile/", test_frontend_views.profile), ] The views code: def profile(request): return render(request, 'frontend/Profile_temp_master.html') Within my React components that are dynamically creating HTML for the template, I am making requests to my Django backend API with the following scheme: fetch("api/profile", requestOptions).then(..).then(..) However, rather than this request routing to http://localhost:8000/api/profile/, it is routing to http://localhost:8000/profile/api/profile/ which is not a valid endpoint and returns and error. How can I solve this so that the URL routes to the correct endpoint? -
Why do I get a Key Error for 'post' in PostListView
I don't know why I got a Key Error message (KeyError at / 'post') when I def get_context_data in PostListView. But that was totally fine when I just def get_context_data in PostListDetailView. Views.py def home(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'posts': Post.objects.all(), 'is_liked': is_liked, 'total_likes': post.total_likes(), } return render(request, 'blog/home.html', context) def like_post(request): # post like post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True return HttpResponseRedirect('http://127.0.0.1:8000/') class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 is_liked = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['post'] if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return context class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post is_liked = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['post'] if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return context -
Admin Section with Users and Groups Disappeared
I want to add custom views and templates to Admin and wrote this: # in models.py class MyAdminSite(admin.AdminSite): def my_view(self, request): return HttpResponse("Test") def get_urls(self): from django.urls import path urlpatterns = super().get_urls() urlpatterns += [ path('my_view/', self.admin_view(self.my_view)) ] return urlpatterns admin.site = MyAdminSite() # and in apps.py class MyAdminConfig(AdminConfig): default_site = 'ToDoDashboard.admin.MyAdminSite' I have registered all the models and I see them in my custom Admin panel. However, the section with users and groups has disappeared. How to get it back? -
Query database in django using model procedure
I have created model with procedure that subtract two dates from fields in model returning days difference between them, for example: class Example: earlierDate=models.DateField() laterDate=models.DateField() def day_diff(self): return (laterDate-earlierDate).days Is it possible to query database including day_diff procedure ? in_views_query=Example.objects.filter(day_diff__gte=30) When i use this kind o query it shows me that there is no field 'day_diff' Regards -
How to redirect to post detail page after deleting a comment in Django?
Can someone help me out please. I want to redirect to a post detail page after deleting a comment of a given pk. I got an AttributeError when ever I hit the comment delete button. Error: function object has no attribute 'format' If I change my success_url of the comment delete view to redirect to post list page with no argument, it works well but that's not what I want. I need the user to be redirected to post detail page after deleting a comment. Here's my Post model STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') objects = models.Manager() published = PublishedManager() tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[self.pk, self.slug]) def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs)''' **Comment model** ```class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) comment = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.author} on {self.post}' def get_absolute_url(self): return … -
Unable to access static files in Django - Development server
I am trying to access static files in browser but unable to access them. My static settings insettings.py are below STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") My urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', FrontPage.as_view()), # url('', include(router.urls)) ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My folder structure projectname projectname settings.py urls.py app1_name static bootstrap css cover.css templates My template.html <link href="/static/bootstrap/css/cover.css" rel="stylesheet"> The above link isn't loading the static file. Please let me know where am I going wrong. -
TypeError: __init__() got an unexpected keyword argument 'instance' for custom user in Django
When I am trying to register a custom user or when i am trying to view profile of login user, i am getting this error. I am not sure why i am getting this error, Here is my code, please suggest where i am doing wrong. Thank you in advance. Url.py path('register/', RegisterView.as_view(template_name='users/register.html'), name='register'), path('profile/', user_views.profile, name='profile'), Model.py user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=254, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser # notice the absence of a "Password field", that is built in. USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # Email & Password are required by default. objects = UserManager() ``` Form.py ``` class RegisterForm(forms.Form): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: Model = User fields = ('email',) def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") return email def clean_password2(self): # Check that the two password … -
Template extending not working properly - Django
i have 3 files, Base.html, Navbar.html and dashboard.html. im trying to extend base.html and include navbar.html in dashboard. its getting extended but the problem is then dashboard's content data is not visible. If i remove navbar.html it works but no navbars. Below are the files pls check and help to resolve. Navbar.html {% load static %} <!-- Navbar --> <nav class="main-header navbar navbar-expand navbar-white navbar-light"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a> </li> <li class="nav-item d-none d-sm-inline-block"> <a href="dashboard" class="nav-link">Home</a> </li> </ul> <!-- SEARCH FORM --> <form class="form-inline ml-3"> <div class="input-group input-group-sm"> <input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search"> <div class="input-group-append"> <button class="btn btn-navbar" type="submit"> <i class="fas fa-search"></i> </button> </div> </div> </form> <!-- Right navbar links --> <ul class="navbar-nav ml-auto"> <div class="dropdown-divider"></div> </ul> # Side configutarion {# <li class="nav-item">#} {# <a class="nav-link" data-widget="control-sidebar" data-slide="true" href="#" role="button">#} {# <i class="fas fa-th-large"></i>#} {# </a>#} </nav> <!-- /.navbar --> <!-- Main Sidebar Container --> <aside class="main-sidebar sidebar-dark-primary elevation-4"> <!-- Brand Logo --> <a href="dashboard" class="brand-link"> <img src="{% static 'img/AdminLTELogo.png' %}" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8"> <span class="brand-text font-weight-light">Acro Paints</span> </a> <!-- Sidebar --> <div class="sidebar"> <!-- Sidebar user panel (optional) --> <div class="user-panel … -
How to use string of <li> in django view?
I am building a blog where users can click on several <li> items in the sidebar to show blog posts according to the clicked category. So far I managed to show the five latest blog posts on the landing page (blog.html extends base.html) with a load more button to display another five so on and so forth until the pagination is done. Now I would like to extend this logic to use the same views (there are two views, one for the initial 5 posts and one for the pagination - load more logic) for the categories as well to avoid ending up with two views + 1x Ajax function for each category. Is there any dynamic solution to this? My basic idea is to get the string of the clicked <li> item and filter the queryset by the category then to get the correct objects from the database. So the general logic would be the same and each URL would be mapped to the very same view. If my general idea might work, how can I use the clicked string within the view function to adjust the queryset? views.py def render_blog(request): # Get 5 latest posts and order by … -
Django - Variable inside style not detected
{% if photos %} {% for photo in photos %} {% endfor %} {% else %} No images availble for the project. {% endif %} And I want to add a picture url inside the style tag. div class='image-block col-sm-4' style="background: url({{photo}}) no-repeat center top;background- size:cover;" How can I get the {{photo}} url inside the string? -
Blank field not working correctly in Django model
I have a Django model described as follows- class Building(models.Model): name = models.CharField(max_length=25,unique=True,blank=False) country = models.CharField(max_length=20,blank=False) city = models.CharField(max_length=20,blank=False) def __str__(self): return self.name All of the fields are required as blank is set to False in each of them but still, I am able to save objects for this model by leaving city and country as blank. -
virtualenv could not install on my machine due to permission denied
creating c:\program files\python38\Lib\site-packages\distlib error: could not create 'c:\program files\python38\Lib\site-packages\distlib': Access is denied ---------------------------------------- How do I fix this? I tried to install virtualenv and django but got the error above -
Elastic Beanstalk: /bin/sh: /opt/python/run/venv/bin/activate: No such file or directory
Trying to deploy a django app which uses channels following this https://medium.com/@elspanishgeek/how-to-deploy-django-channels-2-x-on-aws-elastic-beanstalk-8621771d4ff0 These are my config files: 01_env.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: "dashboard/wsgi.py" aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "dashboard.settings" PYTHONPATH: /opt/python/current/app/dashboard:$PYTHONPATH aws:elbv2:listener:80: DefaultProcess: http ListenerEnabled: 'true' Protocol: HTTP Rules: ws aws:elbv2:listenerrule:ws: PathPatterns: /websockets/* Process: websocket Priority: 1 aws:elasticbeanstalk:environment:process:http: Port: '80' Protocol: HTTP aws:elasticbeanstalk:environment:process:websocket: Port: '5000' Protocol: HTTP 02_setup.config container_commands: 00_pip_upgrade: command: "source /opt/python/run/venv/bin/activate && pip install --upgrade pip" ignoreErrors: false 01_migrate: command: "django-admin.py migrate" leader_only: true 02_collectstatic: command: "django-admin.py collectstatic --noinput" 03_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' When I run eb create django-env it fails with Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001]. and in the logs, I found that the reason is: 2020-06-17 16:36:41,880 P4189 [INFO] Command 00_pip_upgrade 2020-06-17 16:36:41,883 P4189 [INFO] -----------------------Command Output----------------------- 2020-06-17 16:36:41,883 P4189 [INFO] /bin/sh: /opt/python/run/venv/bin/activate: No such file or directory So even though I'm following the guide, the directory seems to not exist. I'm also not being able to SSH into the EC2 instance to check this. Has the python venv directory in Amazon Linux 2 changed? -
Django Rest Framework : Nested Serializer not working
I have almost tried everything but am not able to reach at the point model.py file class RecievingImages(models.Model): """Original and Masked Images""" .... name = models.CharField(max_length = 100, unique = True, primary_key=True) area = models.IntegerField() number = models.IntegerField() agency_name = models.CharField(max_length=100, default='general') rawImage = models.ImageField(upload_to=imageNameForRawImage,) ... class UpdationImages(models.Model): """ Update Image wrt name""" .... name = models.ForeignKey(RecievingImages, on_delete=models.PROTECT, related_name='updated') updated_image = models.ImageField(upload_to=UpdatedImageFolder,) updated_image_url = models.TextField(default='None') .... serializer.py class UpdatedImageSerializer(serializers.ModelSerializer): model = UpdationImages fields = ('name', 'updated_image', 'updated_image_url') class RecievingImagesSerializer(serializers.ModelSerializer): updated = UpdatedImageSerializer(many= True, read_only=True) model = RecievingImages fields = ('updated','name','area','number','agency_name', rawImage) I have used related_name in the model and also following the documentation along with that with many = True But still in serializer.data updated does not show views.py class MappingSinglePhoto(APIView): """ Mapping Single Image """ def post(self, request): try: data = request.data # import pdb; pdb.set_trace() name_of_image = data['name'] mapped_images_qs = UpdationImages.objects.select_related('name').filter(name = name_of_image) for image in mapped_images_qs: serializer = RecievingImagesSerializer(instance = image) pdb.set_trace() serializer.data # return Response(serializer.data) except Exception as e: print(e) NOTE if I use depth=1 then it's working fine, but I am not looking for all the fields that depth displays. Thanks & Regards -
Django model order by custom algorithm Using the difference between the current time and creation time
Django version 2.1.15 Python version 3.7.4 Djngo settings.py LANGUAGE_CODE = 'ko-kr' TIME_ZONE = 'Asia/Seoul' I am not familiar with English.I will write in English as hard as possible. Django model order by custom algorithm Using the difference between the current time and creation time my model is models.py class Review(models.Model): title = models.CharField(max_length = 100) content = models.TextField() movie = models.ForeignKey(Movie,on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete = models.CASCADE) like_users=models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='like_reviews') created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) i want to Descending order_by (Count(like_users)/(current_time - created_at + 60)) Review model (current_time-created_at) : I want to change the difference between two hours to minutes. (integer) I tested these things. from django.db.models import ExpressionWrapper,F,Value from django.db.models.fields import DurationField,DateTimeField def test(request): now = timezone.localtime() test = Review.objects.annotate(diff_time=(ExpressionWrapper(Value(now, DateTimeField()) - F('created_at'), output_field=DurationField()))).annotate(diff_value=F('diff_time')+60).values() But failed. How can I get the results I want? I used a translator to ask questions, but I hope my intentions are clearly communicated. I'm so sorry for my poor English. -
Django, accessing model methods
In the Django documentation, they recommend writing business logic in Model. How do the View layer or queryset access the methods in Model ? As per example in documentation (https://docs.djangoproject.com/en/3.0/topics/db/models/) from django.db import models class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField() def baby_boomer_status(self): "Returns the person's baby-boomer status." import datetime if self.birth_date < datetime.date(1945, 8, 1): return "Pre-boomer" elif self.birth_date < datetime.date(1965, 1, 1): return "Baby boomer" else: return "Post-boomer" How do view layer access the baby_boomer_status ? I have a little experienced in Django development but I used to write logics in View itself. -
join the results of two query on each others with Django
I have 2 models, i simplify them for the example: class CustomerOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT) isPaid = models.BooleanField(default=False) and class EventParticipant(models.Model): customerOrder = models.ForeignKey(CustomerOrder, on_delete=models.CASCADE) event = models.ForeignKey(Product, on_delete=models.CASCADE) What i need to do is to display in a table every participants for an event but link the order to the participant so i can display the isPaid status for each participant. I think its similar to a join on SQL. So i tried something like: participants = EventParticipant.objects.filter(event=event_pk).select_related('customerOrder') but when i try to access it like participants.cusomerOrder i get: 'QuerySet' object has no attribute 'customerOrder' so i guess is missunderstand something. Thanks -
Saving a form in a foreign key field
I have two models Order and a date model. The order model has a foreign key attribute of date model. I have made a form in which I can update the date fields of order, but when I click submit it creates a new date object in date model not in the order date field. The order model date field is empty. My views code seems to be alright maybe somethings wrong in my form.py.I want my form to save values in the date field in order. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) view.py def dateDetailView(request, pk): order = Order.objects.get(pk=pk) date_instance = order.date form = DateForm(request.POST, request.FILES, instance=date_instance) if …