Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ,supervisord,and gunicorn setting environment variables and accessing in django settings
I am using gunicorn and django in python virtual environment. os: ubuntu 14.04 gunicorn : 19.0 django : 1.10 supervisor In my setings file I am reading variable from virtual environment My prod_settings.py DB_NAME = os.environ.get("USER_NAME") DB_PASSWORD = os.environ.get("MONGO_PASSWORD") DB_URI_STRING = os.environ.get("MONGO_URI_STRING") I have set environment variable through .bashrc In virtual environment, if I run python manage.py runserver then everything is working fine. my gunicorn.bash NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=django_project.settings.prod_settings DJANGO_WSGI_MODULE=django_project.wsgi echo "starting $NAME as `whaoami` " # Activate the virtual environment cd $DJANGO_DIR source /home/sachin/Documents/django_project/virtEnv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGO_DIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR= $(dirname $SOCK_FILE) test -d $RUNDIR || mkdir -p $RUNDIR #Start Django Unicorn #Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCK_FILE \ --log-level=debug \ --log-file=- if I run this script directly in console everything working but when I run this script using supervisorctl then key error is occuring . For ex "USER_NAME" keyerror my supervisor_config script [program:django_project] command = /home/sachin/Documents/django_project/gunicorn_start.bash user = sachin stdout_logfile = /home/sachin/Documents/django_project/logs/gunicorn_supervisor.log redirect_stderr = true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 sudo supervisorctl start django_project same code is working with supervisor also if hardcode … -
Unique Slug Field: Django
I'm trying to add a slug field, Here's what I tried in my model, slug = models.SlugField(unique=True) def pre_save_receiver(sender, instance, *args, **kwargs): slug = slugify(instance.title) exists = Data.objects.filter(slug=slug).exists() if not exists: instance.slug = slug else: instance.slug = "%s-%s" % (slug, instance.id) pre_save.connect(pre_save_receiver, sender=Data) Problem is that it's adding the ID in slug field behind title no matter even if it's a very Unique title. How can I fix that? Thank YOU :) -
How to resolve Django error 'index' is not a valid tag library: Template library index not found, tried"
I have write down a new templatetag for django under "table" app inside "myproject" folder, further another folder has been created inside the "table" app folder as "tamplatetages", further two files, "__init__.py" and "index.py" have been created. Template tag was created to get list item from the list index as we do in regular python code ex: ls = [a, b, c,d] nl = [w, x,y,z] for i,x in enumerate(ls): print x, nl[i] this is my tamplatetag file"index.py" from django import template register = template.Library() @register.filter def index(List, i): return List[int(i)] and this is how I have incorporated new tamplatetags inside my template: {% load index %} <ul class="sidebar-categories"> {% for news in text_list %} <a href="{{ link_list|index:forloop.counter0 }}"> <b> {{news}}</b> <br> {% endfor %} </ul> but its shows error like this: 'index' is not a valid tag library: Template library index not found, tried django.templatetags.index,django.contrib.admin.templatetags.index,django.contrib.staticfiles.templatetags.index,import_export.templatetags.index Request Method: GET Request URL: http://127.0.0.1:8000/cholera/ Django Version: 1.8 Exception Type: TemplateSyntaxError Exception Value: 'index' is not a valid tag library: Template library index not found, tried django.templatetags.index,django.contrib.admin.templatetags.index,django.contrib.staticfiles.templatetags.index,import_export.templatetags.index Exception Location: /usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py in load, line 1159 Python Executable: /usr/bin/python Python Version: 2.7.12 while, I am able to successfuly import it on the Django shell >>> … -
Bokeh zoom and pan bounds acting strange
I have a Bokeh plot that looks like this: plot = figure(plot_width=1000, plot_height=300, y_range=(0, 1), x_range=Range1d(1, len(fasta_object.sequence()), bounds=(1, len(fasta_object.sequence()))), tools="xpan,xwheel_zoom,box_zoom,save,reset", active_scroll="xwheel_zoom", title=fasta_object.header(), y_axis_label='Score', x_axis_label='Position') What i want is to be able to wheel scroll only on the x axis, and dont go outside the possible bounds. The code above does exactly this, however when i zoom in with scrolling and out again i cant scroll out to the "full" picture. The scrolling out stops at some seemingly random number. Why is this happening? PS: The figure is rendered inside Django, if thats a possible source of this error. -
How to initialize java script when you have two or more base HTML
I have two base HTML page one with navbar and one without navbar and i am using metralized css and it has js file to be initialized in order many functions in UI level i need the js files to accessed in all html page. How to implement that . i am getting following error: VM798 jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/. send @ VM798 jquery-3.2.1.min.js:4 VM806:6 Velocity is already loaded. You may be needlessly importing Velocity again; note that Materialize includes Velocity. VM798 jquery-3.2.1.min.js:2 jQuery.Deferred exception: $(...).sideNav is not a function TypeError: $(...).sideNav is not a function at HTMLDocument.<anonymous> (<anonymous>:4:26) at j (https://code.jquery.com/jquery-3.2.1.min.js:2:29999) at k (https://code.jquery.com/jquery-3.2.1.min.js:2:30313) undefined r.Deferred.exceptionHook @ VM798 jquery-3.2.1.min.js:2 VM798 jquery-3.2.1.min.js:2 Uncaught TypeError: $(...).sideNav is not a function at HTMLDocument.<anonymous> (<anonymous>:4:26) at j (VM798 jquery-3.2.1.min.js:2) at k (VM798 jquery-3.2.1.min.js:2) VM807 jquery-3.2.1.min.js:2 jQuery.Deferred exception: $(...).sideNav is not a function TypeError: $(...).sideNav is not a function at HTMLDocument.<anonymous> (<anonymous>:4:26) at j (https://code.jquery.com/jquery-3.2.1.min.js:2:29999) at k (https://code.jquery.com/jquery-3.2.1.min.js:2:30313) undefined r.Deferred.exceptionHook @ VM807 jquery-3.2.1.min.js:2 VM807 jquery-3.2.1.min.js:2 Uncaught TypeError: $(...).sideNav is not a function at HTMLDocument.<anonymous> (<anonymous>:4:26) at j (VM798 jquery-3.2.1.min.js:2) at k (VM798 jquery-3.2.1.min.js:2) … -
How to style django-multiselectfield with CSS
I am using 'django-multiselectfield' in my model form so users can select multiple 'areas' in my form. What I want to know now is how can I style the multiselectfield using css. I have tried simply adding a class to the form field in my template like I normally do with all the other types of model fields, but no luck: {% render_field form.area class="area" %} Any help would be much appreciated. -
python3 django manage.py runserver error
I have a project in AWS cloud9. I tried to login via LinkedIn or Facebook, i use django. When i run the command : python manage.py runserver 0.0.0.0:8080 i get Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 307, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.4/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python3.4/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.4/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib64/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "/home/ec2-user/environment/gowith/django_social_project/django_social_project/settings.py", line 17, in <module> from config import * File "/usr/local/lib/python3.4/site-packages/config.py", line 733 except Exception, e: ^ SyntaxError: invalid syntax -
Execute code after celery finishes a tasks
I'm using Django 2.0, Python 3.6 and Celery 4.1 After celery is finishing a task, I want to execute a code that do an update in the database. How can I do that ? -
Django - How to add a file during model save?
I'm trying to create and save a csv file as part of a save and then associate the file to the record. This is my model class ReOrder (models.Model): product = models.ForeignKey( Product, ) order_quantity = models.IntegerField( default = 0 ) order_date = models.DateField( default = datetime.datetime.now() ) received = models.BooleanField( default = False ) order_file = models.FileField( upload_to = 'reorder_documents/', null = True, blank = True ) def __unicode__(self): return u'%s' % (self.product) def save(self, *args, **kwargs): # create the text file filename = str(self.product)+'_'+str(self.order_date)+".csv" path = os.path.join(MEDIA_ROOT, 'reorder_documents', filename) print path f = open(path, 'wrb') f.truncate() writer = csv.writer(f) writer.writerow((self.product, self.order_quantity)) f.close() self.order_file = ContentFile(f) #save everything super(ReOrder, self).save(*args, **kwargs) # Call the "real" save() method. This creates and saves the file exactly where I want it but doesn't save it to the model. How do I do that? -
Scheduling with Celery - Issue KeyError
I'm trying to schedule tasks using Celery. I have the following code in the django folder (where are settings.py): in celery.py app.conf.beat_schedule = { 'add-every-3-minutes': { 'task': 'notes.tasks.add', 'schedule': crontab(minute='*/2'), # execute every 2 minutes 'args': (16, 16) }, } In notes folder of the django app notes I have the following code: @task(name="sum_two_numbers") def add(x, y): return x + y The error that I have is: line 561, in on_task_received strategy = strategies[type_] KeyError: 'notes.tasks.add' I'm on Django 2.0 and python 3.6, using Celery 4.1.0; Without schedule I tested in shell and it works. I suppose is related to the path to the tasks, but I don't understand why. -
Django 'datetime.datetime' object is not callable
I just want to update my model : My view : message = InboxRecruiting.objects.get(id=id_message, on_team=team, is_removed=False) message.update(is_read_team=True) My model : class InboxRecruiting(models.Model): on_team = models.ForeignKey(Team, verbose_name="Equipe") from_user = models.ForeignKey(User, verbose_name="De", related_name='from_user') to_user = models.ForeignKey(User, verbose_name="Vers", related_name='to_user') is_read_team = models.BooleanField(default=False, verbose_name="Lu (auteur)") is_read_player = models.BooleanField(default=False, verbose_name="Lu (destinataire)") is_removed = models.BooleanField(default=False, verbose_name="Supprimé") is_accepted = models.NullBooleanField(default=None, verbose_name="Accepté") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") def __str__(self): return str(self.date) It returns an error : 'datetime.datetime' object is not callable Thank you -
remove duplicates from the list of a model instances
Based on the post: Django comparing model instances for equality I am trying to remove the duplicates from my list of instance (Which have not been saved yet and I assume their 'id' to be None) the code is: a = list() a.append(relation_list.pop()) for x in relation_list: duplicate = False for z in a: if z is x: #or if z.attrib1 == x.attrib1 and z.attrib2 == x.attrib2: duplicate = True if not duplicate: a.append(x) However, given the attribs being equal the line duplicate = True never get executed. What am I missing? Is there a more efficient way to achieve this? (inspired from this post using "in relation_list" either does not work. -
django.db.utils.ProgrammingError: column "questions" is of type character varying[] but default expression is of type integer
class college(models.Model): image = models.ImageField(upload_to='college_image/',default=None) name = models.CharField(max_length=100) email = models.CharField(max_length=100,unique=True) password = models.CharField(max_length=500) add_field = models.CharField(max_length=200) city = models.CharField(max_length=200) state = models.CharField(max_length=200) zipcode = models.CharField(max_length=10) phone = models.CharField(max_length=10, validators=[RegexValidator(r'^[789]\d{9}$')]) status = models.BooleanField(default = True) last_date = models.DateTimeField() is_active = models.BooleanField(default = False) reg_time = models.DateTimeField(auto_now_add=True,blank=True) questions = ArrayField(models.CharField(max_length=500),blank=True) def __str__(self): return self.email Error occurred when I added questions field in college model and used command 'python manage.py migrate' HINT(shown after the command): You will need to rewrite or cast the expression -
Filtering starting from a Foreign key users that are not staff combined with other filters
I have the following model: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='activity', sent_at = models.DateTimeField(blank=True, null=True) on_delete=models.CASCADE) I need a query that exclude all users that are not staff and sent is null. So I tried to use exclude: Post.object.all().exclude(user.is_staff=True) and I get the following error: keyword can't be an expression -
MySQL trigger condition
Consider the following scenario where users can enable/disable MySQL triggers using a web interface. I am creating a session variable once the user opens a specific web page by executing the following command: SET @vsAge = 0 This variable is then used inside a BEFORE INSERT trigger: BEGIN IF (@vsAge = 1) THEN IF new.age < 0 THEN SET new.age = 0; END IF; END IF; END However when I run my Django server and create this variable, my trigger doesn't work properly, running the command SELECT * FROM performance_schema.user_variables_by_thread is showing me that this variable does exist, and the problem can't be with the code since if I create this variable using MySQL workbench, everything works fine, so the problem is probably somewhere on the server. How does django handle database connections and sessions, I'm guessing somewhere in my code the database connection gets closed and this variable is stored in a different session. Is it possible to force django to use a single MySQL session? I use the django database api for some operations and for making variables I am using: class Database: def __init__(self): self.con = None def connect(self): self.con = mdb.connect('localhost', 'root', 'password', 'dbname') def trigger_toggle(self, … -
How to manage PK when a view must be called with it
Hi guys I have an issue with my private keys. I do not know what is the problem if someone could give me a hand it would be greatly appreciated. the errror that I get is : Generic detail view ProjectDetailView must be called with either an object pk or a slug my models are the following: class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) members = models.ManyToManyField(MyUser, related_name="members") def __str__(self): return self.team_name class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True) candidat_answers = models.ManyToManyField('survey.response') def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs = {'pk1' : self.pk}) def __str__(self): return self.name my views : class HomePage(TemplateView): template_name= 'index.html' class LinkTeam(generic.ListView): template_name = 'link_project.html' def get_queryset(self): #import pdb; pdb.set_trace() #team2 = Team.objects.all().filter(team_hr_admin = self.request.user) queryset = Team.objects.filter(team_hr_admin=self.request.user) return queryset def TeamSelect(request): import pdb; pdb.set_trace() if request.method == "POST": select_form = EditSelectTeam(request.user, request.POST) if select_form.is_valid(): data = select_form.cleaned_data['team_choice'] obj2 = Project.objects.filter(project_hr_admin=request.user) obj3 = obj2.latest('id') if obj3.team_id == None: obj3.team_id = data obj3.save() obj4 = obj3.team_id obj5 = obj4.members.all() for i in obj5: current_site = get_current_site(request) message = render_to_string('acc_join_email.html', { 'user': i.first_name, 'domain':current_site.domain, }) mail_subject = 'You have been invited to SoftScores.com please LogIn to … -
Django: How to trigger a session 'save' of form data when clicking a non-submit link
I know if want you to store form information to the session during a submit you do it with the 'def post' in your view. However, I can not figure out how to store form information when a random link e.g. 'homepage'. How would you go about storing form information when a user clicks away from the form? -
signupp() got an unexpected keyword argument 'name'
Here is my views.py Here is my models.pyenter image description here -
Passing kwargs to django admin form
I have a couple of models, for example: class Product (models.Model): title = models.CharField( max_length = 255, ) supplier = models.ForeignKey( Supplier, blank=True, null=True ) min_level = models.IntegerField( default = 10, ) quantity = models.IntegerField( default = 0 ) class ReOrder (models.Model): product = models.ForeignKey( Product, ) order_quantity = models.IntegerField( default = 0 ) order_date = models.DateField( default = datetime.datetime.now() ) received = models.BooleanField( default = False ) def __unicode__(self): return u'%s' % (self.product) When I'm listing my Products within Django Admin I have a ReOrder button. When click I want to go straight to the Django Admin ReOrder Add ReOrder.product defaulting to the Product prefilled Getting the button etc in place is fine but I cannot work out how to pass the Product.id through. I'm trying: reverse('admin:inventory_reorder_add', kwargs={'product_id' : obj.pk }) where obj.pk is the Product. This is giving me Reverse for 'inventory_reorder_add' with keyword arguments '{'product_id': 31L}' not found How do I make a call and have the field pre-selected within admin? Thanks for your help. Below is the complete ProductAdmin class. class ProductAdmin(admin.ModelAdmin): list_display = ['title', 'get_sku', 'get_ebaylink', 'quantity', 'quantity_status','account_actions','weekly_stock','monthly_stock','quarterly_stock'] ordering = ['title', 'quantity', ] inlines = [SkuInline, EbayLinkInline] search_fields = ('title', 'sku__sku', 'ebaylink__custom_label', ) fields = … -
Django: Query Selected Info in Model Within Class Based Views
I created some link with model-slug. But When I click my link, go to the page but return the empty value. I want to When I click any link, It will query value from the selected field like class_name or slug field. this class list html page {% extends "result/base.html" %} {% block title %}Class List Name{% endblock title %} {% block content %} <div class="row"> <div class="col-md-12 col-xs-offset-4"> <h2>Class List</h2> {% for object in object_list %} <a href="{% url 'result:class-detail' object.slug %}">{{object.class_name}}</a> {% endfor %} </div> </div> {% endblock %} this is models.py file class ClassName(models.Model): class_name=models.CharField('Class Name', max_length=10) class_added=models.DateTimeField(auto_now_add=True) class_updated=models.DateTimeField(auto_now=True) slug=models.SlugField(max_length=200, unique=True) def __str__(self): return self.class_name this is views.py file class ClassListView(ListView): model=ClassName slug_field = 'slug' template_name='result/class_list.html' class ClassDetailView(DetailView): model=ClassName slug_field = 'slug' template_name='result/class_detail.html' def get_context_data(self,*args, **kwargs): context = super(ClassDetailView, self).get_context_data(*args,**kwargs) context['class_wise_std'] = StudentInfo.objects.filter( student_class_name__class_name__startswith=self.model.slug) return context this is class details html page {% extends "result/base.html" %} {% block title %}Class Detail's List{% endblock title %} {% block content %} <div class="row"> {% for object in class_wise_std %} <div class="col-lg-12 col-sm-offset-4" style="margin:20px 10px"> <p>Name: {{object.student_name}}</p> <p>Class: {{object.student_class_name}}</p> <p>Father's Name: {{object.student_father_name}}</p> <p>Mother's Name: {{object.student_mother_name}}</p> <p>Roll: {{object.student_roll}}</p> </div> {% endfor %} </div> {% endblock content %} this code def get_context_data(self,*args, … -
What are the best possible ways to integrate a Front End(Vue) and Backend(Django-DRF) for a web application?
What are the best possible ways to integrate a Front End(Vue) and Backend(Django-DRF) for a web application ? -
Is it possible to read the SECRET KEY from djano settings.py by other apps?
I want to use the django SECRETE_KEY for creating my JWT (Json web token). Is it possible to read the django secrete key from all apps under a django project? Please advise me on if it is a good practice to use the django secrete key for internal app logic. -
changing VS2015 django project settings directory name cause ModuleNotFoundError on startup
I use VS2015 create a Django project. It has the project directory (say, MySite). Under which, it also has a directory with the same name (i.e. MySite) which contains web project configuration and setting files such as settings and urls. I don't like it having the same name as the project root directory and so changed this settings directory name to 'config'. I also made the following changes: 1. in manage.py: os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "config.settings" ) 2. in IDE's Projects setting, remove $(MSBuildProjectName) from Django's "Settings Module". However, when I start the project from IDE debugging run, execute_from_command_line(sys.argv) in manage.py raises an exception ModuleNotFoundError on 'MySite'. It seems that Django startup hardwired the sys.argv value to the project name. That is, it assumes that the settings.py is in a subdirectory with the same name as project name. How can I change this default behaviour so that it understands the settings in the directory with a different name. Thank you -
Django build video website similar to YouTube
I am trying to build a video upload website using Django 1.11.8, Python 3.6.3 and MySQL. I have No experience in developing any kind of video upload website. But I am confident that I can build similar website with my Django experience. I am worried about the performance and scalability. I want to share my approach and please correct me If I am wrong or you can suggest me better way. I already have default user database on Django.contrib.auth.model>>User and will be use same users information to upload, likes, views and other interactions with videos 01. Create Model.py (this is sample) from django.db import models from django.contrib.auth.models import User class Channel(models.Model): name = models.CharField(max_length=100) subscribers = models.ManyToManyField(User, related_name='+', blank=True) creation_time = models.DateTimeField(auto_now_add=True) modified_time = models.DateTimeField(auto_now=True) class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') channel = models.ForeignKey(Channel, on_delete=models.CASCADE) notifications = models.BooleanField(default=True) class Playlist(models.Model): video = models.ForeignKey('Video', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class Category(models.Model): name = models.CharField(max_length=100) class ChannelSettings(models.Model): channel = models.ForeignKey(Channel, on_delete=models.CASCADE) verified = models.BooleanField(default=False) 02 Create View.py To render Html templates frames. such as video view page, channel page, playlist page, history page, search page I will not use Django template tags to populate any information. 03 Create api.py To create … -
Javascript add class to classList don't add. Used in Django web development framework
We have a form in which we want all input areas with faulty submitted data to gain red borders. This is done by setting the class of the input tag to "form-control-danger" in addition to the original class "form-control". The HTML/JS/Django code looks like this, and it is mostly correct. I have controlled that the scripts tags are only generated and run when faulty data is submitted. <!-- Output all fields --> {% for field in form %} <div class="input-group form-group-no-border"> <span class="input-group-addon"> <i class="now-ui-icons {% if field.name == 'email' %} ui-1_email-85{% endif %} {% if field.name == 'username' %} users_circle-08{% endif %} {% if field.name == 'password1' %} ui-1_lock-circle-open{% endif %} {% if field.name == 'password2' %} ui-1_lock-circle-open{% endif %} "></i> </span> {{ field }} <!-- Give input box red border if data is not valid --> {% if field.errors %} <script> var element = document.getElementById("{{ field.id_for_label }}"); element.classList.add("form-control-danger"); </script> {% endif %} </div> {% endfor %} As we feed the form faulty data this gives us this source code. <div class="input-group form-group-no-border"> <span class="input-group-addon"> <i class="now-ui-icons ui-1_lock-circle-open "></i> </span> <input type="password" name="password2" value="iuhqeifuhweifuhweifuwefw" id="id_password2" required placeholder="Password again..." class="form-control" /> <!-- Give input box red border if data is …