Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mocking models used in a Django view with arguments
For the life of me I cannot figure this out and I'm having trouble finding information on it. I have a Django view which accepts an argument which is a primary key (e.g: URL/problem/12) and loads a page with information from the argument's model. I want to mock models used by my view for testing but I cannot figure it out, this is what I've tried: @patch('apps.problem.models.Problem',) def test_search_response(self, problem, chgbk, dispute): problem(problem_id=854, vendor_num=100, chgbk=122) request = self.factory.get(reverse('dispute_landing:search')) request.user = self.user request.usertype = self.usertype response = search(request, problem_num=12) self.assertTemplateUsed('individual_chargeback_view.html') However - I can never get the test to actually find the problem number, it's as if the model does not exist. -
Unable to add ajax post data to div
I am creating an ajax function that sends data to server and upon success receives html data and this HTML data will be added to a particular div element. However, i am unable the the data onto the div. Below is my HTML and jQuery Code. Further, i am using Django Framework. {% block content %} <div class="row"> <div class="col-md-8 col-lg-8 col-sm-10 col-xs-10 offset-lg-2 offset-md-2 offset-xs-1 offset-sm-1"> <div class="card"> <div class="card-header text-center"> No of Floors </div> <div class="card-header"> Project Name: {{ project_details.name }} <br> Location: {{ project_details.location }} <br> PIN: {{ project_details.pin }} <br> User: {{ project_details.user }} </div><br> {% for project in project_status %} <div class="col-md-12 text-center floor-container"> <h6>Floor No: {{ project.floor_no }}</h6> <input type="hidden" id="project_detail" value="{{ project_details.id }}"> <input type="hidden" id="floor_no" value="{{ project.floor_no }}"> <input type="hidden" id="floor_detail" value="{{ project.id }}"> <div id="progress"></div> <div class="card-footer text-muted text-right"> <a href="{% url 'single_project' id=project.project_detail.id floor_no=project.floor_no %}" class="btn btn-primary">View</a> </div> <br> </div> {% endfor %} </div> </div> </div> {% endblock content %} {% block script %} <script type="text/javascript"> $(document).ready(function(){ $('.col-md-12 .text-center .floor-container').each(function(){ $.ajax({ url: '{% url "progess_bar" %}', method: 'POST', data: { 'csrfmiddlewaretoken': '{{ csrf_token }}', 'project_detail_id': $(this).children('#project_detail').val(), 'floor_no': $(this).children('#floor_no').val(), }, success: function(data){ $(this).children('#progess').html(data) } }) }); }); </script> {% endblock script … -
How to get the request object in Django?
I want to access the request.user and request.session deep in my Django project. As I didnt want to pass the request object (from the view) in tons of methods on the way, I created a thread local middleware to accomplish this. But later I came to know that this is not a fail proof/safe method (Why is using thread locals in Django bad? and https://www.pythonanywhere.com/forums/topic/710/). It is mentioned there that one thread can process multiple API requests. (How is this even possible?-not my main issue right now) Anyways, I have to accomplish this in a new way. Help appreciated. Thank you in advance! -
Django + Active Directory Using Current Data
I have a Django project with MS SQL Server as the backend. I also have Active Directory information (i.e. username, first name, last name and email) in a table that is updated daily and not currently related to the Django project. Is there a way to just write that information to the Django auth_user table and use that to provide Active Directory "integration"? I understand I could use a third-party package to actually integrate Active Directory, but I'm wondering if it's possible to take advantage of the existing data stream. The part I don't know is how Active Directory passwords would work if I was just writing users (without passwords) to the auth_user table. Update: The third-party package I would use says to map these fields: LDAP_AUTH_USER_FIELDS = { "username": "uid", "first_name": "givenName", "last_name": "sn", "email": "mail", } I currently have all those fields in my unrelated table. However, the package also says "When a user attempts to authenticate, a connection is made to the LDAP server, and the application attempts to bind using the provided username and password.". My intuition tells me that writing from the unrelated table would mimic syncing Active Directory users to the auth_user table, but … -
Django 1.10 upload file. form is not valid
I try upload file from Form in Django. I use Django 1.10. my form <form id='form_' enctype="multipart/form-data"> {% csrf_token %} <input id="fileupload" data-url="{% url 'analyzer:upload_files' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}' type="file" name="file" multiple> <p>Drag your file(s) here or click in this area.</p> </form> my views def upload_files(request): print(request.FILES, request.user.username) if request.POST: print('ok') form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): print('YEEEES') return JsonResponse({'data':'ok', 'is_valid': True}) else: return JsonResponse({'data':'Bad', 'is_valid': False}) my forms.py from django import forms from .models import File class UploadFileForm(forms.ModelForm): class Meta: model = File fields = ('file_upload','user',) my model from django.db import models def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return ('user_%s/%s' %(instance.user.id, filename)) class File(models.Model): id = models.IntegerField(primary_key=True) id_user = models.IntegerField() user = models.TextField() uploaded_at = models.DateTimeField(auto_now_add=True) file_upload = models.FileField(upload_to='files/') file_size = models.IntegerField() file_name = models.TextField() I do not know what I'm doing wrong. My form is not valid. Please, help me! P.S. Still, I'm trying to save the file for each user separately, but examples from the Internet do not help -
django admin readonly_fields = 'some_filed' But create or add can not edit the same, what is a good way
django admin: readonly_fields = 'some_filed' But create or add can not edit the same, what is a good way -
how to set default group for new user in django?
how can I set default group for new users that I create? I didn't create custom model of user and My django version is 1.11. -
Passing Django Queryset in Views to Template
I have a Django Views which has some logic for passing the correct category to the template. class ProductListView(ListView): model = models.Product template_name = "catalogue/catalogue.html" def get_queryset(self): category = self.kwargs.get("category") if category: queryset = Product.objects.filter(category__iexact=category) else: queryset = Product.objects.all() return queryset I can't work out how to pass this to the template, my template code is as below: {% for product in products %} <tr> <td><h5>{{ product.name }}</h5> <p>Cooked with chicken and mutton cumin spices</p></td> <td><p><strong>£ {{ product.price }}</strong></p></td> <td class="options"><a href="#0"><i class="icon_plus_alt2"></i></a></td> </tr> {% endfor %} I am pretty sure my template syntax is wrong, but how do I pass the particular category to the template? So if I have a category called 'Mains' how do I pass all the products for mains to the template. -
Django inheriting testCases
How can I use subclassing for Django Test case for setUpTestDate(cls) Following code without setUpTestData() works just fine when subclassing, however, if I call super().setUpTestData(), I am getting setUpTestData() missing 1 required positional argument: 'cls' Can we inherit setUpTestData()? because I need to create carrier and dispatcher before setUp is called class DashboardTestCase(TestCase): password = '12345' def authenticate(self): self.client.login(username=self.dispatcher.email, password=self.password) def setUp(self): self.authenticate() def setUpTestData(cls): password = '12345' cls.carrier = Carrier.objects.create( .... ) cls.dispatcher = Dispatcher.objects.create( ... ) cls.dispatcher.set_password(password) cls.dispatcher.save() -
non_form_errors doesn't show
I am working with inlineformset_factory and created a forms.BaseInlineFormSet to override the clean function to make some validations. the validation works and the form isn't accepted but the ValidationError message doesn't appear when the page is reloaded. here is my form class: class BaseDetailFormSet(forms.BaseInlineFormSet): def clean(self): super(BaseDetailFormSet, self).clean() if any(self.errors): return self.errors for form in self.forms: product = form.cleaned_data['product'] if form.cleaned_data['quantity_sold'] > product.quantity_in_stock: raise forms.ValidationError(_('not enough products')) DetailFormset = inlineformset_factory(Invoices, InvoiceDetail, fields=('product', 'quantity_sold'), widgets= {'product': forms.Select( attrs={ 'class': 'search', 'data-live-search': 'true' })}, formset=BaseDetailFormSet, extra=1) and my html code: <form class="form-inline" method="post" action=""> {% csrf_token%} {% include '_layouts/form_snippet.html' %} <table class="table"> {{inlines.management_form}} {%for form in inlines.forms%} {% if forloop.first%} <thead> <tr> {%for field in form.visible_fields%} <th>{{field.label|capfirst}}</th> {%endfor%} {%endif%} </tr> </thead> <tr class="formset_row"> {{ form.non_form_errors }} {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> <button type="submit" value="Add" class="btn btn-inverse">{% trans 'Submit Invoice' %}</button> </form> any ideas how to show the validation error message or why it isn't shown. -
How to design crawler process bar in django?
I want to design crawler process bar in django. When I click start button, the process bar will show the crawler is working. But I don't know how to design because I don't know when the crawler ends. -
How to create a custom testsuite and run testsuite for a django app using mongodatabase
I have a django app structure /myapp /myapp/obj1/.. /myapp/obj1/views.py /myapp/obj1/forms.py /myapp/obj2/.. /myapp/obj2/views.py /myapp/obj2/forms.py /myapp/tests/.. /myapp/tests/__init__.py /myapp/tests/obj1.py /myapp/tests/obj2.py I can run each test file under tests directory of django app using python manage.py test myapp.tests.obj1.py Can u help me to create a testsuite and run testsuite of all testcases as report file in django? -
With Django, why do I get 404 errors on static resources during login?
I know very little about Django. I am taking over a project that was developed by someone else. I was asked to implement a new design. Now suddenly I get an error when I try to log in. I get a broken page, which I'm not supposed to see, as it is should simply redirect me to my the user's profile page. Instead, this happens: [31/Jan/2018 13:28:47] "POST /accounts/login/ HTTP/1.1" 200 2829 [31/Jan/2018 13:28:48] "GET /static/core/bundles/main.css HTTP/1.1" 404 1787 [31/Jan/2018 13:28:48] "GET /static/core/img/sugar-notagline-23may.jpg HTTP/1.1" 404 1826 [31/Jan/2018 13:28:48] "GET /static/core/img/tools.png HTTP/1.1" 404 1778 [31/Jan/2018 13:28:48] "GET /static/core/img/library.png HTTP/1.1" 404 1784 [31/Jan/2018 13:28:48] "GET /static/core/img/filter1.png HTTP/1.1" 404 1784 [31/Jan/2018 13:28:48] "GET /static/core/img/settings.png HTTP/1.1" 404 1787 There is the main.css file here: ./sugarlab/core/static/core/bundles/css/main.css I don't get why that is a 404, since on other pages it seems to be included fine. The images don't exist, but that shouldn't matter, because this page is not supposed to be shown to the user. Assuming I've broken some redirect mechanism, what should I be looking for? How would this redirect normally be handled? -
AngularJS $http request fails with custom headers
I am trying to add a custom header to my common request like so: myApp.config(['$httpProvider', function ($httpProvider) { // $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; $httpProvider.defaults.headers.common['test_key'] = 'kkkkk'; }]); Without the above header request works fine. but when added gives the following error: { "data": null, "status": -1, "config": { "method": "GET", "transformRequest": [ null ], "transformResponse": [ null ], "jsonpCallbackParam": "callback", "url": "http://localhost:8900/tt/", "data": {}, "headers": { "Accept": "application/json, text/plain, */*", "test_key": "kkkkk" } }, "statusText": "", "xhrStatus": "error" } On server side I have Django with Django Rest Framework. Server side code is very simple: from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET']) def test(request): return Response({'ddddddd'}) urlpatterns = [ url(r'^tt/$', test) ] What am I doing wrong? How should I add these headers? -
Celery does not start multiple workers
I am trying to set up a server to run multiple workers on Ubuntu using celery. Set up the daemon using the generic scripts and using rabbit-mq as the broker. celery==3.1.23 django-celery==3.1.17 django-celery-beat==1.0.1 /etc/default/celeryd - (internally using celery multi start RRR SSS TTT STST OTS ...) CELERYD_NODES="RRR SSS TTT STST OTS" CELERYD_OPTS="-c 4 -Q:RRR r,e,h -Q:SSS s,p -Q:TTT d -Q:STST sd -Ofair --detach --time-limit=1500 CELERYD="/x/home/ks/wb/manage.py celeryd" $ service celerd start $ ps -ef | grep celery /etc/init.d/celeryd start root 25636 25631 0 01:37 pts/4 00:00:00 /usr/bin/python /usr/local/bin/celery multi start RRR SSS TTT STST OTS -c 10 --uid=celery --gid=celery --workdir=/x/home/ks/wb --pidfile=/var/run/celery/%n.pid --logfile=/var/log/celery/%n.log --loglevel=DEBUG --cmd=/x/home/ks/wb/manage.py celeryd -Q:RRR r,e,h -Q:SSS s,p -Q:TTT d -Q:STST -Ofair --detach --time-limit=1500 celery 27440 25636 0 01:53 pts/4 00:00:01 [celeryd: STD@dt:MainProcess] -active- (--time-limit=1500 -c 4 --executable=/usr/bin/python --gid=celery --detach --logfile=/var/log/celer/STD.log -n STD@dt-ss-app-3040 --loglevel=DEBUG --uid=celery --pidfile=/var/run/celery/STD.pid --workdir=/x/home/ks/wb -Ofair -Q standard) celery 27452 27440 1 01:53 pts/4 00:00:05 [celeryd: STD@dt:Worker-1] celery 27453 27440 0 01:53 pts/4 00:00:01 [celeryd: STD@dt:Worker-2] celery 27455 27440 0 01:53 pts/4 00:00:01 [celeryd: STD@dt:Worker-3] Only one worker (STD) gets started. The other workers are not starting. when I tried to stop the service service celeryd stop Worker STD stops and another worker RRR starts. which signifies that … -
Django tag based on model and view not showing on webpage
I am trying to show another table with postgresql data on my django webpage. The page does show the normal HTML content, but it is not showing the postgresql data. Interestingly, the Django shell does indicate the data is available: In [1]: Companystats.objects.all() Out[1]: , etc I tried: restarting the server (python3 manage.py runserver) python3 manage.py makemigrations python3 manage.py migrate Simplified code: HTML webpage {% for compstat in compstats %} {{ compstat.symbol }} {% endfor %} models.py class Companystats(models.Model): company_name = models.TextField(blank=True, null=True) symbol = models.TextField(primary_key=True) class Meta: managed = False db_table = 'companystats' views.py from django.shortcuts import render from .models import Companystats def companystats_list(request): compstats = Companystats.objects.all() return render(request, 'blog/post_list.html', {'compstats': compstats}) any ideas on what i could try to fix it would be very much appreciated. -
Passing a costant in a template using include filter with variables
In a custom widget I have: <img src="{% static 'img/placeholders/whitepaper-color.png' %}" height="80" width="90"/> I want the src to contain a variable that I sent using a template with variables, something like: {% include "name_snippet.html" with variable='whitepaper-color.png' %} It is possible tto take this variable from constants ? I know that I can attach the constants to the view, but I have a more complex situation using multiple formsets(some of them derived from same model) etc. So I want to see if there is a more cleaner way. -
ModuleNotFoundError: No module named 'googlemaps'
I am a newcomer to Django python programming. Now I am working on the server side. I want to use google maps API, my view.py is like this: from django.shortcuts import render from django.shortcuts import HttpResponse from googlemaps import * # Create your views gmaps = googlemaps.Client(key='A') def index(request): if request.method=="GET": geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA') return geocode_result Also, I have already installed 'googlemaps' using pip. And when I import it in IDE, nothing goes wrong. But when I want to start the server to test the code, the server won't run and tells me ModuleNotFoundError: No module named 'googlemaps', I am confused that I have already downloaded it and added it in settings.py, importing in IDE also seems fine. But where I did wrong makes it fail to start the server? -
Django REST: 'Request' object has no attribute 'field_name'
I'm trying to create a post request to add a job application to the list of applicants. This is done by POST /task-worker/<task_id> However, I get the error: 'Request' object has no attribute 'task' Models.py class Task_worker(models.Model): worker = models.ForeignKey(Worker) task = models.ForeignKey(Task) class Meta: unique_together = ('worker', 'task') class Task(models.Model): ... class Worker(models.Model): ... views.py class TaskWorker(generics.ListCreateAPIView): serializer_class = TaskWorkerSerializer def get_queryset(self): task_id = self.kwargs.get('task_id', '') queryset = Task_worker.objects.filter(task__user=self.request.user, task_id=task_id).distinct() return queryset def perform_create(self, serializer): worker = Worker.objects.get(user=self.request.user) task = Task.objects.get(pk=self.kwargs.get('task_id', '')) serializer.save(task=task, worker=worker) #ALSO TRIED #serializer.save(task_id=self.kwargs.get('task_id', ''), worker=worker) Even if I don't have task explicitly in perform_create(), I still get the same error, saying request has no task attribute. urls.py url(r'^task-worker/(?P<task_id>[0-9]+)/$', views.TaskWorker.as_view()), -
ImportError: No module named 'app.settings.ci'; 'app.settings' is not a package
I got an error,ImportError: No module named 'app.settings.ci'; 'app.settings' is not a package.I wanna install CircleCI 2.0 into Django application.Traceback says Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/xxx/anaconda/envs/rf/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/xxx/anaconda/envs/rf/lib/python3.5/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/Users/xxx/anaconda/envs/rf/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/xxx/anaconda/envs/rf/lib/python3.5/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Users/xxx/anaconda/envs/rf/lib/python3.5/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/xxx/anaconda/envs/rf/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ImportError: No module named 'analytics_api.settings.ci'; 'analytics_api.settings' is not a package I run command,python manage.py makemigrations --settings app.settings.ci,so the error happens.I think this command is necessary to install CircleCI 2.0,but is it wrong?How can I fix this?What is wrong in my code? -
Django: Form widget not accepting date format provided by bootstrapdatetimepicker
I have the following problem: I have a django form that uses the 'bootstrapdatetimepicker' widget for a datetimefield. However, when I try to post the form it throws a 'format is invalid' error. I am using a local (Dutch) timeformat, but I have included this new format in both the forms.py code (see below) class Meta: model = Quotation fields = [ 'full_name', 'organisation', 'address', 'date', 'type', 'description', 'budget', ] widgets = {'date': DateTimeInput( attrs={'id': 'datetimepicker1'}, format='%d-%m-%Y %H:%M:S')} and in the template as well, <div class="col-md-12 speaker-form" id="offerte"> {% csrf_token %} {% crispy form %} </div> <script> $(function () { $('#datetimepicker1').datetimepicker({ format:'DD-MM-YYYY HH:mm:ss', defaultDate: new Date(), icons: { up: "fa fa-chevron-circle-up", down: "fa fa-chevron-circle-down", next: 'fa fa-chevron-circle-right', previous: 'fa fa-chevron-circle-left', } }); }); </script> Does anyone know what I am doing wrong? Why are my 'format' overrides in both the Python and Javascript code not working as they should? -
Django-orm Queryset for Find object by count a particular field
Lets say i have two model class Testmodel1(): amount = models.IntegerField(null=True) contact = models.ForeignKey(Testmodel2) entry_time = models.DateTimeField() stage = choicesfiled class Testmodel2(): name = models.CharField() mobile_no = models.ForeignKey() I want to find out the object of Testmodel1 for contact > 3 which is created in last 24 hours last = arrow.utcnow().shift(hours=-24).date(). I am applying a query n1=Testmodel1.objects.filter(entry_time__gte=last, stage=1).annotate(t_count=Count('contact')).filter(t_count__gt=3) But it's seems, it' not working. Because I am getting a empty queryset. Any help would be appreciated. -
Django-hvad _clone() got an unexpected keyword argument 'shared_model'
I'm trying to implement django-hvad on a django app but I'm getting this error _clone() got an unexpected keyword argument 'shared_model' when I'm trying to launch python manage.py runserver. Did I made any mistakes to translate my models? Thanks for your help! models.py class Opponent(TranslatableModel): name = models.CharField(max_length=255, unique=True, null=True) companyType = models.ForeignKey(CompanyType, on_delete=models.SET_NULL, blank=True, null=True, related_name='opponents') pricing = models.ManyToManyField(Pricing, blank=True) translations = TranslatedFields( description = models.TextField(null=True, blank=True) ) def __str__(self): return "{}" .format(self.name) def save(self, *args, **kwargs): super(Opponent, self).save(*args, **kwargs) # Call the "real" save() method. serializers.py class OpponentSerializer(TranslatableModelSerializer): class Meta: model = Opponent fields = '__all__' views.py class OpponentViewSet(viewsets.ModelViewSet): queryset = Opponent.objects.language().all() serializer_class = OpponentSerializer def get_queryset(self): user_language = self.request.GET.get('language') return Opponent.objects.language(user_language).all() -
Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualst udio.com/visual-cpp-build-tools
I have tried all methods mentioned on the internet but there is no use. I am trying to install misaka by writing pip install misaka it keeps complaining by showing the same message. I have downloaded and installed MS build tool 2015 and 2017, Restarted my laptop. Whatever I did, couldn't figure out why it complains. Python version 3.6.4 Windows 10 -
Remove blank lines from Django template output of render_to_string
I am trying to add contents to models.py dynamically using templates. For this i have the following line in views.py model_content = render_to_string('myapp/models.txt',{'table':table_name, 'fields':fields}) models.txt in templates class {{ table }}(models.Model): {% for field in fields %} {{ field.field_name }} = models.{{ field.field_type.name }} {% endfor %} But when i wrote model_content string to a file say models.py i am getting the below class Mytable(models.Model): order = models.CharField cust_name = models.CharField I am getting an extra line after every line. How to avoid this. I will provide additional information if required.