Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django makemessages not parsing static html in templates directory
I'm trying to generate translation files for my project. I have following set up: settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( '/home/------/webapps/django_------/webshop/locale', ) ugettext = lambda s: s LANGUAGES = ( ('en', ugettext('English')), ('de', ugettext('German')), ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ '/home/------/webapps/static_------/templates/', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And in my test html I have: {% extends "front/base.html" %} {% load i18n %} {% block pagetitle %}{{block.super}} | {{ title }}{% endblock pagetitle %} {% block content %} TRANSLATION TEST {% trans "Testing translate" %} {% endblock content %} After setting that up, I ran ./manage.py makemessages -l de After that, django.po file is created in locale/de/LC_MESSAGES with following content #: webshop/settings.py:131 msgid "English" msgstr "" #: webshop/settings.py:132 msgid "German" msgstr "" So the makemessages did work, but it only parsed .py files for translation and it found two lines in my settings files, where LANGUAGES are stored. Yet, tranlation line from my static html file is not parsed. I tried running ./manage.py makemessages -l de -e html but, nothing has changed. I also tried running … -
Django many to many field relationship
I have two models . One model is called Company and the other model is called Product. class Company(models.Model): creator=models.ForeignKey(User,unique=True,on_delete=models.CASCADE,related_name="owner",null=True) addbusiness_to_business_list=models.ManyToManyField(User,related_name="business_added") class Product(models.Model): creator=models.ForeignKey(User,null=True) company=models.ForeignKey(Company,null=True ) Login users can add companies to a list called businesslist . I want the login user to be able to view prouducts posted by only companies they have added to their businesslist. I tried going through the official django page, but their explanation was not clear enough, for me to understand this type of relationship querying . Please help me to understand, and to solve this problem. -
Get senders email - Gmail API
Hello! I've got a Django project connected to Gmail API. At this moment I try to say what are user's top senders and top recipients. My general idea is to get an adress from every email (so that adresses may repeat), put them in some kind of a map and then count how many times did this email appear, something like cnt[emails[i]]++. Then sort it and say who is in the top. But the main problem here is with getting those email adresses. -
Job settings form resetting active/deactive attribute on saving changes in views.py
I wrote an active/deactive functionality for my job page. When a user changes some of the attributes of the job and saves the changes, the active/deactive functionality is set back to deactive. Below are my job_settings and active/deactive functions: views.py: @login_required @user_is_type('communitypartner') def job_settings(request,job_id): job = Job.objects.get(id=job_id) #if the request was a GET if request.method == 'GET': form = JobEditForm(instance=job) elif request.method == 'POST': form = JobEditForm(request.POST, instance=job) #check form validity if form.is_valid() : #get form info job = form.save(request) #job = form.save() #add new orgs/remove removed orgs here message = "Job {0} has been modified.".format(job.name) messages.add_message(request, messages.INFO, message) return render(request, 'main/job_settings.html', {'form':form,'job' : job}) @login_required def job_status_update(request): status = request.GET['status'] job_id = request.GET['Jobid'] if status == 'Active': flag = True else: flag = False job = Job.objects.get(pk=job_id) try: #job = Job.objects.get(pk=job_id) job.active = flag job.save() #write back return HttpResponse(status) except Exception as e: return JsonResponse(status) I need help in fixing this issue and maintaining the original status of the active/deactive functionality -
Elastic Beanstalk does not load the Django admin static files
I have static files in a specific app in my project, and I add that route in my config file as my static route for EB, and as I do this EB doesn't load required CSS files for django admin page. My python.config looks like: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: MyProject/wsgi.py "aws:elasticbeanstalk:container:python:staticfiles": /static/: "MyApp/static/" And I get the following error: Failed to load resource: the server responded with a status of 404 (Not Found) /static/admin/css/responsive.css:1 -
Django model attributes will not show up in template
Im having an issue getting attributes from a model showing up in my template correctly. I am querying my User model and trying to show user.id and/or user.username into my template, the following html code, the template renders with the user object showing, and 'None' when I try user.id or user.username. foo.html {% for user in query %} <ul> <li> {{ user }} </li> <!-- WORKS, Shows User Object --> <li> {{ user.id }}</li> <!-- shows NONE --> <li> {{ user.id }}</li> <!-- shows NONE --> </ul> {% endfor %} I am filtering the users that belong to a specific campaign and attempting to show the user details in my template. views.py def campaignDetails(request, **kwargs): form = AddUserForm(request.POST or None) campaign = Campaign.objects.get(id=kwargs['id']) #Query and Filter Users query = User.objects.filter(campaign=campaign) context = {'campaign': campaign, "form": form, 'query': query} return render(request, 'campaigns/campaignDetail.html', context) Model.py class Campaign(models.Model): id = models.AutoField(primary_key=True) campaign_name = models.CharField(unique=True, max_length=25, blank=True) campaign_start = models.DateTimeField(null=True, default=datetime.datetime.now(), blank=True) campaign_end = models.DateTimeField(null=True, blank=True) class User(models.Model): id = models.AutoField(primary_key=True, null=False) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, null=True, blank=True) username = models.CharField(max_length=25, null=True) -
Django: writing text from uploaded file to text field
I have the following model: class Clean(models.Model): name = models.CharField(max_length=100) cv = models.TextField(max_length=10000) cvfile = models.FileField() I am trying to write the contents of cvfile to cv when the user submits the name and file from the form. I'm sure this can be done as the file and text field will be in the same object. The file will always be .txt so I assume a simple .read() can be performed. Should I have a function that the form calls to perform this? If so how can this be done? def writeCV(self): get_text = cvfile.open().read() #write to cv field somehow return self.cv I am using django 1.9 -
Django tests taking a long time to start
I'm running tests on a django App called stats which uses a Postgre database. The project keeps all tests in a folder ./stats/tests/. When I run a test i.e. python manage.py test stats.tests.test_dataGeneration, several minutes of nothing pass where the text cursor in my command line just blinks. At this early stage I cannot even use a keyboard interrupt to instantly stop the test (keyboard interrupt takes at least 30 seconds to register). Eventually, after several minutes I see the Creating test database for alias 'default' ('test_statsdb')... message which creates the database for testing. From this point the tests always complete in less than 10 seconds (as in django outputs Ran XX tests in 5.00s). I don't know or understand why the tests take so long to start, or what is exactly being executed in the first few minutes. A few days ago I had no issues testing the app. Using --keepdb to recycle the test database between test runs does not noticeably improve the time that running tests takes. I was hoping someone could shed some light on what is happeneing. Example output of test results when i run them with verbosity=2 for extra details: >python manage.py test stats.tests.test_dataGeneration … -
Django DRF create user
I am trying to serialize a CreateUserSerializer(ModelSerializer) My code is as follows. My problem is that it will only create a User and not a UserProfile. models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) """ Many other attributes like display_name, dob, hometown, etc """ serializers.py class CreateUserProfileSerializer(ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create( validated_data[''], validated_data[''], validated_data['']) user.save() user_profile = UserProfile(user=user) user_profile.save() return user_profile And in my views it goes as follows... api/views.py class RegistrationAPI(GenericAPIView): serializer_class = CreateUserProfileSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserProfileSerializer(user, context=self.get_serializer_context()).data, }) If you follow the code, the Response will give me a "RelatedManager has no attribute 'pk'" -
Django debug page shows up even with DEBUG set to `False` in nginx on server
I set up my Django project on a Linode server running Ubuntu 14.04, using this guide for help: https://www.linode.com/docs/web-servers/nginx/deploy-django-applications-using-uwsgi-and-nginx-on-ubuntu-14-04/. I have DEBUG set to False in both settings.py and local_settings.py. When I open a Python shell with python manage.py shell and run from django.conf import settings; print settings.DEBUG, False prints to the terminal. If I run python manage.py runserver 0.0.0.0:8080 in a virtual environmnt and navigate to my.server.ip:8080/path-that-does-not-exist, it takes me to a page that says "Page not found." Why does debug continue to appear when I navigate my browser to a bad request on my Linode server? -
ImportError: No module named nocaptcha_recaptcha, but it is installed
I have this site running on my pc using python manage.py runserver. I also have it running on a Ubuntu16.04 Digital Ocean droplet where this is the only site running. I'm trying to load it on another Ubuntu16.04 Digital Ocean server which has a number of Python2.7 projects running and suddenly I'm getting this ImportError. I'm getting the following traceback in my apache error.log mod_wsgi (pid=5404): Target WSGI script '/var/www/crowdfunder/crowdfunder/wsgi.py' cannot be as Python module. mod_wsgi (pid=5404): Exception occurred processing WSGI script '/var/www/crowdfunder/crowdfunder/wsgi.py'. Traceback (most recent call last): File "/var/www/crowdfunder/crowdfunder/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named nocaptcha_recaptcha I've checked my site-packages and nocaptcha_recaptcha is there. I am wondering if I have something wrong in my Apache .conf file because my virtual environment is python3.5 but the above traceback is python2.7. Here is my .conf file <IfModule mod_ssl.c> <VirtualHost _default_:443> ServerAdmin webmaster@example.co.uk ServerName crowdfunder.example.co.uk ServerAlias www.crowdfunder.example.co.uk DocumentRoot /var/www/crowdfunder WSGIDaemonProcess crowdfunder-ssl python-path=/var/www/crowdfunder python-home=/var/www/crowdfunder/env/lib/python3.5/site-packages WSGIProcessGroup crowdfunder-ssl WSGIScriptAlias / /var/www/crowdfunder/crowdfunder/wsgi.py … -
Django - A link that will update database row before leaving site
I'm quite new to Python development and working on a specific project. I have a list of 'action items' that people can 'claim'. So I created a Model that has all of the information about the action item, including a BooleanField called is_claimed which is defaulted to False. I'm printing out all of the action items in a table, of which the last column is a link to an external site (which is also a URLField in my model). I want to have that last table cell be something like this: <a href="{{ action_item.url }}">Claim and Complete Action Item</a> When someone clicks that URL, I need to update the database to show is_claimed=True. Any ideas or help? Sorry if this question is too simplistic. Learning a lot but need some expert help! Thanks -
How can I get selected option value from html template to Django view.py without form tag via GET ? - Python
I have a small filter on my html template which orders the results by price. I'm trying to get the select value from the filter to later render a new queryset base on the selected value. category.html <select name="precio-filter" class="custom-select" aria-labelledby="dropdownMenuButton"> <option value="0" selected> Todos </option> <option value="1"> Gratis </option> <option value="2"> De 0 a $30 </option> <option value="3"> Mas de $30 </option> </select> view.py class CategoriaListView(ListView): template_name = "clasecentral/categoria.html" def get_context_data(self, *args, **kwargs): context = super(CategoriaListView,self).get_context_data(*args, **kwargs) slug = self.kwargs.get("slug").replace("-", " ") context['categorias'] = categorias[slug] return context def get_queryset(self): slug = self.kwargs.get("slug").replace("-", " ") courses = EdxCourse.objects.filter(search_category__icontains=slug) #filter by price precio = self.request.GET.get('precio-filter') if precio == "0": queryset = courses.filter(price=0) elif precio == "0-30": queryset = courses.filter(price__range=(1,30)) elif precio == "<30": queryset = courses.filter(price__gte=31) else: queryset = courses return queryset.order_by('title') It doesn't seem to be sending any data when I select any option. Please Help!!! -
Perform 3 tasks in a single api call
My current api call flow from my client is as follows: Send data to brand endpoint, retrieve recently inserted id, assign to userData.brand Send data to user endpoint, retrieve recently inserted id, assign to userData.user Send both values to userBrand endpoint This seems like a costly process, so I am thinking of consolidating all the requests into one, but I am not sure how to process it from the server side. I know that I can just use one endpoint, but I don't know to how to use all the serializers/views against one endpoint. So on the client side, this is what I have: In brand.js AdsomaService.registerUser(vm.userData).then(function(data) { vm.successMessage = data.message; vm.userBrandData.user = data.id; }, function error(data) { $log.info(data); vm.errorMessage = data; errorCount++; }); AdsomaService.registerUserBrand(vm.userBrandData).then(function(data) { vm.successMessage = data.message; }, function error(data) { $log.info(data); vm.errorMessage = data; errorCount++; }); if(errorCount > 0) { vm.message = vm.errorMessage; angular.element('#errorMessage').appendTo('body').modal('show'); } else if(errorCount === 0) { vm.message = vm.successMessage; angular.element('#successMessage').appendTo('body').modal('show'); } In adsoma.js function registerUser(userData) { var url = envService.read('apiUrl') + '/user_signup/'; var dataJSON = { email: userData.email, password: userData.password, account_type: userData.accountType }; var req = { method: 'POST', url: url, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, data: $httpParamSerializerJQLike(dataJSON) }; return ($http(req).then(handleSuccess, handleError)); } function registerBrand(brandData) … -
ImageField Form doesn't work in django
I know that there's a lot of similar questions to mine on stackoverflow but none of them fixed my problem I have a form with an imagefield which doesn't work as it should redirect me to the index page when it succeeds but it doesn't yes i can create a payment with that image from the admin panel but the form doesn't work models.py class Payment(models.Model): Address = models.CharField(max_length=255) Payment_ID = models.ImageField(upload_to='payproof') Status = models.CharField(max_length=5, default="X") Review_result = models.CharField(max_length=255, default="Not yet reviewed") created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __unicode__(self): return u'%s'% self.Status def __str__(self): return self.Status views.py def new_payment(request): template ='payment.html' form = PayForm(request.POST or None) if form.is_valid(): form.save() return redirect('index') else: form = PayForm() context = { 'form' : form, } return render(request, template, context) forms.py class PayForm(forms.ModelForm): Payment_ID = forms.ImageField() class Meta: model = Payment fields = ['Address', 'Payment_ID'] -
ForeignKey Error at Django
i spend a lot of hours searching for such an error but didn't found anything, as you know Djangov2.00 requires you to set on_delete=*** with ForeignKey and here i can't do a ForeignKey anymore. my Models.py from django.db import models class makereport(models.Model): Name = models.CharField(max_length=50) VID = models.IntegerField() Callsign = models.CharField(max_length=6) Date = models.DateField(default='yy-mm-dd') SelectAward = models.CharField(max_length=50, choices=(('1', 'Division Online Day'), ('2', 'Pilot Event'), ('3', 'ATC Event'), ('4', 'Pilot Event'))) done = models.ForeignKey('reports', on_delete=models.CASCADE) # reports.ATC = reports.ATC + 1 def __str__(self): return self.Name class reports (models.Model): Name = models.CharField(max_length=50) VID = models.IntegerField() DivisionOnline = models.IntegerField(default=0) ATCEvent = models.IntegerField(default=0) PilotEvent = models.IntegerField(default=0) PilotSupport = models.IntegerField(default=0) ATC = 0 def __str__(self): return self.Name and the Error django.db.utils.IntegrityError: Not Null constraint failed: report_makereport.done_id i don't know what to do with that id ,versions before V2 was working. -
Removing Images, Image_titles, Image_description from a post with multiple images
Hi Djangonauts, I have a post with multiple images. I was able to make the post_create view for this post. Also I was able to create a partially working post_edit view. When I say partially working, what I mean is.. example: If my post has 5 images. I can replace all 5 of my images with alternate 5 images. I can also add more images so my post has 6 or 7 images. what I cannot do is remove any existing images. What makes this a bit more complicated is that the extra images have their own image_title and image_description to them below are my models.py so you know what exactly is going on class Post(models.Model): user = models.ForeignKey(User, related_name='posts') title = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) message = models.TextField() post_image = models.ImageField() def get_absolute_url(self): return reverse('posts:single', kwargs={'username': self.user.username, 'slug': self.slug}) class Prep (models.Model): #(Images) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_prep') image = models.ImageField(upload_to='images/', blank=True, null=True, default='') image_title = models.CharField(max_length=100, default='') image_description = models.CharField(max_length=250, default='') def __str__(self): return self.post.title + " Image" Below is my post_create view which is working perfectly @login_required def post_create(request): ImageFormSet = modelformset_factory(Prep, fields=('image', 'image_title', 'image_description'), extra=7) if request.method == "POST": form = PostForm(request.POST or None, … -
Django : Factorize HTML code
I am building a website about movies, actors etc... And I need your advices in order to factorize my templates. Currently I have 5 templates : base.html : containing header menu, footer [located in the master templates folder] actors : display all the actors (extends base.html) [located in the templates folder from the application 'movie-library'] actor : display one actor and all tbe movies he played in (extends base.html) [located in the templates folder from the application 'movie-library'] movies : display all the movies (extends base.html) [located in the templates folder from the application 'movie-library'] movie : display one movie (extends base.html) [located in the templates folder from the application 'movie-library'] So, in actor.html and movies.html it's the same HTML code to display one movie. And in actors.html and movies.html I have the same HTML to display a pagination bar. How could I factorize those to piece of code ? Thank you. -
Django models.BinaryField Postgres not showing upload button
I have in my model documentFile = models.BinaryField(blank=True, null=True) and I am connected to Postgres. But my admin view does not render this field? Any idea why? -
http profiling tools for django api
I am trying implement the billable concept for few API(s) end of my client resources. I have gone through the doc of silk as well as prometheus.io http://silk.readthedocs.io/en/latest/profiling.html https://prometheus.io/docs/introduction/comparison/ https://stackshare.io/stackups/grafana-vs-graphite-vs-prometheus Still not able to decide which one should i chose. My requirement is observe the api traffic on few important resources and implement the price based access like: 200$ monthly for 10 api call a minutes for one month. 350$ monthly for 25 api call a minutes for one month. I can't missed a single api call please suggest the best available options. -
Django - access ManyToManyField right after object was saved
I need to notify users by email, when MyModel object is created. I need to let them know all attributes of this object including ManyToManyFields. class MyModel(models.Model): charfield = CharField(...) manytomany = ManyToManyField('AnotherModel'....) def to_email(self): return self.charfield + '\n' + ','.join(self.manytomany.all()) def notify_users(self): send_mail_to_all_users(message=self.to_email()) The first thing I tried was to override save function: def save(self, **kwargs): created = not bool(self.pk) super(Dopyt, self).save(**kwargs) if created: self.notify_users() Which doesn't work (manytomany appears to be empty QuerySet) probably because transaction haven't been commited yet. So I tried post_save signal with same result - empty QuerySet. I can't use m2mchanged signal because: manytomany can be None I need to notify users only if object was created, not when it's modified Do you know how to solve this? Is there some elegant way? -
Excluding Objects Based Upon Field Char Len
I have a content field in the Data model, like, class Data(models.Model): content = models.TextField() So, while querying the Data model I want to exclude that Data in which content characters length is less than 50 characters. How can we do that? I tried something like, Data.objects.exclude(content__len__lt=50) But it didn't work. It said Unsupported lookup 'len' for TextField or join on the field not permitted. -
Celery tasks registering in multiple queues
I am using celery in Django (1.9) with RabbitMQ server. I have four different queues and I am registering a task in one of these four queues. The issue is all my tasks are registered in all four queue. Like I have a task named add and have four queues A, B, C and D. Ideally task should be registered in only A queue (As I registered) But It is showing in all four queues. could not rectify what is the actual issue. Please help. -
give unique names for images uplodaded via imagefield django
I have a form with an imagefield in it and i want to give the images unique names to avoid overwriting how can i acheive that ? models.py class Payment(models.Model): Address = models.CharField(max_length=255) Payment_ID = models.ImageField(upload_to='pay_proof/') Status = models.CharField(max_length=5, default="X") Review_result = models.CharField(max_length=255, default="Not yet reviewed") created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __unicode__(self): return u'%s'% self.Status def __str__(self): return self.Status -
Django form choice
I have a model "A" and model "B"(both are just containing the image). I would like to be able to pick one of the image from model "A", change it and save to the model "B". I need to make a form which will show me on template the list of visible images from model "A". All what i achieved is just a rolling list with the models "A" names.