Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Queue is empty even though there are items in it
I have a django app in which I'm using Queue.Queue. class DataThread (threading.Thread): data_queue = Queue.Queue() In another thread I have stuff being added to the queue like below DataThread.data_queue.put(msg) And it is being consumed in DataThread in the below fashion while True: self.sendMessagesFromQueue() time.sleep(1) def sendMessagesFromQueue(self): try: while not DataThread.data_queue.empty(): data = self.data_queue.get() #Some processing logic except Exception as e: print str(e) Now this works when I run it using python manage.py runserver (using django itself). But it doesn't work when I use guinicorn to run this app. Because the queue empty check keeps returning its empty but when i check queue size at the location I add to the queue, it keeps building up. -
How does the url parameter api_key work for a large number of requests?
I'm messing around with building a mapping tile server and want to implement an api_key so that users can only get the data associated with that key. I'm looking at sites like mapbox, mapzen, and openmaptiles. Each of these companies have an api_key or access token as a query string parameter and I'm at a loss as to how the api_key is checked for hundreds or thousands of requests. Is it a database lookup each time a request is made or is it comparing against a file or some other method? Users have the ability to create and remove api_keys so i assume it needs to do some sort of check to ensure the api_key is valid. I've tried implementing the check through django, and it worked, but was slow and i couldn't cache the tiles. Would a good workflow for this be to cache the available api_keys in something like redis and update the cache when an api_key is modified? Thanks -
Python Django forms replaces old inputs
I am currently trying to impliment a registration form but everytime I test it out, the new registrant replaces the old registration. So I am unable to have more than one user at a time. any help would be great because I do not know what to do. Thanks. My views: def register_page(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): cd = form.cleaned_data new_user = bitcoinUser(first_name=cd['first_name'], last_name=cd['last_name'], phone_number=cd['phone_number']) new_user.save() -
How to add button in django admin site?
I do want to know how to add button in django admin site.I tried many stuff but I couldn't able to do the stuff.I want to add a reset button for an attribute in the model where it should regenerate the value for the attribute. -
Django JSONField
We have been using JSONField from jsonfield library for a while, but now we want to use native PostgreSQL JSONField. So I would like to know whether it is possible to change field types for existing models preserving old field names and without loosing any data. Thanks. -
Why is Django Photologue not automatically deleting images from the project directory?
According to https://github.com/jdriscoll/django-photologue/wiki, Photologue cleans up after itself. Unused files and folders are deleted automatically. However, when I add a picture in the admin interface and then delete it, the image files are not deleted from the associated folder. I am working on a development server using python manage.py runserver, and I have tried deleting the image, exiting the server, running python manage.py migrate as well as python manage.py makemigrations (because why not?) and the image files are still there in the /media/photologue/photos/ folder as if nothing happened. I have set up my MEDIA and STATIC settings according to the recommendations of https://timmyomahony.com/blog/static-vs-media-and-root-vs-path-in-django/ and set up Photologue according to their Read-the-Docs page. Before discovering this issue I fixed a problem with broken thumbnails by implementing the recommendations here: django-photologue thumbnails not loading. Am I misunderstanding the meaning of deleted automatically or is there something I can do to fix this behavior? To be clear, I want the delete command in the admin interface to also remove the physical files in the associated directory. -
Django manytomany field using a postgresql view
I am attempting to create a ManyToManyField in a model with a table in the database connected to a view in the database. The model connected to the view (named precheck_check) migrated successfully so the only new code is applicable_checks = models.ManyToManyFields(Check, related_name = '+'). When I try to migrate with the added code I get django.db.utils.ProgrammingError: referenced relation "precheck_check" is not a table" Models.py from future import unicode_literals from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.validators import validate_slug,validate_comma_separated_integer_list from static import validators class Check(models.Model): pkey = models.IntegerField(primary_key=True) cif = models.CharField(max_length=255) check_name = models.CharField(max_length=255) description = models.TextField() class Meta: managed = False # Create your models here. class Job(models.Model): user = models.ForeignKey('auth.User') jobID = models.CharField(max_length=50, validators=[validate_slug]) original_file = models.FileField(upload_to='temp',validators = [validators.validate_zip]) rev = models.IntegerField() create_date = models.DateTimeField(default=timezone.now) file_name = models.CharField(max_length=255, null = True) applicable_checks = models.ManyToManyField(Check, related_name = '+') def save(self): last_rev = Job.objects.filter(user_id=self.user_id).filter(jobID=self.jobID).order_by('-rev') if last_rev: self.rev = last_rev[0].rev + 1 else: self.rev = 1 super(Job,self).save() def __unicode__(self): return self.jobID + " rev " + str(self.rev) class Meta: indexes = [ models.Index(fields=['user','jobID']), ] unique_together = ("user","jobID","rev") ordering = ['-create_date'] get_latest_by = 'create_date' Where am I going wrong? -
Attaching a form to each Post in a list of Posts
So I have a List of Posts on my site and I would like to implement something like a "instant Comment". The Problem is that when I define a Form in the views.py and submit it, all Blogposts get the Comment. Something like instance = get_object_or_404(Post,...) or instance = get_list_or_404(Post,...) does not work. Then I tried to implement a context_processor for the form but same problem. Now I want to initialize a API to take care of the task but maybe someone has a better Idea on how to solve that issue and I don't have to try different things all the time. my Blogpost are a normal QuerySet like articles = Post.objects.all() the form needs some information from the Post like content_type and id. If any other Informations are required leave a comment. -
How can I display a global alert in Django admin panel?
I don't want it to show up after performing an action, I want it to show up on all pages of the Django admin panel. Is this possible? -
python : Error in crawler library
i have a ModuleNotFoundError in my script and i don't know how to solve it, my script was writting in python 1 .4 and i'm trying to make it compatible with python 2.7.6 i'm trying to do this imports(i already installed crawler using pip install crawler): from crawler.app.pdf_parser import normalize from crawler.app.pdf_parser.normalize import parse_partners_rg_rne from crawler.app.pdf_parser.utils import remove_accents and the error i'm getting is ModuleNotFoundError: No module named 'crawler.app' -
API data in Django listview
Having trouble figuring out how to add data from an API into a listview in Django. I am using django-restframework, and have an internal API for a portion of my data. Ultimately, I want to display all the information from my Freight model, into a list view. I know I have to create a context, but I'm not sure how to do that with API data. Here is my code so far: @method_decorator(login_required, name='dispatch') class ManifestEngineView(ListView): model = Freight template_name = 'pages/engine.html' def get_context_data(self, **kwargs): freight_list = requests.get('http://localhost:8000/api/freight/').json() for freight in freight_list: print(freight['pu_customer']) I can print the customer name to the console, but I can't figure out how to put it in a context I can pass to my template and use. The template should have a box with all the necessary data from the model. -
django error: NOT NULL constraint failed
i am getting this error while i was trying to make two forms (with two models) and process that in the view. my SongForm is not saving its data in database while AlbumForm is perfectly saving its data.could anyone please help me out. views.py- def formm(request): if request.method=='POST': songform = SongForm(request.POST) albumform=AlbumForm(request.POST) if songform.is_valid() and albumform.is_valid(): songform.save() albumform=albumform.save(commit=False) albumform.date=timezone.now() albumform.save() return redirect("result") forms.py- from django import forms from . models import Album,Song class SongForm(forms.ModelForm): class Meta: model=Song fields=('song_title','genre') class AlbumForm(forms.ModelForm): class Meta: model=Album fields=('album_title',) models.py- from __future__ import unicode_literals from django.db import models class Album(models.Model): album_title=models.CharField(max_length=50) date=models.DateTimeField(blank=True,null=True) def __str__(self): return self.album_title class Song(models.Model): song_title=models.CharField(max_length=50) genre=models.CharField(max_length=50) album=models.ForeignKey(Album,on_delete=models.CASCADE) def __str__(self): return self.song_title formmpage.html- {% extends "musicapp/basepage.html" %} {% block content %} <form method="POST" class="post-form"> {% csrf_token %} {{ songform.as_p }} {{ albumform.as_p }} <button type="submit" class="btn btn-info">POST</button> </form> {% endblock %} Do correct me, where actually i am doing wrong. i guess, it is in my views.py. Thanks. -
django integrityError. not NULL constraint failed
i am getting this error while i am trying to make two forms ( with two models) after submitting the form. also SongForm data is not saving in database while AlbumForm is perfectly saving. views.py- def formm(request): if request.method=='POST': albumform=AlbumForm(request.POST) songform = SongForm(request.POST) if albumform.is_valid() and songform.is_valid(): albumform=albumform.save(commit=False) albumform.date=timezone.now() albumform.save() and songform.save() return redirect("result") else: albumform=AlbumForm() songform=SongForm() return render(request,"musicapp/formmpage.html", {'albumform':albumform, 'songform':songform}) -
Error while performing migrations with django-constance
Before answering: Yes I already have 'constance.backends.database' in my INSTALLED_APPS and CONSTANCE_CONFIG as per the default implementation I have just setup an existing project that has django-constance "https://github.com/jazzband/django-constance" When I makemigrations or migrate, i get the following exception: Traceback (most recent call last): File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "constance_config" does not exist LINE 1: ...ce_config"."key", "constance_config"."value" FROM "constance... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/core/management/base.py", line 342, in execute self.check() File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/saad/virtualenvs/sentimeter_backend/lib/python3.5/site-packages/django/urls/resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) … -
Django DEBUG setting never evaluates as a boolean - only displays debug log
I have some GA code that we need to put on the live site only. So I'm trying to check the value of DEBUG, which in settings.py is being set to True currently. However, in my template file settings.DEBUG will not evaluate to either True or False. If I print out the variable, it displays the debug log. I tried following this guide: How to check the TEMPLATE_DEBUG flag in a django template? by adding the context_processors.py and still in my template file DEBUG comes out as the debug log. -
Why isn't vim-snipmate UltiSnips for Django not working?
I'm running Vim 8.0.124 and I've installed the vim-snipmate plugin to use in my Python and Django development. I followed the instructions by creating a .vimrc file that contains the following: # ~/.vimrc set nocompatible " Required by Vundle filetype off " Required by Vundle " Begin Vundle settings ========================================================== " set rtp+=~/.vim/bundle/Vundle.vim call vundle#begin() Plugin 'VundleVim/Vundle.vim' Plugin 'MarcWeber/vim-addon-mw-utils' Plugin 'tomtom/tlib_vim' Plugin 'garbas/vim-snipmate' # Optional Plugin 'SirVer/ultisnips' Plugin 'honza/vim-snippets' call vundle#end() filetype plugin indent on " " End Vundle settings ========================================================== " SnipMate autocmd FileType python set ft=python.django autocmd FileType html set ft=htmldjango.html " UltiSnips let g:UltiSnipsExpandTrigger="<tab>" let g:UltiSnipsJumpForwardTrigger="<c-b>" let g:UltiSnipsJumpBackwardTrigger="<c-z>" let g:UltiSnipsEditSplit="vertical" Installing vim-snipmate includes the creation of these four files: ~/.vim/bundle/vim-snippets/snippets/django.snippets ~/.vim/bundle/vim-snippets/snippets/htmldjango.snippets ~/.vim/bundle/vim-snippets/UltiSnips/django.snippets ~/.vim/bundle/vim-snippets/UltiSnips/htmldjango.snippets I have two questions. First, why are the UltiSnip Django snippets not working? The snippets in snippets/django.snippets work but those in the UltiSnips django.snippets file don't. If I open a file test.py and type "fdate" where fdate should expand into a Django DateField, nothing happens (other than a tab is entered). Initially, when the UltiSnips weren't working, I went to its Github page and read the instructions which seemed to indicate I should add the SirVer plugin so I did. Even then, then don't … -
Return just the number when using the np.divide function with dtype:float64
I apologize as I am new to Python and Django. I have created a class object that retrieves information from a db and stores it in pandas so I can use some data science library's for manipulation. class IntDailyGoals (object): def __init__(self, begin_date, end_date, store=None): self.begin_date = begin_date self.end_date = end_date self.store = store self.int_mnth_goal = pd.DataFrame(list(StoreGoalsInput.objects.values('store_number', 'interest', 'date'))) self.int_mnth_goal['interest'] = pd.to_numeric(self.int_mnth_goal['interest']) self.int_mnth_goal['date'] = pd.to_datetime(self.int_mnth_goal['date']) self.mnth_goal_int =self.int_mnth_goal[(self.int_mnth_goal['date'] >= self.begin_date) & (self.int_mnth_goal['date'] <= self.end_date) & (self.int_mnth_goal['store_number'] == self.store.store_number)] self.mnth_goal_int= self.mnth_goal_int['interest'] self.tot_workingdays = np.busday_count(np.datetime64(self.begin_date), np.datetime64(self.end_date), weekmask='Mon Tue Wed Thu Fri Sat') self.div_intmnthgoal_workingdays = round(np.divide(self.mnth_goal_int, self.tot_workingdays),2) def get_div_goalsint_wdays(self): div_goalsint_wdays = self.div_intmnthgoal_workingdays return div_goalsint_wdays def __str__(self): return self.get_div_goalsint_wdays() This returns: 2 6558.4 Name: interest, dtype: float64 I just need it to return the int 6558.4 as this is being displayed in a Django template. I have tried this: def get_div_goalsint_wdays(self): div_goalsint_wdays = self.div_intmnthgoal_workingdays['interest'] return div_goalsint_wdays but I get a KeyError: 'interest' Any help would be greatly appreciated! -
django - image isn't saving, all other fields are
When I update the user profile via the view everything is saving to the db except the image. The forms are validating but image isn't being saved. I can log in the admin portal and successfully add an image to an existing instance. I assume my problem lies in my html template but I can't figure out what it is. **Btw I've read multiple similiar post but none I believe addresses my issue. form.py class EditUserForm(forms.ModelForm): template_name='/something/else' class Meta: model = User fields = ( 'email', 'first_name', 'last_name', ) class EditProfileForm(forms.ModelForm): template_name='/something/else' class Meta: model = UserProfile fields = ( 'description', 'city', 'website', 'phone', 'image', ) views.py @transaction.atomic def edit_profile(request): if request.method == 'POST': form = EditUserForm(request.POST, instance=request.user) form2 = EditProfileForm(request.POST, instance=request.user.userprofile) if form.is_valid() and form2.is_valid(): form.save() form2.save() return redirect(reverse('accounts:view_profile')) else: form = EditUserForm(instance=request.user) form2 = EditProfileForm(instance=request.user.userprofile) args = {'form': form, 'form2':form2} return render(request, 'accounts/edit_profile.html', args) models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) image = models.ImageField(upload_to='profile_image', blank=True) def __str__(self): return self.user.username edit_profile.html <div class="container"> {% if form.errors %} <ol> {% for field in form %} <H3 class="title"> <p class="error"> {% if field.errors %}<li>{{ field.errors|striptags }}</li>{% endif … -
Error importing module: 'No module named provider'
I'm working on my first django project, It was working fine when I restarted the server I have this error django.core.exceptions.ImproperlyConfigured: WSGI application 'webtracking.wsgi.application' could not be loaded; Error importing module: 'No module named provider' ( webtracking is my project's name) Thank you -
How to access Django ForeignKey model filed?
I have two django models model A class A(models.Model): aname = models.CharField(max_length=64, verbose_name='name') and model B class B(models.Model): bname = models.CharField(max_length=64, verbose_name='name') mod = models.ForeignKey(A, related_name='a_b',null=True,on_delete=models.CASCADE) The serializer for model B is class HotelSerializer(serializers.ModelSerializer): mod= ASerializer(many=False, read_only=True) class Meta: model = Hotel fields = (','id','bname','mod.aname') I want the aname field of model A to be accessed with the serializer of model B. Using mod.aname doesn't work. It says Field name mod.aname is not valid for model B. How can i do it? -
Filter with variable as param Django
I have this view in Django: def stutente(request): cog = request.GET['cognome'] nom = request.GET['nome'] utenti = Utente.objects.order_by('cognome') utenti_presenti=Utente.objects.filter(cognome="Acanfora") utenti_assenti=utenti utenti_assenti=Utente.objects.filter(~Q(cognome="Acanfora")).order_by('cognome') return render(request,"accesso/stato.html",{ 'utenti_presenti' : utenti_presenti, 'utenti_assenti' : utenti_assenti, }) I would like to pass as parameter in the filter not the string "Acanfora" but the variable cog, that is the GET request. If I do: utenti_presenti=Utente.objects.filter(cognome=cog) and utenti_assenti=Utente.objects.filter(~Q(cognome=cog)).order_by('cognome') not function. Can you help me? -
How to save Json in the django database from Javascript
I will generate a json and save it in a string variable, and I need to save the whole json in my database. -
Javascript - constructor cannot be called as a function
Please, could you tell me what's wrong in this code ? This is Django framework + JS. I want to make my div block to be visible when I click on the button. Everything else is working fine. I mean my boucle is ok and comment.id return a unique ID. When I click on the button, I have a JS error : "constructor cannot be called as a function" Uncaught TypeError: Failed to construct 'Comment': Please use the 'new' operator, this DOM object constructor cannot be called as a function. at HTMLButtonElement.onclick ((index):218) onclick @ (index):218 (index):218 Uncaught TypeError: Failed to construct 'Comment': Please use the 'new' operator, this DOM object constructor cannot be called as a function. at HTMLButtonElement.onclick ((index):218) onclick @ (index):218 My code : <!-- Button see comments --> <button onclick="Comment()" type="button" class="w3-button w3-theme-d1 w3-margin-bottom"> Commenter </button> <!-- end button --> {%for comment in comments%} {%if comment.articles.id == post.id or comment.statut.id == post.id %} <!-- Bloc comments--> <div id="{{comment.id}}" style="overflow-wrap: break-word; display: none;" class="w3-container w3-card-2 w3-white w3-round w3-margin"> <p>{{comment.text}}</p> <p style="width: 100%; text-align: right;"> <img alt="Avatar" class="w3-circle-articles" style="vertical-align:middle;" src="{{media}}{{comment.author.profile.avatar}}" /> <span style="color: #0477BF;"">{{comment.author}}</span> le {{comment.date|date:"d F"}} à {{comment.date|date:"H:m"}} </p> </div> <!-- End bloc comments --> <!-- JAVASCRIPT … -
Customize Django report builder base.html
I installed django-report-builder and followed the configuration like: 1. pip install django-report-builder 2. Add report_builder to INSTALLED_APPS 3. Add url(r'^report_builder/', include('report_builder.urls')) to url.py url patterns 4.Ensure django.core.context_processors.static and django.core.context_processors.media are in TEMPLATE_CONTEXT_PROCESSORS Note: For Django 1.8+ template context processors have been moved from django.core.context_processors to django.template.context_processors. The settings for template context processors have moved from TEMPLATE_CONTEXT_PROCESSORS to be part of the template engine specific configuration in TEMPLATES, as described here. 5.Sync your database. python manage.py migrate 6.Use Django admin or navigate to /report_builder/ requirement: I am trying to customize /report_builder/base.html, so that I can change look and feel of Django-report-builder.But whenever I extend with my base class using {% extends "base.html" %}^. Can anyone suggest which file I should be actually customizing for django-reort-builder ? -
python variable reference unexpectedly changing behaviour
I'd like to understand what's the cause of this totally unexpected change of behaviour and how it could be implemented. I come from JS world and this is very likely to be impossible to implement in any way.. Calling a fn by traversing an object gets a different result from when this object is first assigned to a new variable: >>> from core.models import SomeModel >>> s = SomeModel.objects.get(id=45) >>> s.user.profile.needs_review True >>> s.user.profile.needs_review = False >>> s.user.profile.needs_review True >>> profile = s.user.profile >>> profile.needs_review True >>> profile.needs_review = False >>> profile.needs_review False This is really disturbing because in any language I've worked with this would execute likewise.