Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run this script in django correctly? (mqtt script)
I use mqtt paho, the way here is explained. First if I run the development django server, that gives me 2 scripts of mqtt.py runing, unless I run the server with --noreload python manage.py --noreload That gives me just 1 mqtt script running. But in production I have all this setup with django, gunicorn, nginx, and postgress. So the issue is that gunicorn runs 3 times my mqtt.py file I think that its directly atached to the number of workers in my gunicorn configurations(it is 3 workers). I need to know how do I run this script just 1 time? My mqtt file is suscribed to a topic that writes in a data base that topic, so if the script is runing 3 times, I get 3 database new objects each time I publish 1 message. I think I am calling in the wrong place the script. Of course I need a solution without changing the 3 workers in gunicorn to 1. mqtt.py import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose … -
NOT NULL contraint failed: campgrounds_campground.author_id
First go at building a Django app solo. I've set up a user model as follows class User(auth.models.User): def __str__(self): return self.username Everything works fine there. I've then created a campground model class Campground(models.Model): author = models.ForeignKey('auth.User' , related_name='submitted_campgrounds') name = models.CharField(max_length=128, blank=False, unique=True) image = models.URLField(blank=False) description = models.TextField() def __str__(self): return self.name def get_absolute_url(self): return reverse('campgrounds:single', kwargs={'pk':self.pk}) I'm getting the error when submitting a form to create a new campground. Shound't it be taking the user id from the logged in user? I do have the LoginRequiredMixin on the view for the create view. Any help is appreciated -
How to query Django model from views.py file?
I have a model named Search in my models.py file. I have made migrations and everything is working totally fine except one problem. In my views.py file I have created one variable called var1 which queries "search_query" field into the database, but unfortunately, it couldn't assign that variable. Please help me how to access my model to work this line, var1 = Search.objects.latest('search_query'),search_query Here is my models.py file, from django.db import models class Search(models.Model): search_query = models.CharField(max_length=64) views.py file, from django.shortcuts import render, redirect import requests from git_profile.forms import SearchForm from git_profile.models import Search def index(request): var1 = Search.objects.latest('search_query'), search_query -
Unable to connect nginx
I'm tynna run my django via nginx and uwsgi at vps at ubuntu I have home/first/mySite/deployment at deployment folder I have two files: nginx.conf and uwsgi_paramsse at mySite folder I have Django project which include:deployment, joins (my app django), lwc(my "main" app django), media, static, Templates, manage.py and nginx.sock my nginx.sock file is # the upstream component nginx needs to connect to upstream django { server unix:///home/first/mySite/nginx.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name my_site.ru; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias alias /home/first/mySite/media; required } location /static { alias /home/first/mySite/static; required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/first/mySite/deployment/uwsgi_paramsse; # the uwsgi_params file you installed } } ngins.conf is # the upstream component nginx needs to connect to upstream django { server unix:///home/first/mySite/nginx.sock; # for a file socket # server … -
what kind and how much logic to store in django views
My django views are getting rather large. I am wondering how much and what kind of logic is recommended for a django view. When a view goes beyond the recommended scope, is there a recommended file to use to abstract out logic like data controller or view controller? -
How to support user polymorphism in Django without raw sql?
Subtitle: when the student becomes the teacher Imagine two classes, Student and Teacher, that each inherit from User. None of these models is abstract. How to you modify an instance of student so that they can also be a teacher, without just dropping into raw sql and inserting the teacher record? -
Working with generic "locations" under django-cities-light
Cities-light uses 3 models: City, Region and Country. What I'm trying to do is treat them all as the same generic type - a "location" - so that users can type something into a search box and easily find results that are of any type. I've been doing this by simply joining querysets together, but now I'm also looking into allowing users to add favourite locations, and having to process these 3 model classes individually is becoming troublesome. Can anyone recommend a good approach to cleaning this up? It seems like ideally each of the cities-light classes should inherit from a "location" base model, which would then be easily query-able. But this would mean doing a lot of re-writing of the app itself, so not ideal. The other option I can think of is to create a helper-class called Location which stores either a city, region or country, but this would mean duplicating an already large dataset so, again, not ideal. Appreciate any advice here. -
Push updates to client through Django Channels & Websockets
I'm trying to make a page which shows live-updating data to the client. The rest of the site is built with Django, so I'm trying to use Channels for this. The data I am displaying is saved in both a JSON file and a MySQL database for further calculations in other parts of the site. Ideally, I would like to display the latest data received (that is, when the file updates) to the client as it is received. And even though as I understand Channels are built exactly for this purpose, I am having trouble doing it. I have tried sending multiple requests from the client-side with delay and loops in the consumer, but it either (ironically) only updates on refresh or updates instantly. However, neither of these approaches are triggered by a change in the file or database. This is the code that "works", but doesn't really do what's required. (also, admittedly, there's basically nothing there...) # consumers.py def ws_connect(message): message.reply_channel.send({"accept": True}) def ws_receive(message): with open("data.json") as jsonfile: jsondata = json.load(jsonfile) res = json.dumps(jsondata) message.reply_channel.send({ "text": res, }) #routing.py from channels.routing import route from .consumers import ws_receive, ws_connect channel_routing = [ route("websocket.receive", ws_receive, path=r"^/websockets/$"), route("websocket.connect", ws_connect, path=r"^/websockets/$"), ] JS … -
Include a menu to several templates in Django
I'm trying NOT to write same code twice on different templates. Real hassle when changing something. So when I go to a section of the webpage, I want to display a side menu. This side-menu is suppose to be on several templates. Like index.html, detail.html, manage.html and so on. But the section is only a part of the webpage, so I can't have it in base.html. I was thinking about using include. But since the side menu is dependent of DB queries to be generated, I then have to do queries for each view. Which also makes redundant code. What is best practice for this feature? Cheers! -
Django url regular expression matching but page not found error
Project Name: JalaBapa_website JalaBapa_website\urls: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^about_us/', include('About_Us.urls')), url(r'^activities/', include('Activities.urls')), url(r'^collections/', include('Collections.urls')), url(r'^contact_us/', include('Contact_Us.urls')), url(r'^donate/', include('Donate.urls')), url(r'^events/', include('Events.urls')), url(r'^home/', include('Home.urls')), url(r'^publications/', include('Publications.urls')), ] Publications/urls.py: from django.conf.urls import url from . import views app_name = "Publications" urlpatterns = [ # /publications/ url(r'^$', views.publications, name='publications'), # /publications/Xyz_9999.pdf/ url(r'(?P<file_name>^[A-Z][a-z]+\_[0-9]{4}\.pdf$)', views.pdfs, name='pdfs') ] Publications/views.py from django.http import HttpResponse, FileResponse from django.shortcuts import get_object_or_404, render from .models import * # Create your views here. def publications(request): all_files = Publications.objects.all() uploaded_file_names = [] for obj in all_files: uploaded_file_names.append(str(obj.file_name())) context = { 'uploaded_file_names': uploaded_file_names } return render(request, 'publications/publications.html', context) def pdfs(request, file_name): with open('media/pdfs/'+file_name, 'r') as pdf: response = FileResponse(pdf, content_type='application/pdf') return response some code of: Publications/templates/publications/publications.html <div class="container-fluid"> {% for file_name in uploaded_file_names %} <a href="{{ file_name }}"> <!-- <a href="{% url 'Publications:pdfs' file_name %}"> will be continued... the above line in snippet was COMMENTED BECAUSE BEFORE THIS WAS SHOWING ERROR : NoReverseMatch at /publications/ Reverse for 'pdfs' with arguments '('July_2017',)' not found. 1 pattern(s) tried: ['publications/(?P^[A-Z][a-z]+\_[0-9]{4}\.pdf$)'] Here is Error Screen Shot image I WOULD LIKE TO KNOW WHY THIS IS NOT WORKING - QUESTION 1 ANYHOW, <a href="{{ file_name }}"> was hardcoded but … -
is there any way to dynamically add formclass to the view using url in django?
I m new to Django, and experimenting few things.. I want to dynamically pass the form_class in my view so that a single view can do all the work. urls.py: url(r'^(?P<form>[\w-]+)/$',BillCycleCreateView.as_view(),name='BillCycle'), views: class BillCycleCreateView(CreateView): template_name = 'form-view.html' success_url = '.' def get_form_class(self): print(self.kwargs) x = self.kwargs['form'] print(x) return x the following code raises error that 'str object is not callable'. Is there any way to fix it or any other way to achieve the desired result? Thanx in advance!! -
Turning an edited table within html into json, sending to django
I have a contenteditable="true" table as a part of my html. I want a user to be able to edit that table and click a button to send updated data which will transform the table into JSON which I will later unwrap to a dataframe in python. So far, I have figured how to get JSON: <button onclick="table2json()"> JSon </button> <script> function table2json(){ var myJSON =JSON.stringify(makeJsonFromTable("dataframe")) //return console.log(myJSON) } </script> However, I know almost none of ajax. In views.py, I created: def gettable(request): if request.method == 'POST': json_data = json.loads(request.body) out_file = open("file.json", "w") json.dump(json_data, out_file) out_file.close()` but what do I actually write in my jQuery? Thank you! -
Get model attributes without making them required for modelform_factory?
I've got a modelform_factory which works perfect for what I need. I call it like this: dep_formset = modelformset_factory( Dependent, fields=('has_medical', 'med_group_id'), max_num = dep_count ) As you might guess, Dependent has additional fields that I want to use simply for display purposes (first_name and last_name respectively) I want to show the first_name and last_name of the dependent person - but have it be simply for display, not edit. If I add 'first_name' and 'last_name' to the fields in the above, I can then access them in my template - but the form fails against .is_valid() because I'm displaying them simply as text and not as an input, so they're not being POST'ed Is there some clever way to get access to the first_name and last_name of the dependent objects without adding them to fields for the formset_factory? The template looks like this (partial snippet so you can see what I'm trying to do with the first_name, last_name): {% for form in dep_formset %} {{ form.id }} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <div class="g"> <h4>{{ form.first_name.value }} {{form.last_name.value}}</h4> </div> <div class="g dependent-option"> <div class="g-1-4 dependent-option-check"> {% if form.has_medical %} -
django admin short_description colon
When I use short_description='ABC' in a custom ModelAdmin class, a colon will be displayed. So you get ABC: in your view. Is there a way to omit/remove the colon character? -
Keep getting 400 error response while storing image on S3 from djagno models?
Here is the settings that i have for django-boto # S3 configuration AWS_ACCESS_KEY_ID = os.environ.get("AWSAccessKeyId") AWS_SECRET_ACCESS_KEY = os.environ.get("AWSSecretKey") AWS_STORAGE_BUCKET_NAME = os.environ.get("S3BucketName") S3DIRECT_REGION = os.environ.get("S3Region") # S3 configuration for boto BOTO_S3_BUCKET = os.environ.get("S3BucketName") BOTO_BUCKET_LOCATION = os.environ.get("S3Region") # AWS_S3_FORCE_HTTP_URL = True # AWS_QUERYSTRING_AUTH = False AWS_S3_HOST = 's3.ap-south-1.amazonaws.com' And i am defining models as follows from django_boto.s3.storage import S3Storage s3 = S3Storage() class userProfileModel(models.Model): """User profile model. """ user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='profile') profile_pic = models.ImageField(storage=s3,null=True,blank=True) I keep getting 400 response code without any error from s3. The only exception i have been able to find is at env/lib/python2.7/site-packages/boto/s3/connection.py in head_bucket, line 556 On same note, i am also using django-s3direct with same credentials and it is working all fine without any issues. Where am i going wrong with this ? -
Django defining __str__ for nested foreign key
Using a nested model like this: class Gov(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class State(models.Model): parent = models.ForeignKey(Gov) abbreviation = models.CharField(max_length=100) def __str__(self): return self.parent.name class State_Park(models.Model): parent = models.ForeignKey(State) park_name = models.CharField(max_length=100) How would I set __str__ for class State_Park to be name in class Gov? I tried: def __str__(self): return self.parent.parent.name which did not work. -
How to correct OperationalError at /Self/register/ no such table: auth_user
I am creating an authentication system using django 1.10.5. I am using email as the unique identifier instead of username. I followed these instructions HOW to use email I created my Customer User Model and Custom User Manager for the new User Model from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('THE email is not set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique = True ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() I added the Custom User Model in my settings document : AUTH_USER_MODEL = 'Identities.User' I then registered my new User Model in the administration document from django.contrib import admin from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from django.utils.translation import ugettext_lazy as _ # Register your … -
Hide drop-down menus in using id number
I passed a list [object1, object2, ...] to a drop-down menu. When I pressed on F12 with the desire of knowing the id of object1 which is Total number of clients in the following HTML code. I want to use that id in a JS file. How could I generate one id for each item of the list. Otherwise, what can I use in the JS file instead of an id number for Total number of clients? <div class="select-wrapper select initialized"><span class="caret">▼</span><input type="text" class="select-dropdown" readonly="true" data-activates="select-options-655bff26-fb5b-1642-ddeb-41bd1b4ab105" value="Total number of clients"> <ul id="select-options-655bff26-fb5b-1642-ddeb-41bd1b4ab105" class="dropdown-content select-dropdown" style="width: 100px; position: absolute; top: 1px; left: 0px; opacity: 1; display: none;"> <li class="active selected"><span>Total number of clients</span></li> <li class=""><span>Total new loans</span></li> <li class=""><span>Total renewals</span></li> <li class=""><span>Total debit fees</span></li> <li class=""><span>Total brokerage fees</span></li> <li class=""><span>Total interest</span></li> <li class=""><span>Total accounts receivable</span></li> <li class=""><span>Total active accounts receivable</span></li> <li class=""><span>Total special accounts receivable</span></li> <li class=""><span>Total accounts loss</span></li> <li class=""><span>Total completed loans</span></li> <li class=""><span>Total terminated loans</span></li> <li class=""><span>Total suspended loans</span></li> <li class=""><span>Total delayed fees</span></li> <li class=""><span>Total denied fees</span></li> </ul> <select class="select initialized" id="id_type_choice" name="type_choice"> <option value="0" selected="selected">Total number of clients</option> <option value="1">Total new loans</option> <option value="2">Total renewals</option> <option value="3">Total debit fees</option> <option value="4">Total brokerage fees</option> <option value="5">Total interest</option> <option value="6">Total … -
filtering a foreign key on a form and displaying the value with dropdown menu
I'm having issues with it displaying the related table's value. It'd show me table object. When I try retrieving it, I get the table value itself, but I cannot get the foreign table value. form.py class MyForm(forms.ModelForm): name = forms.CharField(label='Whatever Name') class Meta: model = MyModel def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(MyForm, self).__init__(*args, **kwargs) qs = ForeignTable.objects.filter(user=user, status="Y") | ForeignTable.objects.filter(rel_user=user, status="Y") self.fields['dropdown'].queryset = qs #the user id can be one column or a rel_user column The output to this is a dropdown menu but it says ForeignTable object. This ForeignTable is then connected to the UserTable with a foreign key. This is where I am stuck. I can't get the list to display. So I tried letting qs=[(o.id, str(o.user.username)) for o in qs]. On print I can see my usernames. But it gives an error after my print list object has no attribute all. So I looked at the template. template.html {{ form.as_ul}} this is what i had then I change to see what is in the dropdown I'm looking for {{form.dropdown }}. It gave me the same error. So now I have no idea where to look next. Where is this all that is it is saying? -
Specific way of requiring one of two fields in django model definition
I have model MyModel with fields field1 and field2. I want to require either one of these two fields. How can I do this? class MyModel(models.Model): field1 = models.TextField(?) field2 = models.TextField(?) I am looking for a specific, best-practice way that I have seen but forgotten, not the overriding clean function method. I do remember the method overriding some function, but I don't think it was clean. Thanks in advance -
Adapt JSONField to have auto conversion to Decimal
I have model with fields of type: django.contrib.postgres.fields.JSONField and I want have it always deserialized by: json.loads(value, parse_int=decimal.Decimal, parse_float=decimal.Decimal) when accessing objects by: MyModel.objects.get(..) however I found it hard to find the line with json.loads which must be overriden by above one. -
tinymce simplest integration in django admin with medias
I am trying to integrate django-tinymce to the admin page for editing posts entries. so far I have a basic editor by adding the following lines in models.py from tinymce import models as tinymce_models class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) # text = models.TextField() text = tinymce_models.HTMLField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) title_pic = models.ImageField(upload_to = 'posts/title_pics', blank = True) def __str__(self): return self.title But how to add more features to the editor as images, medias, etc.. like in https://www.tinymce.com/docs/demo/image-tools/ ? -
Why error 404? Python,Djagno
Why error 404? models.py : gist.github.com/roma323/78f69487c16546a2b917d5679ade21aa views.py : gist.github.com/roma323/16e974d54af13cc126ab98e3a4964dbb urls.py :gist. github.com/roma323/9784f2fc41336a40228ff5fa976cb325 index.html :/gist. github.com/roma323/44685a30e78de405ec8ec23d8916bf48 post.html :gist. github.com/roma323/c2b2ed91dfc4cd3eea1cc33cffefee14 -
django app putting value in tables
i am making this app "student" in django where i need to populate the database tables(there are many tables connected to each other via foreign keys). As i login and move from one page to another(different views), for eg, as i login, the page redirects to a category page where i'm supposed to select a category and then the page redirects to another page where i'm supposed to select some other field. So these fields that i'm selecting on my way are the table columns(eg subject in subject table, grade in marks table,etc). i want to populate my different tables as i go on...when i click on the subject, the selected subject fills up the "subject" attribute of the subject table...and in the same way others. So how do i do that? -
Django: Variable in template doesn't display
views.py def tick(request): leave_id=request.POST['leave_id'] ticked_leave=leave.objects.filter(id=leave_id).select_related('employee') emp_name=ticked_leave[0].employee.emp_name; data=dict() data['ticked_leave'] = render_to_string('m_manage/tick_modal.html', { 'emp_name':emp_name,'leave_id':leave_id }) return JsonResponse(data) In my template I am using: <h4 class="modal-title" >Do You want to accept <b>{{emp_name}}</b> leave?</h4> It display nothing..It just displays Do you want to accept leave? leaving emp_name... Thanks in advance....