Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does it make sense to point to same table twice on django model
I have this Tables class Category(models.Model): name = models.CharField(max_length=20) class Rule(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) next_page = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) # ... other fields Obviously, I am no database or Django expert, the need for next_page and category are different The Rule table is supposed to be used to set the page that comes next after certain condition are met/performed by the user. My general question is there a better way to do this? -
How to exclude objects connected via ForeignKey Django?
class AnimalX(models.Model): my_animal = models.ForeignKey('animals.MyAnimal', on_delete=models.CASCADE, null=False, blank=False, related_name='animals') class MyAnimal(models.Model): name = models.CharField(max_length=256) I'd like to get all the MyAnimal instances that do not have AnimalX instance. Do you have any idea how can i achieve this? I thought about doing MyAnimal.objects.all().exclude(AnimalX.objects.all()) but it doesnt work. -
How to make a request in the database Django
class A(models.Model): name_A = models.CharField(max_length=200) class B(models.Model): name_B = models.IntegerField() relate_a = models.ManyToManyField(A) class C(models.Model): name_C = models.CharField(max_length=100) relate_b = models.ManyToManyField(A) We have name_C from C and name_B from B. How to make a queryset that gets name_A from tables C and B, and compare them. -
How to use HTML date type with Django and HTMX
I am trying to get date from a picker and trigger an hx-get when the date is changed. The code below produces and text input field with a datepicker pop up. When I pop up the datepicker and change the date, the hx-get is not triggered. If I then click in the text input area the hx-get is triggered with the picked date. So how do I get the trigger to activate when I select the date from the picker? I tried both the TextInput and DAteInput widgets but they both act the same way. I played a bit with django-bootstrap-datepicker-plus but found it did not work well with my forms which use both HTMX and Crispy forms helper layouts. Thanks datedue = forms.DateField(initial=timezone.now().date(), label="On or before", widget=forms.TextInput(attrs={'type': 'date', 'hx-get': reverse_lazy('change-priority'), 'hx-target': '#tasklist', 'hx-include': '[name="priority"], [name="status"],[name="assigned"], [name="iscomplete"]', 'hx-trigger': 'click change' }) ) -
Django-Tenant Application using Cpanel
I have devloped a Django-Tenant Application with Postgresql and is ready for deployment. could not find much info about deploying a Django-Tenant Application. confused and stuck at this point. Want to know if it is possible to deploy on Cpanel hosting with postgres support and Shared Hosting Plans. If so how? Second, does Heroku support Django-Tenant Application with Postgresql. any suggestions please. -
Django QA forms with sections
I am stuck and I try to explain to you what I am trying to accomplish. I am creating an application to create, organize and respond to operational checklists. I have a structure like: checklist -> section -> question -> answer type -> answer Each question can have a different and configurable answer type, for example: the fire extinguisher is in the correct place: Yes / No what state is the main switch in: On / Off I have create models/views/forms for managing and sorting "checklist -> section -> question -> answer type -> answer" and it works. Here is the model.py class Checklist(models.Model): class Meta: verbose_name = "Checklist" verbose_name_plural = "Checklists" name = models.CharField(max_length=64) Description = models.CharField(max_length=64) def __str__(self): return self.name class Section(OrderedModel): class Meta: ordering = ('order',) verbose_name = “Section” verbose_name_plural = “Sections” name = models.CharField(max_length=64) description = models.CharField(max_length=64) checklist = models.ForeignKey( Checklist, on_delete=models.CASCADE, blank=True, null=True, default=None, related_name=‘section_rel') def __str__(self): if self.checklist: return self.checklist.name + " - " + self.name else: return self.name class AnswersValue(models.Model): class Meta: verbose_name = "Answers Value" verbose_name_plural = "Answers Values” name = models.CharField(max_length=16, unique=True) value = models.CharField(max_length=16, unique=True) def __str__(self): return self.name class AnswerType(models.Model): class Meta: verbose_name = "Answer Type" verbose_name_plural = "Answer … -
How to make keyword field in django model
I'm trying to have my django model automatically create a slug of the model name, but I get this error: AttributeError: 'str' object has no attribute 'slugify' This is my code: from django.db import models from django.utils.text import slugify class school (models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=750) location = models.CharField(max_length=19, choices=location_choices) picture = models.URLField(max_length=200, default="https://i.ibb.co/0MZ5mFt/download.jpg") slug = models.SlugField(unique=True, default=name.slugify(), editable=False) -
image.url returns twice https
I just implemented s3 bucket and all the static assets work fine but when I try to get a file I get the following link https://https//mybucket.s3.eu-central-1.amazonaws.com/static/media/thumbnails/Northern_Lights-1.jpeg What is the problem? settings.py AWS_ACCESS_KEY_ID = AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY = AWS_SECRET_ACCESS_KEY AWS_STORAGE_BUCKET_NAME = AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False AWS_S3_CUSTOM_DOMAIN = 'https://mybucket.s3.eu-central-1.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_DEFAULT_ACL = None AWS_LOCATION = 'static' STATIC_URL = 'https://mybucket.s3.eu-central-1.amazonaws.com/static/' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') STATIC_ROOT = os.path.join(BASE_DIR, 'static/') -
How to convert a List of objects to a queryset in Django
I've used chain from itertools to join more than a single queryset into 1 list. but after that when I try to use the generated list. it fails with the error : AttributeError: 'list' object has no attribute 'all' Here is how I do this : def formfield_for_foreignkey(self, db_field, request, **kwargs): parent = self.get_parent_object_from_request(request) home_team_object = parent.home_team away_team_object = parent.away_team if db_field.name == "team": kwargs["queryset"] = Team.objects.filter( Q(away_team_team=parent) | Q(home_team_team=parent)) if db_field.name == "player": parent = self.get_parent_object_from_request(request) print(parent) away_team_players = away_team_object.players.all() home_team_players = home_team_object.players.all() cap_objects = PlayerProfile.objects.filter(Q(id=home_team_object.cap.id) | Q(id=away_team_object.cap.id)) result_list = list(chain(away_team_players, home_team_players, cap_objects)) print(result_list) kwargs["queryset"] = result_list if db_field.name == "assistant": parent = self.get_parent_object_from_request(request) print(parent) away_team_players = away_team_object.players.all() home_team_players = home_team_object.players.all() cap_objects = PlayerProfile.objects.filter(Q(id=home_team_object.cap.id) | Q(id=away_team_object.cap.id)) result_list = list(chain(away_team_players, home_team_players, cap_objects)) print(result_list) kwargs["queryset"] =result_list return super().formfield_for_foreignkey(db_field, request, **kwargs) Here is where I tried to call 3 different querysets from the same Model than tried to merge them into 1 query set : away_team_players = away_team_object.players.all() home_team_players = home_team_object.players.all() cap_objects = PlayerProfile.objects.filter(Q(id=home_team_object.cap.id) | Q(id=away_team_object.cap.id)) result_list = list(chain(away_team_players, home_team_players, cap_objects)) -
How to setup frontail with Django and Docker
I am trying to setup Frontail to access the logs for a Django application deployed using Docker locally. Has anyone done this before? There is very little documentation or other information online. -
Django Admin Configure Column ConfigurableColumnsMixin Display list
By making ConfigurableColumnsMixin I can display all the columns by default i can view all the column. How not to make the columns as default , so that usercan select which column hecan select and then display those coulmns. admin.py class ProductAdmin( TimestampedModelAdminMixin, ConfigurableColumnsMixin, admin.ModelAdmin ): list_display = [ "id", "comment", "active", ] -
How can I load css and js files faster and does storing these files in your media directory affect load time?
So I have a django app and I'm hosting it on heroku, everything works fine.I am storing the images(for now) in my media directory Same for js and css file, however they're going to be there forever but i don't know if thats a good practise, should i host it somewhere online also. Also how can i load css and js faster (get the resources).I have a function that add a load screen so the website gets to load all resources but whenever the files arent loaded it the function is basically useless since it's in the js file and for some reason this problem mostly occurs when i open the website through a mobile browser Here is the code for the function, although i don't think its needed: base.js const loader = document.querySelector(".loader"); document.addEventListener('readystatechange', function checkResources(){ let socials = document.getElementById("nav-socials"); alert(`readystate: ${document.readyState}`); if(document.readyState == "complete"){ //remove a social nav sinces it also has a z-index:100 and will still be seen socials.style.display = "block" alert("page ready, remve") return loader.classList.add("hidden") }else{ loader.classList.remove("hidden") socials.style.display = "none"; } }); Note: i have a base template which is used in almost all the pages. Here is how my django template server the css and … -
I'm trying to view a file I uploaded django FileField but it's not work
Hi friends I got stuck in problem while trying to view a pdf file in my page which I uploaded have this models: class HomeWork(models.Model): nameFile = models.CharField('Name File',max_length=30) file = models.FileField('File',upload_to="files",null=True) course = models.ForeignKey(Course, on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE, null=True) i make this field because i want to upload pdf files. file = models.FileField('File',upload_to="files",null=True) in the settings.py i make this: MEDIA_ROOT = BASE_DIR / 'static/upload' MEDIA_URL = "/upload/" here i have the html file that i want to see my upload file Whenever I try to access to: <iframe src="{{hw.file.url}}" frameborder="10"></iframe> it's not show me the pdf. {% block content %} <h1>{{course.name_course}}</h1> {% if user.is_authenticated %} <a href="{% url 'Category:u-f' course.id user.id%}">Upload FILE</a> {% endif %} {% if homeworks %} <div class="row"> {% for hw in homeworks %} <div class="col-md-4"> <br> <div class="card"> {{hw.file}} <iframe src="{{hw.file.url}}" frameborder="10"></iframe> <div class="card-body"> <h4 class="card-title text-center"> <a class="Course" href=""><b>{{hw.nameFile}}</b></a></h4> <h5 class="card-title"></h5> </div> <div class="col text-center"> </div> <br> </div> </div> {% endfor %} </div> {% endif %} {% endblock content %} here some photo how its look like in html But whenever I make that line: <iframe src="{{hw.file.url}}" frameborder="10"></iframe> to static like that: <iframe src="{% static 'upload/files/avl_fib_proof.pdf' %}" frameborder="10"></iframe> It looks like this: -
how to add menu item in side list in django with jazzmin?
I added one menu item in django admin panel.when i clicked that, all othe app and their model disappears.I am using jazzmin in admin panel.How to send all side menu list in my template? -
Table Data with sort, search query, pagination pass to different component in Angular
I will try to explain as simple as possible. There is a table which in start gets first 30 rows of n rows and has sorting, search using mat-table. So even if it is sorted only the first 30 rows will be sent and when the user goes to next page it gets the next 30 rows from backend each time making a new request. Now each row has a button that will take it to another component which will get some detailed data about the specific row. This component has a previous and next feature that will get the detailed view of the next or previous row data in the same order that is displayed in the table(sorted, search Result, page number). Currently the table rows are made again in backend(Django) with all the sort, search and other parameters then find the current row and send the next and previous row (will take minimum 5 hits on DB). Hence it very slow. In Frontend I can only pass the data of only that page, which will have problem in next or previous page. How to properly tackle this... -
sign vs sign_object in Django
Who can explain me the difference between .sign() and .sign_object() in Django Signer class? (from django.core.signing import Signer) I know what the .sign() method do in Django 3. Is .sign_object() a new method in Django 4? Is these same signer = Signer() signer.sign('My string') signer = Signer() signer.sign_objects('My string') -
filter on category in django
I was doing the project on Django & react using RestAPI to get into it more deeply. I have a problem with the view part. There are models; Course, CourseCategory. CourseCategory is about what category a course is related to (which is ForeignKey). I have list all the courses in one page where a certain category is clicked. But I don't know how to do it in the right way. Here is my model class CourseCategory(models.Model): title = models.CharField(max_length=150) description = models.TextField() def __str__(self): return self.title class Course(models.Model): category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100, null=False , blank= False) brief = models.TextField(null=False , blank= False) image = models.ImageField(upload_to='img/%y/m/%d', default='img/1.png') def __str__(self): return self.name and here is my view where i tried to write a filter function class CourseList(generics.ListCreateAPIView): queryset = Course.objects.all() serializer_class = CourseSerializer #permission_classes = [IsAuthenticated] #authentication_classes = [TokenAuthentication] def get_queryset2(self): qs = super().get_queryset() if 'result' in self.request.GET: cat = int(self.request.GET['result']) qs = Course.objects.filter( category=cat ) return qs when tried to test that by writing the id of the category it's doesn't work like this enter image description here enter image description here so is there anyone who can help, please -
Is there any way, I can create a Decorator that will check if the function will run successfully or throws error?
I have to create a decorator for a event in django and store all args,kwargs,status,etc etc in django model. So far I am able to store args, kwargs and traceback, but challenge is,the event might also fail, so i have to save the status as well ie. success or failed. How do I do that using a decorator? import inspect import traceback def dump_args(func): def wrapper(*args, **kwargs): func_args = inspect.signature(func).bind(*args, **kwargs).arguments func_args_str = ", ".join(map("{0[0]} = {0[1]!r}".format, func_args.items())) print(f"{func.__module__}.{func.__qualname__} ( {func_args_str} )") return func(*args, **kwargs) return wrapper @dump_args def test(event, profile=None, loan_request=None, approved_loan=None, loan_tranche=None, lead=None, limit_revision=None, event_kwargs=None, use_atomic=False): try: #some event will run pass except: #if event fails var = traceback.format_exc() print(var) test(1, 2, 3, 4, 5, d=6, g=12.9) What I now want is how can get status = Success if the function runs successfully and status = Fail if it fails? Please suggest. -
django-filter ModelChoiceFilter using queryset
I'm using django-filter and I have my model log : class Log(models.Model): admin = models.CharField(max_length=64) appli = models.CharField(max_length=64) ID ADMIN APPLI 1 LEA VM 2 FRANCIS VEEAM 3 LOREN OBJECTS I want to filter ADMIN and APPLI with a Select field related to the model Log like this : <select class='form-control'> <option>LEA</option> <option>FRANCIS</option> <option>LOREM</option> </select> by using ModelChoiceFilter. I tried something like this but the search is not working probably because value_list return a tulp. admin = django_filters.ModelMultipleChoiceFilter( queryset=Log.objects.distinct().values_list('admin', flat=True)) Is there another way to do it ? -
Django I'm trying to write a test for my add_post view and it's not working
my view: def add_post(request): if request.method == "POST": form = NewPostForm(request.POST, request.FILES) if form.is_valid(): form.instance.author = request.user form.save() messages.success(request, "Your post was added successfully.") return redirect("food-feed") messages.info( request, "If you're adding a recipe you must include the ingredients, instructions and cooking time.", ) form = NewPostForm() return render(request, "post/add_post.html", {"addpost_form": form}) test from django.test import TestCase from django.contrib.auth.models import User from django.core.files.uploadedfile import SimpleUploadedFile class TestPost(TestCase): def setUp(self): self.user = User.objects.create_superuser(username='creatingsometest', password='passwordfortesting') def tearDown(self): self.user.delete() def test_add_post(self): self.client.login(username='creatingsometest', password='passwordfortesting') response = self.client.post( "/add-post/", { 'title': 'TESTCASE TITLE', 'post_description': 'TESTCASE POSTDESCRIPTION', 'main_image': SimpleUploadedFile(name='test_image.jpg', content=''), 'is_recipe': 'on', 'ingredients': '', 'recipe_description':'', 'cooking_time': '', '_save': 'Save', }, ) self.assertEqual(response.status_code, 302) self.assertRedirects(response, "/food-feed") The test if failing self.assertEqual(response.status_code, 302) AssertionError: 200 != 302 Also I don't really know how to handle the ImageField (main_image) and the BooleanField(is_recipe). When I printed response.content above the self.assertEqual I see the html that corresponds to the add-post form. -
Auto populated form fields django
I am working on my blog application and I added comment section now I want to auto populate two fields in forms.But i am getting error NOT NULL constraint failed: MainSite_comment.user_id. Models.py class Comment(models.Model): comment_text = models.TextField(("comment_text")) user = models.ForeignKey("account.User", related_name=("comment_user"), on_delete=models.CASCADE) #post = models.ForeignKey("Post", related_name=("comment_post"), on_delete=models.CASCADE) parent = models.ForeignKey('self',related_name=("replies"), on_delete = models.CASCADE , blank= True ,null=True) timestamp = models.DateTimeField(("Comment Timestamp"), auto_now=False, auto_now_add=True) def __str__(self): return self.user.username Forms.py class CommentForm(ModelForm): class Meta: model = Comment fields =['comment_text'] labels ={ 'comment_text':'', } widgets ={ 'comment_text': forms.Textarea(attrs = {'class':'form-control','rows':'5','cols':'50', 'style' : 'background: #fff;', 'placeholder':'Write a comment....'}), } Views.py class PostDetailView(FormMixin,DetailView): model = Post form_class = CommentForm template_name = 'MainSite/blogpost.html' def form_valid(self, form): form.instance.user_id = self.request.user.id return super().form_valid(form) def post(self,request,slug): print(request.user.id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): form.save() messages.success(request,"Comment added successfully") success_url = reverse_lazy('home') I want auto populate both user and post field(I will change the post field in model later).I get error while auto populating user field in model.Currently I using slug in urls to show post.I dont know how this form_valid() works and what does it returns and what is this instance is. Thanks for help and any advice is helpful. -
Invalid data. Expected a dictionary, but got str
Expected Behavior To create a new object using the ID of the ForeignKey Field. Actual Behavior It worked fine when the Serializer class looked like this : class RequestSerializer(serializers.ModelSerializer): """ Serializer for Request model """ class Meta: """ Meta class for RequestSerializer """ model = Request fields = [ "id", "category", "type", "finishing_type", "finishing_level", "need_design", "number_of_floors", "property_space", "no_of_receptions", "no_of_rooms", "no_of_bathrooms", "need_plumbing", "need_electricity", "need_paving", "need_painting", "need_carpentry", "need_plastering_cementing", "need_decorating", "include_materials", "need_installments", "max_installments", "min_installments", "brief_about_the_request", "expires_after_days", "location", ] But then I've added a nested Serializer to be able to see more details when I do a GET request, so now its is like : class RequestSerializer(serializers.ModelSerializer): """ Serializer for Request model """ location = CitySerializer(read_only=False) class Meta: """ Meta class for RequestSerializer """ model = Request ... This Line location = CitySerializer(read_only=False) Helped me to see more details in Get request but enable to post request. NOTE I have used it like location = CitySerializer(read_only=True) but also it returned this error : NOT NULL constraint failed: requests_request.location_id -
How to use a drop down and pagination without getting values reset while going back and forth through pages in DJANGO?
I have a form with a drop down to search. Drop down values help to search for a specific hostname (A field value in elasticsearch). When I go back and forth through pages while using the default dropdown value I don't get any error. But, When I am on page 2/5 (for default dropdown value) and then search for a new hostname my url returns http://localhost:8000/?page=2 and the new hostname in my views.py which is not what I want. In my Views.py if the request if GET (while using the Default hostname value / no form submission) my code goes to the else statement and when I search it goes to the IF statement (POST request with parameters) VIEWS.PY def check(request): if request.method == 'POST': host = request.POST['host'] rows = [] query = { "sort": {"@timestamp": {"order": "desc"}}, "size" : 10, "_source": ["data.service","data.policyid","data.srcuser"], "query":{ "bool": { "must": [ {"match_phrase": {"data.action": "deny"}}, {"match_phrase": {"data.devname": host}} ] } } } index_name = "mssp-stl.archives-2022.04.13" rel = es.search(index=index_name, body= query) data = rel['hits']['hits'] for i in data: row = { 'policyid' : i['_source']['data']['policyid'], 'service' : i['_source']['data']['service'] } rows.append(row) data = pd.DataFrame(rows) p = Paginator(rows, 2) page = request.GET.get('page') venues = p.get_page(page) return render(request, 'firewall_analyser/test.html', … -
how to reverse query set for m2m relation in Django and check if object exists
I need to check if an object exists in a reversed m2m Django relation. Models class PlayerProfile(models.Model): """ Player profile for every user - تحديد شكل كل لاعب خاص بكل مستخدم """ is_cap = models.BooleanField(default=False) app_user = models.ForeignKey("users.AppUser", on_delete=models.CASCADE,related_name="player_profile_list_for_app_user") t_shirt_size = models.ForeignKey(TShirtSize, on_delete=models.PROTECT) positions = models.ManyToManyField(Position) average_skill = models.PositiveIntegerField(null=True) region = models.ForeignKey(Region,on_delete=models.PROTECT,null=True) created = models.DateTimeField(auto_now_add=True) class Team(models.Model): """ Stores Available teams """ name = models.ForeignKey(TeamName, on_delete=models.CASCADE, related_name="team_set_for_name", verbose_name=_("Team Name"), help_text=("Name of the team")) home_strip = models.ForeignKey(TeamStrip, on_delete=models.CASCADE, related_name="team_set_for_home_teamstrip", verbose_name=_( "Team Home Strip"), help_text=("Home Shirt for the team")) away_strip = models.ForeignKey(TeamStrip, on_delete=models.CASCADE, related_name="team_set_for_away_teamstrip", verbose_name=_( "Team Away Strip"), help_text=("Away Shirt for the team")) league = models.ForeignKey("leagues.LeagueSeason", on_delete=models.CASCADE, related_name="team_set_for_league", null=True, verbose_name=_("League Seasson"), help_text=_("League seasson that team plays in ")) cap = models.ForeignKey("players.PlayerProfile", on_delete=models.CASCADE, related_name="team_set_for_cap_playerprofile", verbose_name=_("Team Captain"), help_text=_("Captain of the team")) players = models.ManyToManyField("players.PlayerProfile", blank=True, verbose_name=_( "Team Players"), help_text=_("Players that is playing in the team"), related_name="team_set_for_players") average_skill = models.DecimalField(max_digits=5, decimal_places=2, default=0, verbose_name=_( "Average Team Skill"), help_text=_("An Average of Player's skills")) points = models.PositiveIntegerField(default=0, verbose_name=_("Team Points"), help_text=_("Team points in the current league season")) Now the case that I have a Team Object and I need to queryset on PlayerProfile to return only playerProfile that belongs to that Team Objects based on the field ` Here … -
select titles from the same model in Django admin
I have an Article model with several fields. I want to enable users to link other articles (through selecting titles) to the current one. It must be done by users manually throughout the admin panel. The related_articles field should work exactly the same as ManyToManyField but it should refer to the current (Article) model. models.py class Article(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=400, blank=False, null=False, default='') slug = models.SlugField(unique=True, blank=True, max_length=400) author = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) body = RichTextField(blank=False, default='') case_studies = models.ManyToManyField(CaseStudie, blank=True, null=True) client = models.ManyToManyField(Client, blank=True, null=True) related_articles = models.ManyToManyField(Article, blank=True) # What should I put here? admin.py admin.site.register(Product) When I am trying to use Article in ManyToManyField it gives me an error: NameError: name 'Article' is not defined How can I solve this issue?