Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django request.user.userprofile.save() not working
I suppose to save user's avatar and contact. When I create a form of userprofile and update model with request.user.userprofile.save(), it turns out that nothing changed in database. I've tried many ways, including ModelForm, but I think it has nothing to do with the form, cuz when I directly using UserProfile.objects.filter(id=123).update(avatar=my_avatar) in view, no error raised but still nothing changed in database. Very strange is that When I debug it, slow the program down, it worked! class UserProfile(models.Model): user = models.OneToOneField(User) avatar = models.CharField(max_length=100, blank=True, null=True) contact = models.CharField(max_length=64, blank=True, null=True, verbose_name=u'联系人') class PostSetUserProfileForm(forms.Form): avatar = forms.CharField(max_length=100, required=False) contact = forms.CharField(max_length=64, required=False) def save(self, instance): instance.avatar = self.cleaned_data.get('avatar', '') instance.contact = self.cleaned_data.get('contact', '') instance.save(using='master') class PostUpdateUserProfileView(FormView, AjaxResponseMixin): @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): self.user = request.user return super(PostUpdateUserProfileView, self).dispatch(request, *args, **kwargs) def get_form(self, form_class=None): return PostSetUserProfileForm(**self.get_form_kwargs()) def form_valid(self, form): form.save(self.user.userprofile) return self.ajax_response({'msg': 'success'}) def form_invalid(self, form): self.update_errors(form.errors.popitem()[-1][0]) return self.ajax_response({}) I thought this error might have sth to do with autocommit. -
Select in template parents foreign key
i have in mu Model: class Profile(models.Model): user = models.OneToOneField(User, blank=True, null=True) phone_number = models.CharField(max_length=20, blank=True, null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) is_administrator = models.BooleanField(default=False) def __str__(self): return '{0}\'s profile'.format(self.user.username) class Company(models.Model): created_date = models.DateTimeField(default=timezone.now, null=True) name = models.CharField( max_length=200) class Invitation(models.Model): created_date = models.DateTimeField(default=timezone.now, null=True) date = models.ManyToManyField(Date) speaker = models.ForeignKey(Speaker, on_delete=models.CASCADE) invited_to = models.ForeignKey(Company, on_delete=models.CASCADE) talk = models.ManyToManyField(Talk) def __str__(self): return self.speaker.name + ' by ' + self.invited_to.name class Speaker(models.Model): name = models.CharField(max_length=200, blank=False, null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) talk = models.ManyToManyField(Talk) so in my view i send invites = Invitation.objects.all() and what i need in my template is to access Profile's name: Invitation.invited_to.Company.Profile.name, and also Invitation.speaker.Company.Profile.name. Is there any wasy way to do that? -
How to install Django project with all modules?
I created a Django's application which use some additional modules like crispy_forms. I would like to send this application to my friends to test it. But I don't know how can they just install it and run it? Is it possible? Application using also database PostgreSQL. What is the simplest way to just run this application from any place with no errors and problems on the start? I found only information about https://docs.djangoproject.com/en/1.10/intro/reusable-apps/ and packed my app, but I don't know how to install it. -
How do I Update An User who signed up in my Allauth app
My user have signed up successfully used Allauth application. The social application/sign in form have collected basic data as e-mail and data. Once logged in my web application I want to create a web page to UPDATE that data if the user is willing so. Also I need to update extra data that wasn't recquired during the sign in step as personal fields like gender, birth date, etc. How do I do that? I didn't find any explanation about this in the web. If someone knows a web tutorial or site that explains my question I will validate it as a valid answer too. Many thanks. -
What's the point of {0} placeholder
So I'm currently going through an django+angular tutorial, and in it, one of my model's unicode function is this def __unicode__(self): return '{0}.format(self.content)' My question is why is this necessary to use this placeholder? Could i have not just done this and achieve the same result def __unicode__(self): return self.content content is a TextField -
Django modify bridge table
I have two models in my django application, event/user, that have a many-to-many relationship. Event can have many attendees(user). User can attend many events. Django automatically made a bridge table for for this relationship. My question is how can I add new fields to this table using migrations as there is not a model for this Bridge table. -
django form.is_valid() returns 0 always in case of file upload
I have following form (along with two other forms): class UploadFileForm(forms.Form): file = forms.FileField() The following is my html: <div class="panel panel-danger"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> <form action="" method="POST" role="form" enctype="multipart/form-data"> {% csrf_token %} <legend>Upload a file: </legend> <div class="form-group"> <input type="file" name="file" class="form-control" id="" placeholder="Input field"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> File handling is done: if request.method == 'POST': print "I am in request." print request.FILES['file'] # create a form instance and populate it with data from the request: formName = NameForm(request.POST) formHandle = HandleForm(request.POST) fileForm = UploadFileForm(request.POST) successMessages = [] failureMessages = [] # check whether it's valid: # if fileForm.is_valid(): print "file is uploaded." print request.FILES['file'] else: print "File form is not set." Always else condition is executed, even if the value in request.files is set. What am I doing wrong? -
How to captalize letter on django rest serialize
In my database i have a nome field, and in this charfield all data is uppercase. I need return in the title format, just title() method does. example: data in my field name: CAFE SANTA CLARA SOLUVEL GRAN. RF 50G-12501 i need return like that: Cafe Santa Clara Soluve Gran Rf 50G-12501 I use django rest serializer to return this data. Whats the best way to do this? In my model, serializer class or my view? Tks! model: class Produto(models.Model): def __str__(self): return self.nome.encode('utf-8') def __unicode__(self): return self.nome.encode('utf-8') categoria = models.ForeignKey(ProdutoCategoria, null=True, blank=True) marca = models.ForeignKey(ProdutoMarca, null=True) nome = models.CharField(max_length=256, null=True) #its this column unidade = models.CharField(max_length=256, null=True, db_column='unid') ean = models.CharField(max_length=256, null=True) ncm = models.DecimalField(max_digits=65, null=True, decimal_places=2) fator = models.DecimalField(max_digits=100, null=True, decimal_places=2) fornecedor = models.CharField(max_length=256, null=True) imagem = models.TextField(blank=True, null=True) id_externo = models.IntegerField(null=True, blank=True) top = models.NullBooleanField(null=True, blank=True) serializer: class ProdutoSerializer(serializers.ModelSerializer): marca = serializers.CharField(source='marca.nome') categoria_pai = serializers.IntegerField(source='categoria.pai.id') class Meta: model = Produto fields = ( 'ean', 'id', 'nome', 'imagem', 'marca', 'categoria', 'categoria_pai' ) -
Django NoReverseMatch at /
Everything was perfect in my code, but after when I add "(?P\d+)", to one of mine url, I've receveid error: NoReverseMatch at / Reverse for 'day_data_multiadd' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['day_data_multiadd/(?P\d+)/$'] I have no idea whats going. I'm beginner so probably that will be very easy... view.py def get_number_of_lines(request): if request.method == 'POST': generate_form = multiadd_generate_form(request.POST) if generate_form.is_valid(): no_of_lines = generate_form.cleaned_data['no_of_lines'] return HttpResponseRedirect(reverse('multi_add', kwargs={'no_of_lines': no_of_lines})) else: generate_form = multiadd_generate_form() c = RequestContext(request, {'generate_form': generate_form}) return render_to_response('no_lines.html', c) def day_data_multiadd(request, no_of_lines): no_of_lines = int(no_of_lines) CostFormSet = modelformset_factory(Cost, form=data_add_form extra=no_of_lines) if request.method == 'POST': formset = CostFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() else: formset = CostFormSet() c = RequestContext(request, {'formset': formset}) return render_to_response('multi_add.html', c) forms.py class data_add_form(forms.ModelForm): class Meta: model = Cost fields = ['title', 'value', 'publish', 'category'] class multiadd_generate_form(forms.Form): formy = forms.IntegerField(max_value=30, min_value=1) class BaseLineFormSet(BaseFormSet): def __init__(self, *args, **kwargs): super(BaseLineFormSet, self).__init__(*args, **kwargs) no_of_forms = len(self) for i in range(0, no_of_forms): self[i].fields['formy'].label += "-%d" % (i + 1) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.current_detail, name='current_detail'), url(r'^stats$', views.costs_stats, name='costs_stats'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/$', views.month_stats_detail, name='month_stats_detail'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$', views.day_stats_detail, name='day_stats_detail'), url(r'^(?P<year>\d{4})/$', views.year_stats_detail, name='year_stats_detail'), url(r'^day_data_multiadd/(?P<no_of_lines>\d+)/$', views.day_data_multiadd, name='day_data_multiadd'), url(r'^no_line$', views.get_number_of_lines, name='get_number_of_lines'), url(r'^delete/(?P<id>\d+)/$', views.day_data_delete, name='day_data_delete'), url(r'^add$', … -
Static Files Under the Same Domain with Django
Django recommends serving static content from a seperate server. I'd like the domain of my static files to be the same as my Django server's (including subdomain). Is this possible? If it matters, I'm on Heroku. Thanks! -
Issue of Exporting+Submitting an html form efficiently?
I'm working on my first Django project, and I'm confused about how to send a form from the server to a user, and a filled form back to the server. (i'm using jQuery with AJAX by the way). I want to avoid sending 'massive' chunks of html via the network. Right now, on the POST side, I'm using jQuery's serialize method for a submission, which accomplishes my goal of not having to send a 'big' chunk of data. But the user is GETing the forms by fetching the html form (generated from a Django template) with no alteration to it, 'straight up'. (I'm sorry if my question is too broad for Stack Overflow. The reason for me posting this is that I feel very confused about this general issue, and after doing some searching here and via Google, I haven't found other answers that really clear my doubts about what this issue requires): (Is somehow transforming the html form to a JSON string and exporting that to the user what I'm looking for? Btw, some forms will also have file uploads like pictures) If so, how should I got about doing so in my Django view using an html template, … -
Redirect error with django. Nothing seems to work
I know there are many post about django redirecting. However I did not find anything like my problem. I don't know what's happening but I've read a lot and still haven't found anything about it. So I post my code. My project urls.py: from django.conf.urls import url, include urlpatterns = [ url(r'^backbone', include('backbone.urls', namespace='backbone')), ] My app urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^/shell$', views.shell, name='shell'), url(r'^/login$', views.login, name='login'), ] My app views.py def shell(request, app='cashier'): if 'user' not in request.session: response = redirect('backbone:login', app=app) else: response = render(request, 'template.html') return response The error appearing on console: django.urls.exceptions.NoReverseMatch: Reverse for 'login' with arguments '()' and keyword arguments '{'app': 'app'}' not found. 1 pattern(s) tried: ['backbone/login$'] The error on browser: NoReverseMatch at /backbone/shell Reverse for 'login' with arguments '()' and keyword arguments '{'app': 'app'}' not found. 1 pattern(s) tried: ['backbone/login$'] Request Method: GET Request URL: http://192.168.1.79/backbone/shell Django Version: 1.10.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'login' with arguments '()' and keyword arguments '{'app': 'app'}' not found. 1 pattern(s) tried: ['backbone/login$'] Exception Location: /usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py in _reverse_with_prefix, line 392 Python Executable: /usr/bin/python3 Python Version: 3.5.2 Python Path: ['/home/ipi/workspace/RamoSP', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages'] Server time: … -
Django: Best way to evaluate condition
I'm developing an appointments manager for a doctor's office. There is an option to create a schedule so, for example, if a person wants to come three times a week, (monday, wednesday and friday) at 9:00 starting on 01/02/17 up to 02/24/17 the user can create a schedule by giving just that data: start date, end date, time, days of the week. The app would alert the user if an appointment is already booked in that time so the user has the option to change the schedule or accept anyway, which will create the schedule skipping the previously occupied appointments. I'm using django framework to develop the app In my Schedule model I have the following code monday = models.BooleanField(default=False) tuesday = models.BooleanField(default=False) wednesday = models.BooleanField(default=False) thursday = models.BooleanField(default=False) friday = models.BooleanField(default=False) saturday = models.BooleanField(default=False) I'm having trouble figuring out the best way to check if an appointment is already booked between the input dates. I don't know if the question is clear so I'll leave an example: I want to schedule appointments from 01/02/17 to 02/24/17 every tuesday and thursday at 9:00. An appointment was previously created on 01/19/17 at 9:00 for another patient. The app has to alert … -
Django Ngix error unknown directive in /etc/nginx/sites-available/unom
I am having an issue in /etc/nginx/sites-available/unom when i use sudo ngnix -t with a Django project I keep getting the error: nginx: [emerg] unknown directive "xxx\.xx\.xx\.xxx" in /etc/nginx/sites-enabled/unom:4 nginx: configuration file /etc/nginx/nginx.conf test failed The server block markup is: server { listen 80; xxx\.xx\.xx\.xxx; location = /favicon.ico { access_log off; log_not_found off; } location /static_in_env/ { root /home/ubuntu/devunom; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/devunom/unom.sock; } } } I have tried the IP with \ and without. My file structure of the project is: ubuntu@xyz home/ubuntu devunom - envunom //virtualenv - static_in_env - unom -home -unom // the main app with settting.py -manage.py I am using ubuntu server 16.04 Any pointer would be great Thank you -
Django rest framework Api documentation Swagger 2.0
I am having a hard time configuring Swagger UI Here are the very explanatory docs: https://django-rest-swagger.readthedocs.io/en/latest/ YAML docstrings are deprecated. Does somebody know how to configure Swagger UI (query parameters, etc) from within the python code? If it's impossible for some strange reason. Is there any working alternative or is it the best for me to just go and write, api documentation by hand? -
NameError: name 'anon_session_score' is not defined in django 1.10
Help please. this is model.py from django.db import models import re from model_utils.managers import InheritanceManager # Create your models here. class Subject(models.Model): subject=models.CharField(max_length=250,unique=True, blank=False) class Meta: verbose_name="Предмет" verbose_name_plural = "Предметы" def __str__(self): return self.subject class Quiz(models.Model): name=models.CharField(max_length=120,blank=False) url=models.SlugField(max_length=120,blank=False) subject=models.ForeignKey(Subject) random_order = models.BooleanField(blank=False,default=False) answers_at_end = models.BooleanField(blank=False,default=False) def save(self,force_insert=False, force_update=False, *args,**kwargs): self.url = re.sub(r'\s+','-',self.url).lower() self.url=''.join(letter for letter in self.url if letter.isalnum() or letter=='-') super(Quiz,self).save(force_insert,force_update,*args,**kwargs) class Meta: verbose_name="Тест" verbose_name_plural="Тесты" def __str__(self): return self.name def get_questions(self): return self.question_set.all().select_subclasses() def anon_score_id(self): return str(self.id)+"_score" def anon_q_list(self): return str(self.id)+"_q_list" def anon_q_data(self): return str(self.id)+"_data" class Question(models.Model): quiz = models.ManyToManyField(Quiz,verbose_name=u"Тест",blank=True) figure = models.ImageField(upload_to='uploads/%Y/%m/%d',blank=True,null=True) content=models.CharField(max_length=1000,blank=False) random_order=models.BooleanField(blank=False,default=False) objects=InheritanceManager() class Meta: verbose_name="Вопрос" verbose_name_plural="Вопросы" def __str__(self): return self.content def get_score(self,guess):#сюда надо положить все выбранные варианты пользоватля all_answers=Answer.objects.filter(question=self) rights=0 for q_answer in all_answers: if q_answer.correct is True: rights+=1 corrects=0 incorrects=0 for guess_id in guess: answer = Answer.objects.get(id=guess_id) if answer.correct is True: corrects+=1 else: incorrects+=1 if (rights==corrects)and(incorrects==0): return 2 elif (rights%corrects==1)and(incorrects==1): return 1 elif (rights%corrects>1)and(incorrects>1): return 0 def random_answers(self,queryset): if self.random_order is True: return queryset.order_by('?') else: return queryset.order_by() def get_answers(self): return self.random_answers(Answer.objects.filter(question=self)) def get_answers_list(self): return [(answer.id,answer.answer)for answer in self.random_answers(Answer.objects.filter(question=self))] def answer_choice_to_string(self, guess): return Answer.objects.get(id=guess).answer class Answer(models.Model): question=models.ForeignKey(Question, verbose_name="Вопрос") answer=models.CharField(max_length=1000,blank=False) correct=models.BooleanField(blank=False,default=False) def __str__(self): return self.answer class Meta: verbose_name="Ответ" verbose_name_plural="Ответы" and this is views.py from django.shortcuts import … -
Django 1.10 - get site base url
How do you get base url of a site? like - http://stackoverflow.com/ I would love to set it to settings.py Thanks -
How do I change the object name of my Django model by the data of a field of my database?
I would like to know how I can change Campaign object and Destino object by data that correspond to my database. I was using code that returns the data to my database but in the part where it shows the actions it does not do that. Is there any other way to do it? Thanks for reading my question and leave your answers. Here is my admin.py file: from django.contrib import admin from .models import Campania, Destino class CampaniaAdmin(admin.ModelAdmin): list_display = ('id_campania','nombre_campania','fecha_creacion','fecha_inicio','usuario','correos_diarios','email','sms', 'completado') search_fields = ['nombre_campania'] class DestinoAdmin(admin.ModelAdmin): list_display = ('id_destino','unidad_id_unidad','campania_id_campania','enviado','fecha_hora') search_fields = ['id_destino'] And here is my models.py file: from __future__ import unicode_literals from django.db import models class Campania(models.Model): id_campania = models.AutoField(primary_key=True, verbose_name='ID') template = models.ForeignKey('Template', db_column='template', blank=True, null=True, verbose_name='Template') nombre_campania = models.CharField(max_length=500, blank=True, null=True, verbose_name='Nombre de la campaña') fecha_creacion = models.DateField(blank=True, null=True, verbose_name='Fecha de creación') fecha_inicio = models.DateField(blank=True, null=True, verbose_name='Fecha de inicio') usuario = models.CharField(max_length=250, blank=True, null=True, verbose_name='Creador de la campaña') correos_diarios = models.IntegerField(blank=True, null=True, verbose_name='Correos por día') email = models.BooleanField(default=True, verbose_name='Enviar correo') sms = models.BooleanField(default=True, verbose_name='Enviar mensaje (sms)') completado = models.NullBooleanField(default=False, blank=True, null=True, verbose_name='Completado') class Meta: managed = False db_table = 'campania' verbose_name_plural = "Campañas" def __str__(self): return '{}'.format(self.nombre_campania) class Destino(models.Model): id_destino = models.AutoField(primary_key=True, verbose_name='ID') unidad_id_unidad = … -
database tranactions in django
I am new to Django and have some model definitions as follows: class ProjectModel(models.Model): name = models.CharField(max_length=100) description = models.TextField() class Meta: db_table = "projects" class StudyModel(models.Model): project = models.ForeignKey(ProjectModel) name = models.CharField(max_length=100) description = models.TextField() class Meta: db_table = "studies" I have an associated view which allows the user to create a project and a study at the same time. I do it as follows: pid = ProjectModel.objects.filter(name__iexact=project_name).first() if pid is None: try: #with transaction.atomic(): pobj = ProjectModel.objects.create(name="A", description="") sobj = StudyModel.objects.create(name="B", description="", project_id=pobj.pk) except: #pobj.delete() #sobj.delete() return Response(status=status.HTTP_417_EXPECTATION_FAILED) I have been thinking about how to do this so that if any of the operations fail, the database stays untouched i.e. if the study is not created for some reason, the project is not created either. One way i thought it is doable is to mark the method savepoints before calling the objects.create and then rolling back in the exception handler. However, I am not sure if that is the right way to do this. -
Django Mysql Database returned an invalid datetime value
I have a Django app. I am using MySql server running in docker container as a database. After just moved to a custom User model. Now i am getting those errors: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/ Django Version: 1.10.3 Python Version: 3.5.2 Installed Applications: ['grappelli', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.sites', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'oauth2_provider', 'social.apps.django_app.default', 'rest_framework_social_oauth2', 'rest_framework_swagger', 'accounts', 'dashboard', 'items', 'storages', 'userprofile', 'common', 'registration', 'debug_toolbar', 'django_extensions'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/home/kuba/code/VeeU/Server/dashboard/views.py" in index 66. Bookmark.objects.datetimes('date_bookmarked', 'day')] File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/db/models/query.py" in __iter__ 256. self._fetch_all() File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/db/models/query.py" in _fetch_all 1087. self._result_cache = list(self.iterator()) File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/db/models/query.py" in __iter__ 155. for row in compiler.results_iter(): File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in results_iter 795. row = self.apply_converters(row, converters) File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in apply_converters 779. value = converter(value, expression, self.connection, self.query.context) File "/home/kuba/.virtualenvs/VeeU/lib/python3.5/site-packages/django/db/models/functions/datetime.py" in convert_value 181. "Database returned an invalid datetime value. " Exception Type: ValueError at /dashboard/ Exception Value: Database returned an invalid … -
Bypassing Heroku 30 second worker timeout using Django
I'm struggling to rework the logic of my Django app to comply to the Heroku 30 seconds timeout on workers. The logic in question has two views: "view A" and its successor "view B". In View A, a user will upload an Excel file and a zip file full of pictures. Once they click on a "next" button, the code parses the Excel file row by row, looking for spelling mistakes. Once it has done this, it will extract the ZIP and convert all the images to base64. The corrected spelling mistakes and base64 photos are passed to view B, which renders everything in a HTML table. Unfortunately, for 100 rows or more all this computation takes longer than 30 seconds, causing Heroku to block my worker. The general solution I've seen is to bundle the job into a Redis/Celery task. While I have this set up for other jobs, in this case view B relies on what view A gives it, so job has to be synchronous. I read also an answer that suggests: "As a hack, you can thus repeatedly send "heartbeat" messages over the connection in order to keep it alive." Is this at all possible in … -
Import Error: No module named django - for specific project
DISCLAIMER: I have tried all fixes that I could find online. I have installed Django(1.8.2) in my Ubuntu 16.04. When I cloned a working project into it and run the server, I got the following error. Traceback (most recent call last): File "manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/django/core/management/__init__.py", line 312, in execute django.setup() File "/usr/lib/python2.7/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python2.7/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/lib/python2.7/django/apps/config.py", line 119, in create import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named django Observation(s): I'm able to start a new project and run the server of the same. What have I tried? Installing django using pip install django==1.8.2. Since the error was reported with reference to /usr/lib/python2.7/, I tried: sudo pip install --install-option="--install-purelib=/usr/lib/python2.7/site-packages/" --ignore-installed django==1.8.2 Further, when I got confused with paths /usr/local/lib/python2.7/dist-packages, /usr/lib/python2.7/dist-packages/ and ~/.local/lib/python2.7/dist-packages. I installed django(1.8.2) to each of these paths one by one, updating PYTHONPATH in parallel. I did not get any errors while installing. Can somebody help me out. Kindly explain the reason for the error as well. -
Celery worker does not consume messages
I'm using Celery 4.0.0 with RabbitMQ as messages broker within a django 1.9 project, using django-celery-results for results backend. I'm new to Celery and RabbitMQ. The python version is 2.7.5. After following the instructions in the Celery docs for configuring and using celery with django, and before adding any real tasks, I tried a simple task calling using django shell (manage.py shell), sending the debug_task as defined in the celery docs. Task is sent OK, and looking at the rabbitmq queue, I can see a new message has arrived to the correct queue on the correct virtual host. I run the worker and it looks like it starts OK, then it arrives to the event loop and does nothing. No error is presented, not in the worker output or in the rabbitmq logs. I'm probably missing something here, but I don't know what it can be. Don't know if this is relevant, but when I use 'celery purge' to clear the messages queue, it finds the message and purges it. Celery configuration settings as added to django settings.py: CELERY_BROKER_URL = 'amqp://user1:passwd1@rabbithost:5672/exp' CELERY_TIMEZONE = TIME_ZONE # Using django's TZ CELERY_TASK_TRACK_STARTED = True CELERY_RESULT_BACKEND = 'django-db' Task invocation in django shell: >>> … -
Python/ Django form tracking changes to some fields, but not to others
I have a form in my Django project which is defined as follows: class DepositInfoForm(ValidatedForm): amount_exc_vat = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'class': 'currency',}),label="Deposit exc VAT") amount_inc_vat = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'class': 'currency', 'readonly':'readonly',}),label="Inc VAT") date_received = mDateField(required=False, label="Date deposit received", widget=forms.DateInput(format='%d/%m/%Y', attrs=({'class':'datepicker'}))) class Meta: model = Deposit fields = ('amount_exc_vat', 'amount_inc_vat', 'date_received')#,'received') def __init__(self, *args, **kwargs): print "__init__ method being called in DepositInfoForm" instance = kwargs.get('instance', {}) project = instance.project try: amount_exc_vat = int(round(instance.amount_exc_vat)) except TypeError: amount_exc_vat = None print "amount_exc_vat has been set: ", amount_exc_vat try: amount_inc_vat = int(round(project.deposit.amount_inc_vat)) except TypeError: amount_inc_vat = None print "amount_inc_vat has been set: ", amount_inc_vat try: date_received = instance.date_received except TypeError: date_received = None print "date_received has been set: ", date_received initial = kwargs.get('initial', {}) initial={ 'received': project.deposit_received, 'amount_exc_vat': amount_exc_vat, 'amount_inc_vat': amount_inc_vat, 'date_received': date_received, } kwargs['initial'] = initial super(DepositInfoForm, self).__init__(*args, **kwargs) self.fields['date_received'].widget.attrs.update({'data-original-value': self.initial['date_received'] or ''}) def save(self, commit=True): print "Save method being called in DepositInfoForm" deposit = self.instance data = self.cleaned_data print "save method being called in DepositInfoForm (projects/forms.py line 1142)" if 'date_received' in self.changed_data: if not data['date_received'] == '': deposit.project.deposit_received = True; self.deposit_r = True deposit.project.upgrade_detailed_status(Project.ds75) project.date_deposit_received = deposit.date_received else: deposit.project.deposit_received = False; deposit.project.save() if ('amount_exc_vat' in self.changed_data or 'date_received' in self.changed_data in self.changed_data) and data['amount_exc_vat'] and … -
How to write unit test for admin save function
I have customized save_model admin i.e. class MyModelAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): # some more question code here obj.save() Now, I would like to test MyModelAdmin save_model function. I tried posting like: class MyModelAdminSaveTestCase(TestCase): def setUp(self): # setup code here def test_save_model(self): '''Test add employee ''' my_obj = { 'name': 'Tester', 'address': '12 test Test', 'city': 'New York', 'state': 'NY', } self.client.login(username=self.user, password=self.pwd) response = self.client.post(reverse('admin:mymodel_mymodel_add'), my_obj, follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(MyModel.objects.count(), 1) However, test fails: self.assertEqual(MyModel.objects.count(), 1) AssertionError: 0 != 1