Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django's LoginView doesn't accept custom AuthenticationForm
I have a class LoginForm which is a subclass of Django's AuthenticationForm. In urls.py there is the following line for routing to auth_views.LoginView: from django.contrib.auth import views as auth_views from my_app.forms import LoginForm url(r'^login/', auth_views.LoginView.as_view(authentication_form=LoginForm), name='login'), As you can see, I've been trying to replace the default AuthenticationForm with my LoginForm by using the authentication_form keyword argument mentioned in the Django documentation but the LoginView will still display the default AuthenticationForm. What am I missing? -
How to refresh the selection box when new option is added in Django?
I have a form with a selection box related to a foreign key (for example, category). And on the same page, I have another link that opens a new page to add a new instance of the foreign key. Once the new instance is added, how can I update the current form to add the new option, and preserve the text in the text field (just like how the admin page behaves)? -
Django query add counter
I have 3 tables: Truck with the fields: id, name.... Menu with the fields: id, itemname, id_foodtype, id_truck... Foodtype with the fields: id, type... And I have a query like this: SELECT ft.id, ft.name, COUNT(me.id) total FROM foodtype ft LEFT JOIN menu me ON ft.id = me.id_foodtype LEFT JOIN truck tr ON tr.id = me.id_truck AND tr.id = 3 GROUP BY ft.id, ft.name ORDER BY ft.name And returns something like: id name total 10 Alcoholic drink 0 5 Appetizer 11 My problem is to return the results with 0 elements. At the moment to convert this query to Python code, any of my queries return the exact result than I expected. How I can return the results with the Left Join including the foodtypes with zero elements in themenu`? -
Django Annotating Model with Count() by Chaining related_name Lookups
So I would like to use Count() to aggregate the number of Listings that I have through multiple related_name lookups. For example: Category.objects.annotate(listings_count=Count(productsAsCategory__listingsAsProduct)) ^ This only works if I use Count(productsAsCategory), but chaining it with another field (as done above) doesn't return anything. models.py: class Category(models.Model): [...] class Product(models.Model): category = models.ForeignKey(Category, related_name='productsAsCategory') [...] class Listing(models.Model): product = models.ForeignKey(Product, related_name='listingsAsProduct') [...] -
Pass value to Django model attribute
I am building a file upload page where files will be saved with a different prefix in their name (get_file_path function uses instance.mname) but will go through the same upload model/form. I want the prefix to be declared in the views in form in mname='prefix'. How can I pass this value from views to form? Thank you! models.py class Upload(models.Model): mname = ###need it to be passed#### document = models.FileField(upload_to=get_file_path, validators=[validate_file_extension]) upload_date=models.DateTimeField(auto_now_add =True) forms.py class UploadForm(forms.ModelForm): class Meta: model = Upload fields = ('document',) views.py def uploadFile(request): if request.method == "POST": file = UploadForm(request.POST, request.FILES, mname='....') if file.is_valid(): file.save() -
Add extra metadata to model info Django returns for OPTIONS
In my Django application I have a list of Event_Types that users can subscribe to. Pretty simple with: event_type = models.CharField(choices=EVENT_TYPES, max_length=128) And the UI gets a list of available event types when it calls OPTIONS. The challenge is that certain levels of permissions open up additional choices. So the UI sees a bunch of event types that are unavailable to that user. It's not a security concern to know that the options are there, but it requires per-event_type filtering in the UI, which I would like to rather be driven by the OPTIONS. Is there a way to manually add metadata to what OPTIONS returns? -
How to display the data contained in Django models in a Django Dropdown menu form?
Currently, I have some data stored in a Django model with the following structure: #Django model from django.db import models class Customer(models.Model): first_name = models.Charfield(max_length = 120, null = False, blank = False) last_name = models.Charfield(max_length = 120, null = False, blank = False) def __str__(self): return self.first_name+ " " + self.last_name I want to display all the customers that are stored in the Customer model in the DropDown menu form. What I tried was the following but I've got no success: #Django form from .models import Customer # This throws as a result <Django.db.models.query.utils.deferred.attribute at 0x00013F> inside of the DropDown Menu form class DropDownMenuCustomer(forms.Form): Customer = forms.ChoiceField(choices=[(x,x) for x in str(Customer.first_name)+str(" ")+ str(Customer.last_name))]) Another possibility without success was: #Django form from .models import Customer class DropDownMenuCustomer(forms.Form): querySet = Customer.objects.all() list_of_customers = [] for customer in querySet: list_of_customers.append(customer.first_name + " " + customer.last_name) customer= forms.ChoiceField(choices=[(x) for x in list_of_customers)]) This last possibility does not find list_of_customers, just as if the variable has not been declared. How can I display the data stored in the Django models in the Django forms? -
Django TypeError 'NoneType' when adding objects to ManyToMany field
I'm trying to add an app to my Django project called "clinicaltrials" (CT) that stores data from the clinicaltrial.gov API. Each trial may have multiple collaborators and multiple diseases, so I've set up additional models for them with a ManyToManyField. (note: I originally tried to connect CT directly to my Company model, however not all possible companies are in my database so I'm capturing names as well in the CT model) The problem I'm running into is when I try to add the CT record to either of the additional models I get an error TypeError: 'NoneType' object is not iterable. I would think that looking it up by pk as I'm doing would work. This is my first time using a ManyToManyField and I've been wresting this for the past two days. Where am I going wrong here? This is the function that I'm using to write to the models: def write_database(data): for trial in range(len(data)): # if the trial exists in the database continue to the next one if ClinicalTrial.objects.filter(nct_id=data[trial].get('nct_id')).exists(): continue # create list of collaborators for later if data[trial].get('collaborators') is not None: collaborators = [] collaborator_len = len(data[trial].get('collaborators')) for x in range(collaborator_len): collaborators.append(data[trial].get('collaborators')[x].get('name')) else: collaborators = None … -
getting value and summation from relationship tables on django
I have tow modules (classes) on python django like this sample bellow : #first one class Names(models.Model): name = models.CharField(max_length=200) type = models.ForeignKey(Types) value = models.IntegerField() #second one class Type(models.Model): name = models.CharField(max_length=200) as you see, the class names have relationship with class type so how to make a formula to get the total number of names and the summation of values in every class of type to get result something like this for example : type1_total_names = 4 type1_sum_val = 22 -
Django won't display image from database in HTML
Hi I am trying to get user profile images to display from a Django MySQL database corresponding to the user that is logged in.. Here is my settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR,'media') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR, ] # Media files MEDIA_ROOT = MEDIA_DIR #MEDIA_DIRS = [MEDIA_DIR, ] MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/admin/media/' Here is my urls.py: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^smartcity/',include('smartcity.urls')), #url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'), #url(r'^accounts/register/$', views.register, name='registration'), url(r'^accounts/', include('registration.backends.simple.urls')), url(r'^admin/', admin.site.urls), url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), ] And this is what I have in the html file: src="{% static 'user.userprofile.picture.url' %}" This is my table i am trying to retrieve the picture from: Database screenshot I'm not sure how to get it to display, I thought my URL mapping was correct as i can view the image if i go to http://127.0.0.1:8000/media/profile_images/trump.jpg Any ideas? Sorry I am a bit of noobie. -
'Options' object has no attribute 'get_all_related_objects' but I'm already using Django 1.11
I keep getting an 'Options' object has no attribute 'get_all_related_objects' error. I've researched and people say it is often an issue with using an old version of django, but I'm using 1.11.6 when I navigate to the url: app/employees I get this error. What am I doing wrong? Django Version: 1.11.6 Exception Type: AttributeError Exception Value: 'Options' object has no attribute 'get_all_related_objects' other version numbers: python: 2.7.14 rest framework: 3.1.1 virtualenv: 12.1.1 app/model: class Employee(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) supervisor = models.ForeignKey('self', blank=True, null=True) is_active = models.BooleanField(default=True) is_supervisor = models.BooleanField(default=False) class Meta: ordering = ('last_name',) def __str__(self): return "{}".format(self.first_name + ' ' + self.last_name) app/serializer: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee app/api.py: class EmployeeApi(ListAPIView): queryset = Employee.objects.all() serializer_class = EmployeeSerializer app/url.py urlpatterns = [ ... url(r'^employees$', EmployeeApi.as_view()), ] -
Create subdomain progamatically with Python through Django
I have an application hosted at Digital Ocean. My boss wants that some users have a particular subdomain, i.e., user.mydomain.com Can I do that using Django? I am using gunicorn and nginx. -
How can I load data to the PostgreSQL database in Django project with Docker container?
I have a data which after printing looks in this way: print(myData): 2007-01-01 Estimates of Iraqi Civilian Deaths. Romania and Bulgaria Join European Union. Supporters of Thai Ex-Premier Blamed for Blasts. U.S. Questioned Iraq on the Rush to Hang Hussein. States Take Lead on Ethics Rules for LawsraeCanadian Group. 2007-01-02 For Dodd, Wall Street Looms Large. Ford's Lost Legacy. Too Good to Be Real?. A Congressman, a Muslim and a Buddhist Walk Into a Bar.... For a Much-Mocked Resume, One More Dig. Corporate America Gets the (McNulty) Memo. Completely. Floating Away From New York. National Mourning. The NYSE's Electronic Man. Developer Accuses Hard Rock of Rigging Sale. Shoney's Chain Finds New Buyer. Nucor to Acquire Harris Steel for $1.07 Billion. Will Bill Miller Have a Happier New Year?. 2007-01-03 Ethics Changes Proposed for House Trips, K Street. Teatime With Pelosi. Turning a Statistic On Its Head. War Protest Mom Upstages Democrats. An Investment Banking Love Story. Revolving Door: Weil Gotshal. Should U.S. Airlines Give Foreign Owners a Try?. 2007-01-04 I Feel Bad About My Face. Bush Recycles the Trash. A New Racing Web Site. What&#8217;s the Theme?. The Product E-Mails Pile Up. ... I would like to add this data … -
Error Installing/Launching Django Using Pip
I have downloaded and pip installed Django, but I can't find an icon or the right link to launch the Django app. When I search installed files using "Django" I get a zip file, This is the error I get: Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'django' Plus when I attempt to unzip the Django file, WinRar asks me to purchase a license. So how do I launch the installed Python environment? I use WIN10, Python 3.6.2 Thank you -
How to get specific fields of Django Serialization to JSON
data = serializers.serialize("json", labor_info.labor_selection.all()) print(data) Currently I have a Model Labor which is a ManyToMany Field with another Model LaborSelection. A single object labor_info has 3 labor_selection objects attached to it. Since I cannot return JsonResponse of a ManyToMany field, I must serialize it (from what I have read). This is still new to me, but when I print the data from above, I receive below. If I try to print data[0] I only receive the very first character [. I need to know how I can get each of the choices values from within the fields. [{"model": "inventory.laborselection", "pk": 149, "fields": {"choices": "1-Hole"}}, {"model": "inventory.laborselection", "pk": 150, "fields": {"choices": "2-Holes"}}, {"model": "inventory.laborselection", "pk": 151, "fields": {"choices": "4-Holes"}}] Essentially I with be doing a JsonResponse back to my template where each choice will be displayed. -
Django: how to get the request object in urls.py
I cannot figuring out how I can get ahold of the request object in the urls.py file. I tried to import from django.http.request import HttpRequest But I am stuck here. Can anybody help? -
user conflicts running nginx and uwsgi
I am running a cloud server with root access. I have tried two user combinations for nginx and uwsgi. 1) both as root nginx as root uwsgi as root result: the server is up @port:80 2) both as non root nginx -> www-data uwsgi -> www-data result: uwsgi : error removing unix socket, unlink(): Permission denied [core/socket.c line 198] bind(): Address already in use [core/socket.c line 230] nginx: default welcome page @port:80 I think no webservers must be run as root. I am connecting to a unix socket. The permissions of the socket: srw-rw-rw- 1 root root 0 Oct 20 01:51 project.sock my /etc/nginx/nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; } http { include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; upstream django { # server 127.0.0.1:8001; server unix:/root/project/project.sock; } server { listen 80; server_name my_ip_address_here; location / { uwsgi_pass django; include /root/project/uwsgi_params; } } } and uwsgi configuration [uwsgi] ini = :base socket = /root/project/project.sock master = true processes = 1 [dev] ini = :base socket = :8001 [local] ini = :base http = :8000 [base] chdir = /root/project/ module=project.wsgi:application chmod-socket = 666 uid = user_here what can i do to … -
bootstrap dropdown not working with ajax
So I am creating my blog with Django and I am developing the notification system. I want when the user click the drop to mark all notifications as seen its working and every thing is working fine but when I add the Ajax the dropdown stop working but the Ajax works fine I tried changing the script position in HTML but nothing. Using bootstrap 3.3.7 locally jquery the ajax : <script> $(document).ready(function() { $("#n_d").click(function(event){ $.ajax({ type:"POST", url:"{% url 'seen' %}", success: function(){ document.getElementById("mcount").innerHTML = 0 } }); return false; }); }); </script> the dropdown (it's inside a navbar) {% if user.is_authenticated %} <li class="dropdown"> {% notifications request as notifications %} <a href="#" class="dropdown-toggle" id="n_d" onclick="return x=1" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><i aria-hidden="true" class="fa fa-inbox "> <span class="label label-info" id="mcount">{% noticount request %}</span></i></a> <ul class="dropdown-menu"> {% load blog_tags %} {% for notification in notifications %} <li> <div class="col-md-3 col-sm-3 col-xs-3"><div class="notify-img"><img src="https://www.awn.com/sites/default/files/styles/userthumbnail_tiny/public/avatar92.jpg?itok=i7013HnC" alt=""></div></div> <div class="col-md-9 col-sm-9 col-xs-9 pd-l0"><a href="{% url 'detail' notification.post_pk %}">{{ notification.FromUser }}&nbsp;{{ notification.content }}</a></div> </li> {% endfor %} </ul> </li> {% endif %} the weird tags are Django stuff. -
Django widget template override does not search in the project template directory. How to fix?
I am attempting to override a built in widget template in Django 1.11. I seem to be doing everything that the docs say to do in this regard, but for the widget templates, Django is not looking in my project at all, and I get a TemplateDoesNotExist error. Here's what I have for the override: class MyFileWidget(widgets.FileInput): template_name = 'myapp/my_file_widget.html' The template is definitely there. If I pass the template to a render call, it finds it fine. Problem is an issue of paths. When calling render from a view, it checks the following: projectroot/templates/myapp/my_file_widget.html djangoroot/forms/templates/myapp/my_file_widget.html When it finds the template in my project, it renders it. This is NOT happening when I provide the template path in the class above. In that case, it does not check in my project templates, where the file actually exists, and begins checking in the django path, where it does not. Hence the error message. So I have no clue why this the loader would check my project templates on render calls, but then fail to do so when looking for the "template_name" of the widget override. Any ideas? -
Django periodic task in period of time
I want to make complex tasks that let me control when the task will be started, when it will be finished, when it can repeated Example: I want to create task, it's description call 10 of clients and this task will be assigned to X user and the quantity of this task will be 10 but I want this task will start from 1/1/2018 and it will be finished in 30/12/2018 and the repeat of this task will be weekly Hint: meaning of the repeat, each week I will get the real quantity of the user that's done divided by the quantity of the task and make the quantity of the user is zero in the next week and so on. In details, The X user will start work on Saturday with the target of calling 10 clients by the end of the week, at the end of the week I will calculate the number of clients he called him and I will start again from scratch in the next week with the new task and so on. what is the best way to do that in Django? is there any way to do that with Celery? if can I … -
db_index in django as raw sql query
Can any one specify the real sql query executing for a db_index = True in django, I have a model field which I need to alter with db_index as True, but my rds server crashes since a lot of db process runs in parallel, url = models.CharField(db_index=True,max_length=100, blank=True) What will be the raw psql query for this alteration -
Django - get current user permissions in a view?
Im trying to get the current logged on users permissions My current attempt below returns an error from django.contrib.auth.models import Permission from django.contrib.auth.models import User permissions = Permission.objects.filter(user=User.id) Error int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' does anyone know how I can do this? is there a simpler way? Thanks -
Django: how to get list related ForeignKey records?
I am using Django v1.11. Here are 2 models: class Task(models.Model): title = models.CharField() class TaskUser(models.Model): task = models.ForeignKey(Task, related_name='task_user') user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='+') So, I want to get list of tasks and print in one column list of users that are related to this task. How to do that? The problem is tried a lot: select_related, prefetch_related('task_user') and so on.. but nothing works. In some cases there are no sql error, but it prints task.User.None tasks = Task.objects.all() View must be: <table> <tr> <td>Title</td> <td>Users</td> </tr> {% for task in tasks %} <tr> <td>{{ task.title }}</td> <td> {% for user in task.users %} {{ user.id }} {% endfor %} </td> </tr> {% endfor %} </table> -
How do I create a python app after learning the basic
How can I create an app window, Linux or Android with the basic python I've learned. How can I also learn Django with the basic python I've learned -
Removing unnecessary filters from URL django-filter
I have implemented a pretty standard use of Django-filter, and I noticed that when I submit my query, the URL populates not just with the filters I entered, but with blank values for every filter I did not as well. For example, when I fill out just the STATUS_CODE filter, and then search on my site, I get http://localhost:8888/request-log/?status_code=200&route=&time_sent_0=&time_sent_1=&python_error_msg=&s3_upload_failed=&s3_error_msg= Ideally, I would like the URL to only show fields that aren't blank. So, it would go to http://localhost:8888/request-log/?status_code=200 What is the best way to do this?