Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - UserManager(BaseUserManager)
Within the Django file /django/contrib/auth/models.py , in the class class UserManager(BaseUserManager): , have inserted the prints as seen below . Now creating new users - nothing gets printed in the terminal . My Question - Why wont the email and username print into the terminal ? Is the _create_user method not being used , when creating a new user? class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ print("--PlaceHolder----") # Doesnt Print in Terminal if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) print(email) # Doesnt Print in Terminal username = self.model.normalize_username(username) print(username) # Doesnt Print in Terminal I understand that the class class UserManager(BaseUserManager) is being called with the line of code objects = UserManager() within the class class AbstractUser(AbstractBaseUser, PermissionsMixin): , in the same file . This question is a follow-up to my earlier question here - Django - UserModel - How to create Custom Text Field within the django/contrib/auth/forms.py -
How do I get a context variable into a template tag in django - modifying Wagtail Menus template tag
I'm modifying the Wagtail Menus flatmenu template tag to accept a context variable instead of a string for the handle. The use case is that I want to pull in a specific menu based on a slugified version of a user's group name. The template looks like this: {% for group in user.groups.all %} {% with handle=group.name|slugify %} {% utility_flat_menu handle %} {% endwith %} {% endfor %} The templaet tags looks like: @register.simple_tag(takes_context=True) def utility_flat_menu( context, handle, max_levels=None, show_menu_heading=False, apply_active_classes=False, allow_repeating_parents=True, show_multiple_levels=True, template='', sub_menu_template='', sub_menu_templates=None, fall_back_to_default_site_menus=None, use_absolute_page_urls=False, add_sub_menus_inline=None, *args, **kwargs ): validate_supplied_values('flat_menu', max_levels=max_levels) if fall_back_to_default_site_menus is None: fall_back_to_default_site_menus = settings.FLAT_MENUS_FALL_BACK_TO_DEFAULT_SITE_MENUS if not show_multiple_levels: max_levels = 1 menu_class = settings.models.FLAT_MENU_MODEL return menu_class.render_from_tag( context=context, handle=context, fall_back_to_default_site_menus=fall_back_to_default_site_menus, max_levels=max_levels, apply_active_classes=apply_active_classes, allow_repeating_parents=allow_repeating_parents, use_absolute_page_urls=use_absolute_page_urls, add_sub_menus_inline=add_sub_menus_inline, template_name=template, sub_menu_template_name=sub_menu_template, sub_menu_template_names=split_if_string(sub_menu_templates), show_menu_heading=show_menu_heading, **kwargs ) That tag is a replacement for teh Wagtail Menus Flat Menu template tag found here: https://github.com/rkhleics/wagtailmenus/blob/1a938576adb801c455bea4b64906fb135c89f65f/wagtailmenus/templatetags/menu_tags.py#L46 So, what I'm trying to do is allow the handle to accept a context variable. I can for the life of me figure out how to get that to work. What you see for the handle = context is my guess at where the change needs to go, but I'm guessing. -
How to send sms messages with django and AWS SNS with phone numbers stored in a database
I am making an application with django that does the following, when a user presses a physical button , the button sends a POST request to django-rest which then creates a ticket , at the same time it creates the ticket it sends a sms notification to a phone stored in an SQL database . The phone number corresponds to someone who can help with the problem the user that pressed the button is having. I have tried to think how while handling the POST request in the server I can query the table that has the phone numbers and then with the phone number send the sms but I cant think of a way. I expect that when the user presses the physical button a support ticket is created and the person responsible for helping with the ticket recieves a sms notification on the phone. -
problem with passing parameter between two django template using include
I have created a 'more_btn' component like this. <div> <a href='{% url link %}' >{{ text }}</a> </div> and I want to reuse this component in two-parent components like bellow. {% include "util_components/more_btn.html" with link="job1" text="s1" %} {% include "util_components/more_btn.html" with link="job2" text="s2" %} the problem is that the URL block in 'a' tag in 'more btn' component wants an ID, not a string. How can I solve this? -
getting stats from relationship of django model
I have django model where i have requests and workers who working with this requests. So how i can get the all the requests of every worker for making stats here is my model class workers(models.Model): firstName = models.CharField(max_length=50, verbose_name="имя") lastName = models.CharField(max_length=50, verbose_name="фамилия") surnameName = models.CharField(max_length=50, verbose_name="отчество", blank=True) position = models.CharField(max_length=250, verbose_name="должность") class Meta: verbose_name = "работник" verbose_name_plural = "работники" def __str__(self): return "%s %s - %s" % (self.firstName, self.lastName, self.position) class requests(models.Model): name = models.CharField(max_length=50, verbose_name="название") description = models.CharField(max_length=300, verbose_name="описание") statusChoice = ( ("got", "Заявка получена"), ("processing", "Оброботка заявки"), ("started", "Выполняется работа"), ("ended", "Работа завершена"), ) status = models.CharField(max_length=30, verbose_name="статус", choices=statusChoice) client = models.ForeignKey(clients, on_delete=models.CASCADE, verbose_name="клиент") workers = models.ManyToManyField(workers, verbose_name="работники") requirements = models.ManyToManyField(requirements, verbose_name="требования") class Meta: verbose_name = "заявка" verbose_name_plural = "заявки" def __str__(self): return "%s %s - %s" % (self.name, self.description, self.status) -
And operator in a Django filter
I created a Django Rest Framework API endpoint. I would like this endpoint to retrieve all the records with the Status field set to Free, so i did this: queryset = tst.objects.using('screener').filter(Status=Free) Now, i want to retrieve not only the fields with the field set to Free, but also those with the status set to Pending. I tried this: class tstList(generics.ListCreateAPIView): criterion1 = Q(Status="Free") criterion2 = Q(Status="Pending") queryset = tst.objects.using('screener').filter(criterion1&criterion2) For some reason, this view will retrieve nothing. If i try the queries individually, though, they will work: queryset = tst.objects.using('screener').filter(criterion1) #works -
Autoposting to Facebook page from django-rest-framework app
I have a simple Django Rest Framework app running. I want to auto post to app's Facebook page whenever new item is saved in the db. I was wondering if Django management commands is the best solution. The other option is google cloud functions to make a request at specified time and post to Facebook if there are new items (could be expensive and unnecessarily complex). Any suggestions would be appreciated. -
Run bash script with Django on external Linux server
Good Guys, I am building an application with Django (Python), I really need a help to run a bash script on an external Linux server from my django web application. Can someone help me ? My django view is below, but only runs on the internal server. I need a view that runs to another external server. def teste(request): if request.POST: subprocess.call('/home/user/test.sh') return render(request,'teste.html',{}) -
How to display/render User's name stored in an external model without refreshing the page?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.employee_number This is the model where the name is stored alldata/models.py class Salesman(models.Model): slsmn_name = models.CharField(max_length=25) id = models.IntegerField(db_column='number', primary_key=True) I was reading … -
Django-models - display object in Django admin by FK description
I'm using the following models in Django: Model 1 class Location(models.Model): GID = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) fAccountGID = models.ForeignKey( Account, on_delete=models.CASCADE, verbose_name='Account code') MainDescription = models.CharField( verbose_name='Description/title', max_length=100) ... def __str__(self): return self.MainDescription Model 2 class Review(models.Model): Code = models.AutoField(primary_key=True) fLocationGID = models.ForeignKey( 'Location', on_delete=models.CASCADE, verbose_name='Location') ... def __str__(self): return 'Review for ' + self.FirstName When a review is saved in my database, in Django admin it is displayed as 'Review for ' + the FirstName: What would be the approach if I would like to display as 'Review for ' + 'MainDescription' from the Location model? Thanks -
django inlinecss not loading css file correctly
I'm using django-inlinecss to style emails. Here's a snippet of my email template: {% extends "base/email.html" %} {% block content %} {% load inlinecss %} {% inlinecss "base/css/email.css" %} <p class="c-c-test">test</p> {% endinlinecss %} {% endblock %} When rendering the template, an error occurs saying: No such file or directory: '/usr/src/project/static/base/css/email.css' Although, trying to use the same css file path (i.e. "base/css/emails.css") with static template tag works fine. What am I doing wrong here? -
Url filtering in Django Rest Framework
I created a Django Rest Framework API endpoint. Here is the view i created for my api endpoint: class myApiList(generics.ListCreateAPIView): queryset = tst.objects.using.all() serializer_class = mySerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('Status',) This code lets me add filters when retrieving data from the API endpoint using Jquery on a standard webpage. So, if on my page i want to show only the records with the status Free i will retrieve this endpoint: ("/myApi/?Status=Free") But what if i want to show not only the items with the status Free, but also those with the status Pending? I tried this, but it's not working, as it will only show the records with the status Pending ("/myApi/?Status=Free&Status=Pending") Is there a way to solve this? Should i change something in the URL or do i have to make some changes from my Django Backend? -
Is there any way to change the sorting in a django admin autocomplete field?
I have one model CompletedDiscipline and this model has a FK term_year. I'm trying to modify the ordering of this field, I don't want to use ordering in class_meta I tried to use formfield_for_foreignkey, it worked out in parts because autocomplete_fields doesn't let this method work well, is there any way to make it work? or override sorting within autocomplete def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'term_year': kwargs['queryset'] = TermYear.objects.order_by('term__course_offer__course__nome', 'year', 'number', 'term__name') return super().formfield_for_foreignkey(db_field, request, **kwargs) autocomplete_fields = [ 'student_curriculum', 'discipline', 'term_year', 'teacher', ] -
How to intialize form value to its previously submitted value in Django after pressing submit button?
I dont want to reset my form values after submitting through GET method. I want to put the same value as previous submitted value. -
Django can't import external libraries
So I am using Django version 2.26, and Python 3.7.3. Whenever I try to import or include an external library in my app within my project (specifically background_task in this case, but this error works with celery and a lot of others), it says 'no module named' even though it is installed. And when I run the Django shell and import it works. My settings.py file looks like this: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = # removed here # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ '*', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'background_task', 'projects', 'blog', 'landingpage', 'workspace', ] 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', ] ROOT_URLCONF = 'portfolio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["portfolio/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', ], }, }, ] WSGI_APPLICATION = 'portfolio.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, … -
How do I correct the following code in django, It's give an error "Forbidden (CSRF token missing or incorrect.)"
<script> var CSRF_TOKEN = '{{ csrf_token }}'; function getQuestion(str) { if(str!="select subject") { var req=new XMLHttpRequest(); req.open("post","/addQuestion/",true); str=encodeURIComponent(str); req.setRequestHeader("Content-type","application/x-www-form-urlencoded"); req.send("subject="+str); req.onreadystatechange=function() { if(req.status==200 && req.readyState==4) { document.getElementById("formdiv").innerHTML=req.responseText; document.getElementById("formdiv").style.overflowY="scroll"; } } } } </script> -
How to find the exact path requesting a Django api?
I want to get one single user of an user list by his id, to get his detail information. When I want to get the user list it works out fine. I have this path of the api docs: http://123//users/ and I can retrieve the list with this function in my front-end: private url = 'http://123'; // simplified for question ... // get a list of users getList(): Observable<any> { return this.http.get(`${this.url}/users`); } When it comes to get one user I have this path of the api docs: http://123//users/{id}/ while id is an integer. But when I want to get the user with this function: // get a user's profile getUserDetails(id): Observable<any> { return this.http.get(`${this.url}/users/${id}/`); } I get an 404 error and that the details were not found. Would the path in my function be correct to fetch the api data? Or am I doing something wrong? The strange thing is that it works with the list but not with one user, although I'm using the same scheme. -
How to display django category name instead of Category object (1)
Here is the problem. I've added a category section into my django blog. When I'm trying to add new category, there is a problem with user localization. When I'm adding the category, for example django, it shows like this: image 1 in the admin panel the same: image 2 but I actually add a normal category name: image 3 The funny thing is that, after I posted content with category in my web-app, it's looking normally: image 4 I want something like this, maybe someone have solution: wanted result Some code: models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) categories = models.ManyToManyField('Category', related_name='posts') image = models.ImageField(upload_to='images', default="images/None/no-img.jpg") def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): name = models.CharField(max_length=20) views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import Post from django.contrib.auth.models import User from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView def home(request): content = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', content) def blog_category(request, category): posts = Post.objects.filter(categories__name__contains=category).order_by('-date_posted') content = { 'category': category, 'posts': posts } return … -
Verify django loaddata progress
I'm trying to migrate from sqlite to a google managed postgres db. It worked locally with a postgres db that runs within docker, but when I try python manage.py loaddata db.json for the remote db the cursor just blinks forever but I don't know if something is happening. How can I verify that the process is doing something? I'm using cloud_sql_proxy to connect to the db. -
Is there a way to prompt the user for a value without refreshing the page from views.py in Django?
I'm currently attempting to modify a page that essentially keeps track of when a user enters/leaves an area. Currently all the logic works fine, but I would like to add the functionality to ask a user to enter their own estimate of the time they entered/left in the case they forgot to do so, since these instances get flagged upon submission. What I'm having trouble with, is actually getting the "popup" to display. I'm not sure how to accomplish this from the views.py, where I added the comment. I guess I need a way to just render that extra html on top of the page, without refreshing, until after they submit the edited_timestamp. I'm fairly new to Django/Python, and I have a very basic understanding of how this all works, so I apologize in advance if my suggestions on handling this are a bit off. These is a summarized version of what the models look like: models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) edited_timestamp = models.DateTimeField(null=True, blank=True) time_exceptions = models.CharField(max_length=2, blank=True) time_in = models.DateTimeField(help_text="Time in", null=True, blank=True) … -
Extremely slow queryset lookup in Django with mysql as backend DB
My view has a search bar, which searches extremely slowly. There are four tables that I'm trying to pull information from Restaurant, Food, Menu, Quality. The view sent a pk for food. I also have a local_zip and radius variable to find restaurant near a user. I use this to limit the number of restaurants. Then, I filter the objects by food selected and restaurants near them. Then I pull some quality info on the restaurants. When I run it in the shell, it's actually normal speed. No one line takes super long, not sure why it's so slow on the server. Here is the code that I runs very slowly: local_zip = request.session['local_zip'] radius = request.session['radius'] in_radius = [z.zip for z in zcdb.get_zipcodes_around_radius(local_zip, radius)] list_ids = ['13', '427', '428'] #('ZIP', radius in miles) # Restaurants table has about 500 observations find_objects = Restaurants.objects.filter(Q(zipcode__in=in_radius) | Q(id__in=list_ids)).distinct() # Menu table is large with about a million observation objects_selected = Food.objects.filter(menu__menuid=pk) table = objects_selected.filter(restaurants__in=find_objects).order_by('price').prefetch_related('restaurants') #Food table has 10k objects food_info = Food.objects.filter(foodid=pk) # quality has about 600K objects quality_info = Quality.objects.filter(food__foodid=pk,locality = str(5))[:1] -
How to Set Multi-Select choices in admin django
I have a model class Event(models.Model): event_name = models.CharField(max_length=100, default="") event_organizer = models.ForeignKey(Organizer, on_delete=models.CASCADE) event_type = models.ForeignKey(Type, on_delete=models.CASCADE) event_city = models.ForeignKey(Citie, on_delete=models.CASCADE) event_tag = models.ForeignKey(Tag, on_delete=models.CASCADE) I have a field event_tag. During add event form in admin panel i want to select multiple tags. how to do that and how to save them -
unable to auto-fill data during update in dependent dropdowns
So I have been following this tutorial related to dependent dropdowns which can be found here and I seem to have gotten stuck at the last part the else if statement and am unable to implement the same in my project postlog models.py: from django.db import models # Create your models here. class FlightNum(models.Model): fl_no =models.CharField(max_length=5,primary_key=True) def __str__(self): return self.fl_no class Destination(models.Model): fl_no= models.OneToOneField(FlightNum,on_delete=models.CASCADE,related_name='fl1') dest= models.CharField(max_length=15,blank=True) def __str__(self): return self.dest class Parking(models.Model): fl_no= models.OneToOneField(FlightNum,on_delete=models.CASCADE,related_name='fl2') park_bay= models.CharField(max_length=3) def __str__(self): return self.park_bay class DepartureTime(models.Model): fl_no= models.OneToOneField(FlightNum,on_delete=models.CASCADE,related_name='fl3') dep_time= models.CharField(max_length=9) def __str__(self): return self.dep_time class Flight(models.Model): fl_no= models.OneToOneField(FlightNum,on_delete=models.CASCADE, primary_key=True, related_name='fl4') park_bay= models.ForeignKey(Parking, on_delete=models.CASCADE) dest= models.ForeignKey(Destination, on_delete=models.CASCADE) dep_time= models.ForeignKey(DepartureTime, on_delete=models.CASCADE) inbound= models.CharField(max_length=15,blank=True) airline= models.CharField(max_length=15) arr_time= models.TimeField() status models.py: from django.db import models from postlog.models import FlightNum,Destination,Parking,DepartureTime # Create your models here. class FlightStatus(models.Model): CLEANING_CHOICES = ( ('Yes', 'Yes'), ('No','No'), ) fl_no= models.OneToOneField(FlightNum,on_delete=models.CASCADE,related_name='fli_no',primary_key=True) park_bay= models.ForeignKey(Parking,on_delete=models.CASCADE,related_name='parki_bay') catering= models.CharField(max_length=9) fuel= models.IntegerField() pas_cnt= models.IntegerField() dest= models.ForeignKey(Destination,on_delete=models.CASCADE,related_name='desti',null=True) dep_time=models.ForeignKey(DepartureTime,on_delete=models.CASCADE,related_name='dept_time') Cleaning = models.CharField( max_length=3, choices=CLEANING_CHOICES) status forms.py: from django.forms import ModelForm from status.models import FlightStatus from postlog.models import FlightNum,Destination,Parking,DepartureTime class StatusForm(ModelForm): class Meta: model = FlightStatus fields = ('fl_no', 'park_bay', 'catering', 'fuel', 'pas_cnt', 'dest','dep_time', 'Cleaning') labels = { 'fl_no': ('Flight Number'), 'park_bay': ('Parking Bay'), 'catering': ('Catering'), 'fuel': ('Fuel'), 'pas_cnt': ('Passenger Count'), 'dest': … -
Extract the coordinates from the LineStringField
I've this simple model from GeoDjango for a line vector: from django.contrib.gis.db import models class LineBuffer(models.Model): geom = models.LineStringField() def __int__(self): return self.pk @property def coordinates(self): return str(self.geom.x) + ', ' + str(self.geom.y) I need to create a buffer using Turf.js; the results will be redered using MapBox. With this view I create my map: def line_mapbox_turf_buffer(request): geometry = LineBuffer.objects.all() context = { 'geometry': geometry, } template = 'buffer/reading/line_mapbox_turf_buffer.html' return render(request, template, context) I try to generate the GeoJSON var data_source = { "type": "FeatureCollection", "features": [{% for d in geometry %} { "type": "Feature", "properties": { "pk": "{{ d.pk }}" }, "geometry": { "type": "LineString", "coordinates": [{{ d.coordinates }}] } {% if forloop.last %}} {% else %}}, {% endif %}{% endfor %} ] } But I see this: { "type": "Feature", "properties": { "pk": "1" }, "geometry": { "type": "LineString", "coordinates": [ [14.364295, 14.3662612, 14.3681209, 14.3702697, 14.3730481, 14.3742791, 14.3763224], [40.8086793, 40.8101317, 40.8118721, 40.8139257, 40.8165981, 40.8177693, 40.8206666] ] } } Instead of this: { "type": "Feature", "properties": { "pk": "1" }, "geometry": { "type": "LineString", "coordinates": [ [14.364295,40.8086793], [14.3662612,40.8101317], [14.3681209,40.8118721], [14.3702697,40.8139257], [14.3730481,40.8165981], [14.3742791,40.8177693], [14.3763224,40.8206666] ] } } I think that my problem is the property coordinates. How I can extract … -
End an event at midnight with Python and Django
Guys, I'm working on a project on which Python 2.7 and Django 1.11.26 are used I need to make a change to a condition where events are discarded at the actual event starting time and make them discard at the end of the day (midnight) this is the line of code concerned: show_card = lambda card: card.item.start_datetime >= timezone.now()