Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overriding Django RelatedManager and Queryset to filter on a field in the Through Model
I have two models that are linked via Many-To-Many field via third Through Model. The Through Model has some extra fields in it. I want to override the RelatedManager to produce some custom QuerySets that use the extra fields in the Through Model. The caveat is that my Through Model is created using a subclass/mixin that defines the extra fields. What I want to be able to do is get all the Gene objects related to the SampleBatch that have an active status of 1 in the SampleBatchGene instances linking the Many-to-Many fields: In [1]: SampleBatch.objects.get(sample__lab_number="18_11998").genes.active() Out[1]: <QuerySet [<Gene: BAP1>]> This is what I have so far: class SampleBatch(models.Model): sample = models.ForeignKey(Sample, on_delete=models.CASCADE) batch = models.ForeignKey(Batch, on_delete=models.CASCADE) genes = models.ManyToManyField( "Gene", through='SampleBatchGene', related_name='samplebatches', blank=True, through_fields=('samplebatch', 'gene') ) class Meta: managed = True db_table = 'sample_batch' unique_together = (('sample', 'batch'),) verbose_name_plural = "Sample batches" def __str__(self): return '{}-{}'.format(self.sample, self.batch) class Gene(models.Model): gene_id = models.BigAutoField(primary_key=True) gene_name = models.CharField(unique=True, max_length=255, db_index=True) hgnc_number = models.IntegerField(unique=True, db_index=True) class Meta: managed = True db_table = 'gene' def __str__(self): return self.gene_name class ActiveQuerySet(models.QuerySet): def active(self): return self.filter(active=1) def inactive(self): return self.filter(active=0) class LinkMixin(models.Model): ACTIVE_CHOICES = ( (0, 'Inactive'), (1, 'Active') ) activated = models.DateTimeField(default=timezone.now) active = models.IntegerField( … -
django unable to show search result
I'm trying to do a search function on my home page. What it should does is that when the user clicked the on the Search button, the url should change from http://127.0.0.1:8000/ to http://127.0.0.1:8000/search.html and return the search result. Currently after pressing the search button it still stays at the home page and does not show the search result. I dont know what went wrong. views.py class HomeView(ListView): model = Item paginate_by = 10 template_name = "home.html" def SearchFilter(request, Item): items = Item.objects.all() myFilter = ItemFilter(request.GET, queryset=items) items = myFilter.qs context = { 'Item': items, 'myfilter': myFilter } return render(request, "search.html", context) filters.py import django_filters from .models import * class ItemFilter(django_filters.FilterSet): class Meta: model = Item fields = { 'title': ['icontains'], 'price': ['exact', 'contains'], 'discount_price': ['exact', 'contains'], 'category': ['exact', 'contains'], } home.html <form class="form-inline" method="get"> <div class="md-form my-0"> {{myFilter.form}} <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search"> <button class="btn btn-primary" type="submit">Search</button> </div> </form> -
Python Sending email
I have this code for sending emails. An email is supposed to be sent to an Admin when a staff applies for leave and another one back to the staff as soon as the leave application is processed. I have the first part working ok. An admin user is indeed receiving the leave application email but once they processes it, the staff isnt receiving the feedback email. I suspect am getting it wrong how am grabbing the user email from the leave_obj but can figure out any other way. To the best of my knowledge user.email should work since there's a foreign key relationship between the leave, employee and user models. What am I missing? Below is all my relevant code. send_email function: def send_email( name: str, email: str, subject: str, message: str, obj: object = None, cc_list: list = None, template: str = "generic", template_path: str = "C:/Projects/hr_app/humanresource/src/templates/email", ): context = { "name": name, "subject": subject, "message": message, "object": obj, "SITE": Site.objects.get_current(), } email_subject = render_to_string( f"{template_path}/{template}_email_subject.txt", context ).replace("\n", "") email_txt_body = render_to_string( f"{template_path}/{template}_email_body.txt", context ) email_html_body = render_to_string( f"{template_path}/{template}_email_body.html", context ).replace("\n", "") subject = email_subject from_email = settings.DEFAULT_FROM_EMAIL to_email = f"{name} <{email}>" text_content = email_txt_body html_content = email_html_body … -
Django flatpages The empty path didn't match any of these
On the administration page, I set the URL for the Django flat pages to "/", which is expected to be displayed as the home page at http://127.0.0.1:8000/. Doing so I encountered an error: Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in core.urls, Django tried these URL patterns, in this order: admin/ <path:url> The empty path didn't match any of these. But if I go to http://127.0.0.1:8000// with double slash then the home page is displayed correctly. My only urls.py file looks like this: from django.contrib import admin from django.urls import include, path from django.contrib.flatpages import views urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += [ path('<path:url>', views.flatpage), ] And I took all the code completely from the official guide. How to display the django flatpage homepage at http://127.0.0.1:8000/? -
Celery/Kombu SimpleQueue.get() never returns even when message appears in queue. Why?
This has taken some time to nail this far and gets more mysterious with every step. I'm using a Kombu SimpleQueue quite effectively to send messages to a Celery task. I though all my problems solved to be honest as that's what I need and SimpleQueue delivers it elegantly. Until ... To put it into context, I have a Django site, and a Celery task all working beautifully together. I can put a message on the queue and read it as follows: from time import sleep from celery import current_app from celery.utils.log import get_logger from kombu.simple import SimpleQueue logger = get_logger(__name__) def q_name(task_id): return f'MySimpleQueueFor_{task_id}' def send_to_task(task_id, message): with Connection(current_app.conf.broker_write_url) as conn: q = conn.SimpleQueue(q_name(task_id)) q.put(message) print(f'Sent: {message} to {q_name(task_id)}') q.close() def check_for_message(q, task_id): try: message = q.get_nowait() # Raises an Empty exception if the Queue is empty payload = message.payload message.ack() # remove message from queue q.close() return payload except q.Empty: return None @app.task(bind=True) def my_task(self, *args, **kwargs): with Connection(current_app.conf.broker_read_url) as conn: task_id = self.request.id q = conn.SimpleQueue(q_name(task_id)) while True: message = check_for_message(q, task_id) logger.info(f'Received: {message} from {q.name}') sleep(0.1) With a task_id in hand I can send any message to the task I and I can see the messages … -
A Different Way to Write =>
I don't understand how this function works. And would like the "novice," more detailed approach to specifically replace "=>" in the code. Thanks for helping a newbie! def __str__(self): return f"User: {self.observer.pk} => Habit: {self.habit.pk}" -
'AnonymousUser' object has no attribute '_meta' error in Django login function
I'm having problem in the built-in login function in Django. Here is the views.py code: def login_page(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid: user = form.get_user() login(request, user) return redirect('index') else: form = AuthenticationForm() return render(request, 'login.html', {'form':form}) And below is my html code. <form action="{% url 'login' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Log in"> </form> As soon as I click the 'Log in' button, it gives an error that says: 'AnonymousUser' object has no attribute '_meta' I don't see which part is wrong. I very much appreciate your help. :) -
{**Defaults, **url_pattern.default_kwargs}, TypeError: 'function' object is not a mapping
urlpatterns = [ path('admin/', admin.site.urls), path('home/', include('CORE_INDEX.core_index_urls')), path('about/', include('CORE_INDEX.core_index_urls')), path('privacy/', include('CORE_INDEX.core_index_urls')), path('player/', include('PLAYER.player_urls')), path('member/', include('MEMBER.member_urls')), ] Error: {**defaults, **url_pattern.default_kwargs}, TypeError: 'function' object is not a mapping [09/Mar/2020 10:41:16] "GET /admin/ HTTP/1.1" 500 121679 -
Not able to display images from static folder using Django
This is my home.html I'm not able to display the images in static/images/ folder. Although *[09/Mar/2020 15:52:09] "GET /static/images/mona.jpg HTTP/1.1" 404 1669 * is displayed in terminal. <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {% block content %} {% load static %} <title>Home</title> <link rel="stylesheet" href={% static '/css/style.css' %} /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </head> <body> {% include "includes/header.html" %} <div class="pt-5"> <div class="card d-inline-block"> <img src={% static 'images/mona.jpeg' %} alt="Avatar" style="width:100%;"> <div class="container"> <h4><b>Mona Lisa</b></h4> <p><a href="#">Architect & Engineer</a></p> </div> </div> <div class="card d-inline-block"> <img src={% static "images/mona.jpg" %} alt="Avatar" style="width:100%"> <div class="container"> <h4><b>The Scream</b></h4> <p><a href="#">Architect & Engineer</a></p> </div> </div> </div> {% include "includes/footer.html" %} {% endblock content %} </body> -
Django how to show modal after the user's updating their data
I hope my title is enough to understand what my problem is, i have this code in my html <form method="post" action="/reactivate/" onsubmit="openModal()" id="myForm" enctype="multipart/form-data" autocomplete="on">{% csrf_token %} {% for me in ako %} Date: <input type="hidden" value="{{me.enddate}}" name="date" id="start_date">{{me.enddate}} <input type="hidden" value="{{me.id}}" name="id" hidden><p>{{me.Email}}</p> {% endfor %} <select id="days"> {% for perfume in s %} <option value="{{perfume.adddate}}" data-days="{{perfume.adddate}}" id="days">{{perfume.product}} - {{perfume.adddate}} Days</option> {% endfor %} </select> <br><br><br> <label>Deadline:</label><br> <input type="date" name="endate" id="end_date" readonly/> <input type="submit" value="Sign up"/> </form> this is my modal code in html <div class="modal fade" tabindex="-1" role="dialog" id="myModal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> <p>One fine body&hellip;</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> I want to show this modal when after the user update the date and this is my views.py def reactivate(request): id = request.POST.get('id') date = request.POST.get('endate') update = User.objects.get(id=id) update.enddate = date update.save() the error says this is my script <script> $('#myForm').on('submit', function(e){ $('#myModal').modal('show'); e.preventDefault(); }); </script> -
DateTimeField widget in django isn't saving the data. It keeps on saying enter valid date and time
I am following this tutorial : Simple is better than complex to add a datetimepicker widget to a django crispy form. The icon appears in the form and the date and time gets filled in the field as shown in the picture below : But it keeps on asking me to enter a valid date and time when I try to submit the form as shown below: My model looks as follows models.py class Ads(models.Model): company_name = models.CharField(max_length=50) # Company Name image = models.ImageField( upload_to='ad_images/',blank = True, null= True) # Adding multiple image according to device?? # Header, Content, Sidebar AD_CHOICES = ( ('H','header'), ('C','content'), ('S','sidebar'), ) ad_position = models.CharField(max_length=2, choices= AD_CHOICES, default='H') # profile_pic_status = models.BooleanField(default=True) # use duration field to decide which ad gets placed duration_start = models.DateTimeField(default=timezone.now) duration_end = models.DateTimeField(default=timezone.now) clicks = models.IntegerField(default = 0) url = models.CharField(max_length=50) # Add display status boolean data type to represent whether that image is the profile pic def __str__(self): return self.company_name My form looks like this: forms.my from django import forms from .models import Ads from .widgets import BootstrapDateTimePickerInput class PostForm(forms.ModelForm): duration_start = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput()) duration_end = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput()) class Meta: model = Ads fields = ['company_name', 'image', … -
How to fix DateRangeFilter in order the date widjet to appear properly
Using adminactions to my project I came up with the problem that my date widjet(the calendar) is not appearing to my form at all. I successfully install the django-admin-rangefilter and import it as well. my model class Order(models.Model): stem_date = models.DateField("STEM") delivery_date = models.DateField("Delivery Date") my admin.py from rangefilter.filter import DateRangeFilter, DateTimeRangeFilter list_filter = [('stem_date', DateRangeFilter), ('delivery_date', DateRangeFilter), ('cost_center')] I am using django version = 2.2.6 and python version 3.5.2 Have anyone any idea why my widjet is not loaded at all? -
static files problem, everything is loaded except some files style.css and js
my template didn't work and can't get static files but I did everything. I just can't get style.css but other files are loaded. only style and some js files isn't loaded but the path is not wrong . please help me this is an image of my folder and project tree Settings for Static and media. STATIC_URL = '/temfiles/' MEDIA_URL = '/mediafiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'static/uploads/') X_FRAME_OPTIONS = 'SAMEORIGIN' my project URL file urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('froala_editor/', include('froala_editor.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my app URL file urlpatterns = [ path('', views.index, name = 'index'), path('<slug:slug>/', views.post_detail, name='Post Detail') ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my Views File def index(request): Post_list = BlogPost.objects.all() template_name = 'front/index.html' return render(request, template_name,{"Post_list":Post_list}) def post_detail(request): return render(request, 'front/post_detail.html') my base template CSS example {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'front/css/style.css' %}"> Static Directory Tree image static directory tree with open folders browser inspect terminal picture style CSS URL in browser MY urls.py for static and media root -
Django got an unexpected keyword argument after solving 'collections.OrderedDict' object has no attribute
I am trying to solve the error: AttributeError: 'collections.OrderedDict' object has no attribute 'group_pk' when trying to add an url field to a serializer class in django. I read that I need to save my serializer data so I added serializer.save() before return serializer.data When I do that I get the error: Django got an unexpected keyword argument "linked_sites" I'm now facing this problem for 2 days, seems like its returning with more people. Here is my code: part of test-class: # New group name new_name = "New group name" sites = [self.test_site_3.pk] # Execute the patch operation response = self.client.patch( url, data={"name": new_name, "linked_sites": sites} ) # Test if there was no error self.assertEqual(response.status_code, status.HTTP_200_OK) serializer: class GroupPatchSerializer(serializers.ModelSerializer): linked_sites = serializers.ListField() name = serializers.CharField(required=False) url = serializers.HyperlinkedIdentityField( view_name="group-detail", lookup_field="group_pk", read_only=True ) class Meta: model = Group fields = ("id", "url", "name", "linked_sites") def validate_linked_sites(self, sites): def validate_name(self, name): view: def patch(self, request, group_pk): """ Add site to group, change an existing group's name. -id: The group's id """ user = request.user group_id = int(group_pk) group = Group.objects.filter(pk=group_id).first() # Check if the user has permission to edit the group details if not UserSiteGroup.objects.filter( usersite__user=user.id, group=group_pk ).exists(): raise PermissionDenied( "The user … -
Django how to set url based on model item.title?
I'm trying to create a very basic search like feature but I had no clue on how to do it. Appreciate if anyone could provide any source of help or information. I tried to use something like "{% url 'product' item.title %}" but it return an error Reverse for 'product' not found. 'product' is not a valid view function or pattern name. The end result is when the user click on the shirts tag, the home page should only show results related to shirts home.html <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">All <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">Shirts</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Sport wears</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Outwears</a> </li> </ul> urls.py urlpatterns = [ path('', HomeView.as_view(), name='home'), path('product/<slug>/', ItemDetailView.as_view(), name='product') ] models.py class Item(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() def __str__(self): return self.title[enter image description here][1] -
How can I implement choice field in django model?
I want to develop a pigeon app in django and my pigeon model has status field. For this I must define another model called Status where to store my statuses. My model class PigeonStatus(models.Model): STATUSES = [ ('Activ', 'Activ'), ('Lost', 'Lost'), ('Dead', 'Dead'), ('For Sale', 'For Sale') ] status = models.CharField(max_length=15, choices=STATUSES, unique=True) in_loft = models.BooleanField('In loft?') def __str__(self): return self.status class Pigeon(models.Model): pigeon_id = models.AutoField(primary_key=True) year = models.CharField(max_length=4, null=False, blank=False) band = models.CharField(max_length=25, null=False, blank=False, unique=True) ... status = models.ForeignKey(PigeonStatus, on_delete=models.CASCADE, null=False, blank=False) My question is how can I set boolean value for every status? I want to query like this: Pigeon.status.in_loft = true. From choices, Activ and For Sale must have in_loft=True and Lost, Dead must have in_loft=False. Does anyone can answer this? Is there another way(better one maybe) to set pigeon status and refer to it later? Thanks! -
Why do I get QuerySet object has no attribute user
I am working on a website using Django, where users can send friend request to another user and I came up with an error on my code. Queryset object has no attribute user. def home(request): p = Profile.objects.exclude(user=request.user) u = p.user sent_request = FriendRequest.objects.filter(from_user=p.user) button_status = 'none' if p not in request.user.profile.friends.all() button_status = 'not_friend' if len(FriendRequest.objects.filter(from_uset=request.user).filter(to_user=p.user)) == 1: button_status='add_request' if len(FriendRequest.objects.filter(from_user=p.user).filter(to_user=request.user)) == 1: button_status='accept_request' -
Setting up CI/CD on Gitlab for django project
This is the first time I've tried adding CI/CD for a Django project on gitlab. I want to set up automatic testing and deploying to the server in the development branch if it is successful. With tests almost everything worked out, dependencies are installed and started python manage.py test but the problem with the testing database. The traceback error is a bit lower and here I don't quite understand how the interaction with the database happens during the tests. Creating test database for alias 'default'... ..... MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (115)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main ... super(Connection, self).__init__(*args, **kwargs2) django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (115)") In the settings of django settings.py, a connector to the database is obtained through such variables in a .env file. .env SECRET_KEY=ja-t8ihm#h68rtytii5vw67*o8=o)=tmojpov)9)^$h%9#16v& DEBUG=True DB_NAME=db_name DB_USER=username DB_PASSWORD=dbpass DB_HOST=127.0.0.1 And with the deployment of the project, everything is not clear yet. I'd appreciate your help setting it up. gitlab-ci.yml stages: - test - deploy test: stage: test script: - apt update -qy - … -
How to unit test django application using jena-fuseki?
My django application uses sparql with jena-fuseki RDF-database. How should I run my unit tests as thete's hardly any information in availble for creatig in-memory jena database for a django unittesting ? So far I've been just running a local fuseki-server, but that's not the way unit testing should be done, right ? -
How can i change the currency symbol in the modal of Stripe API , using DJANGO
Can't change the highlighted dollar symbol -
How to correctly separate models into multiple files in Django?
I have one app and one model's file at this point but at the same time I have two databases and the third is upcoming soon. My databases have a few same models and I want to separate them in different files. I saw a few answers here but they are 8 years old. Can someone show it step by step how to do it? I'm using the latest versions of Python and Django as well. -
Multi-tenancy on Django 3.0 with MariaDB and separate databases
We are building a new system on Django 3.0 that requires multi-tenancy with separate databases, and we also intend to use Maria DB. I have already gone through a well-known multi-tenancy solution django-tenant-schemas that offers multi-tenancy with single PostgreSQL database and multiple schemas - so that doesn't solve our problem (Django 3.0 + Maria DB & multiple databases). From what I have understood, it is non-trivial to make changes in Django ORM to change the DB, so I am looking for some other solution. How can I have multi-tenancy with DJango 3.0 if we want to use multiple database with Maria DB? -
two foreign keys in one django model
i'm working on a project the scenario : teacher model then is the teacher has not a profile the institute which working at will upload the courses does this is write way i have tried in the course model? class Course(models.Model): course_name = models.CharField(max_length=20) student = models.ManyToMany(Student) institute_name = models.ForeignKey(Institute,on_delete=models.CASCADE , null=True,blank=True) teacher_name = models.ForeignKey(Teacher ,on_delete=models.CASCADE,blank=True,null=True) tags = models.ManyToManyField(Category,on_delete=models.CASCADE) time = models.DateTimeField(auto_now=True) update = models.DateTimeField(auto_now_add=True) then define if user loggedin in user.is_institute so querying on institute if loggedin in user.teacher then will work on teacher model ! does this structure fork fine ? i know generic foreign keys from django.contrib.contenttypes.models import ContentType but i've hear this will not work with API django:2.2 -
Unable to delete django background tasks
We use django-background-tasks in our application and I have had no issue with deleting tasks from the admin page when running the app in my system. But when I tried to delete some tasks from the production version (hosted with gcp), I keep getting internal server (500) errors. What could be the reason for this? Alternately, is it advisable/safe to directly delete the tasks from the background_task table in the database? -
django distinct in template by filter
I need to display unique values in template. I know distinct will work in query. But table in one row Many to Many field I don't know how to implement for that. If any possibilities are there to use it in template class DoctorFeedback(models.Model): visited_for = models.CharField(max_length=200) tag = models.ManyToManyField(Tags) class Tags(models.Model): tag_title = models.CharField(max_length=50)