Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Error 404 detail“: ”Not found."
When i go to localhost:8000/api/create i get this: views.py: from rest_framework import viewsets from rest_framework.generics import ( ListAPIView, RetrieveAPIView, CreateAPIView, # DestroyAPIView, # UpdateAPIView ) from articles.models import Article from .serializers import ArticleSerializer class ArticleListView(ListAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer class ArticleDetailView(RetrieveAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer class ArticleCreateView(CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer urls.py: from django.urls import path, include from .views import ArticleListView, ArticleDetailView, ArticleCreateView urlpatterns = [ path('', ArticleListView.as_view()), path('create/', ArticleCreateView.as_view()), path('<pk>', ArticleDetailView.as_view()), ] models.py: from django.db import models # Article Model class Article(models.Model): title = models.CharField(max_length=120) content = models.TextField() def __str__(self): return self.title I'm on windows 10, using python 3.7.1 i don't know what else to write but i'm writing these words so this thing will let me post, ignore this. -
Upgrading django from 1.1 to 2.0 - middleware failure
I'm upgrading from django 1.1 to 2.0. I'm getting the following error: System check identified 3 issues (0 silenced). November 05, 2018 - 17:21:55 Django version 2.1.3, using settings 'barfoo.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x11ceea488> Traceback (most recent call last): File "/Users/foobar/.pyenv/versions/barfoo/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/foobar/.pyenv/versions/barfoo/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "/Users/foobar/.pyenv/versions/barfoo/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "/Users/foobar/.pyenv/versions/barfoo/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "/Users/foobar/.pyenv/versions/barfoo/lib/python3.5/site-packages/django/core/servers/basehttp.py", line 44, in get_internal_wsgi_application return import_string(app_path) File "/Users/foobar/.pyenv/versions/barfoo/lib/python3.5/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/Users/foobar/.pyenv/versions/3.5.2/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 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/Users/foobar/work/nhuk/barfoo/barfoo/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/Users/foobar/.pyenv/versions/barfoo/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/Users/foobar/.pyenv/versions/barfoo/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 136, in __init__ self.load_middleware() File "/Users/foobar/.pyenv/versions/barfoo/lib/python3.5/site-packages/django/core/handlers/base.py", line 36, in load_middleware mw_instance = middleware(handler) I have been through the docs, and … -
Failing hstore tests Django
I am having a problem when I get the value from a hstore field. The situation is something like this: model: class Model(models.Model): hstoreField = HStoreField() test cases: def test_case_1(self): new_model = Model.objects.create( hstoreField = { 'key1': 'value1', 'key2': 'value2' } ) self.assertEqual(new_model.subscription['key1'], 'value1') self.assertEqual(new_model.subscription['key2'], 'value2') def test_case_2(self): Model.objects.create( hstoreField = { 'key1': 'value1', 'key2': 'value2' } ) new_model = Model.objects.get( id = 1 ) // assume it works self.assertEqual(new_model.hstoreField['key1'], 'value1') self.assertEqual(new_model.hstoreField['key2'], 'value2') When I run those test cases, the first one passes, but the second one fails and the error thrown is: TypeError: string indices must be integers. Checking the value of hstoreField is a string and it should be a dict. The error only happens in tests, in real code both cases work. Can you help me guys? -
How to make public chat using Django Channels WITHOUT AuthMiddlewareStack?
I cant understand how to do not use AuthMiddlewareStack in routing. Now my code is: application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"leadusers/(?P<pk>\d+)/(?P<chatid>[\w-]+)/$", LeadUserConsumer, name='leaduser_consumer'), ] ) ), ), }) I tried to remove just this class AllowedHostsOriginValidator - doesnt work. May be somebody knows? Help, please. Blockquote -
Deleting objects with unique-together constraints on SQL Server
Consider the following Django ORM example: class A(models.Model): pass class B(models.Model): a = models.ForeignKey('A', on_delete=models.CASCADE, null=True) b_key = models.SomeOtherField(doesnt_really_matter=True) class Meta: unique_together = (('a', 'b_key'),) Now let's say I delete an instance of A that's linked to an instance of B. Normally, this is no big deal: Django can delete the A object, setting B.a = NULL, then delete B after the fact. This is usually fine because most databases don't consider NULL values in unique constraints, so even if you have b1 = B(a=a1, b_key='non-unique') and b2 = B(a=a2, b_key='non-unique'), and you delete both a1 and a2, that's not a problem because (NULL, 'non-unique') != (NULL, 'non-unique') because NULL != NULL. However, that's not the case with SQL Server. SQL Server brilliantly defines NULL == NULL, which breaks this logic. The workaround, if you're writing raw SQL, is to use WHERE key IS NOT NULL when defining the unique constraint, but this is generated for me by Django. While I can manually create the RunSQL migrations that I'd need to drop all the original unique constraints and add the new filtered ones, it's definitely a shortcoming of the ORM or driver (I'm using pyodbc + django-pyodbc-azure). Is there some … -
Download link in template, when you have a model object with a filefield
Is it possible to make a download link in a html template, when you have a model object available, like this? models.py class Barcard(models.Model): name = models.CharField(max_length=30) drinks = models.ManyToManyField(Drink) barcardFile = models.FileField(blank=True, upload_to='barcard') mixingFile = models.FileField(blank=True, upload_to='mixing') views.py def download(request, barcard_id): if request.method == 'GET': barcard = get_object_or_404(Barcard, pk=barcard_id) return render(request, 'drinks/download.html', {'barcard':barcard}) else: return HttpResponseRedirect('/drinks/') template/drinks/download.html {% extends "drinks/base.html" %} {% block fulltitle %}Drinks{% endblock %} {% block content %} <h1>{{ barcard.name }}</h1> <p> Download barkort her: <a href='{{ MEDIA_URL }}{{ barcard.barcardFile.relative_path }}'>{{barcard.name}} barkort</a> </p> <p> Download blandekort her: <a href='{{ MEDIA_URL }}{{ barcard.mixingFile.relative_path }}'>{{barcard.name}} blandekort</a></p> {% endblock %} Right now I don't get a file, when clicking the link. Have I missed something or will I have to do something completely different? -
Django ManyToMany field gives IntegrityError
I am using Django 2.1.2 I am having 2 Models Items and Quotation. class Item(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Quotation(models.Model): company = models.ForeignKey('Company', on_delete=models.CASCADE) unit_rate = models.CharField(max_length=200) item = models.ManyToManyField(Item) def __str__(self): return self.company.company_name Now when I am adding Item it is working correctly. But when I try to add quotation in Admin Panel, it gives me null value in column "item_id" violates not-null constraint I am new to Django. It would be great if someone can point what I am missing. -
Django: custom http header authentification
I want to create an authentication for my Django 1.11 project. A user will be authenticated if the request contains the header : X_USERNAME. I am working with generic views so I use LoginRequiredMixin to control access. I made this Custom authentication class: class CustomAuthentication: def authenticate(self, request): username = request.META.get('X_USERNAME') logging.warning(username) if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=username) user.is_staff = False user.is_superuser = False if request.META.get('X_GROUPNAME') == 'administrator': user.is_staff = True user.is_superuser = True user.save() return user, None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None I added it in my settings : AUTHENTICATION_BACKENDS = ['path.to.file.CustomAuthentication'] But I can't make it work. I am redirected to /accounts/login/?next= which doesn't exist. Thanks in advance! -
Django migration doesn't generate any SQL or affect any tables
I edited my models, and ran python manage.py makemigrations appname. This created a migration which looks something like this: class Migration(migrations.Migration): dependencies = [ ('appname', 'previous_migration'), ] operations = [ migrations.RemoveField( model_name='foo', name='bar', ), migrations.AddField( model_name='foo', name='baz', field=models.CharField(blank=True, default='', max_length=100), ) ] All good, so far. But when I run python manage.py migrate appname --database MY_DB, nothing happens to the appropriate tables. The migration gets written to django_migrations as if it went through, but the foo table is unaffected. When I run python manage.py sqlmigrate appname mymigration --database MY_DB, I get an essentially empty SQL script: BEGIN; -- -- Remove field bar from foo -- -- -- Add field baz to foo -- COMMIT; This is unfortunately all info I can provide, as I wasn't able to find any further clues as to this behavior. -
Django Serializer nests when overriding to_representation()
I have a serializer ReservationSerializer: Class ReservationSerializer(serializers.ModelSerializer): pax_leader = serializers.SerializerMethodField() class Meta: model = models.Reservation fields = ('id', 'booking', 'agency', 'comment', 'status', 'arrival_date', 'departure_date', 'confirmation', 'confirmation_date', 'euroamerica', 'user', 'timestamp', 'pax_leader', 'is_invoiced') depth = 0 def get_pax_leader(self, instance): try: pax_leader = models.ReservationPerson.objects.get(reservation=instance.id, is_primary=True) except: pax_leader = None if pax_leader: return pax_leader.name else: return None def to_representation(self, instance): representation = super().to_representation(instance) representation['agency'] = AgencySerializer(instance.agency).data return representation I don't know why I get the result nested with several levels of depth. If remove to_representation(), I get the result without nesting, but I need to add agency. I don't know how to manage this behavior. -
Django admin UserChangeForm with UUID field as primary key
I'm working on a Django app that will contain sensitive User data, so I'm taking a number of steps to anonymise User objects and their data. I created custom 'User' object that subclassses the AbstractBaseUser model like so: class User(AbstractBaseUser, PermissionsMixin): (...) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) (...) It has the following linked ModelAdmin object: from django.contrib.auth.forms import UserChangeForm @admin.register(User) class UserAdmin(admin.ModelAdmin): form = UserChangeForm I'm using UUID fields for primary keys to ensure maximum anonymity, yet I would like to be able to reset User passwords in the Django Admin (like you can do with the default User object) However, when I open a User in the admin and press the link to change the password I get the following error message: User with ID "21362aca-6918-47ea-9b29-275350a89c54/password" doesn't exist. Perhaps it was deleted? The admin url is still expecting a url with the an integer as its pk value. So it seems that I have to override the admin url configuration in the ModelAdmin definition, but I was wondering if there was a simpler way to achieve the desired result - as I imagine that replacing the User.pk with an UUID field is a fairly regular occurrence and I image … -
Raising a bad request 400 exception in a ListAPIView
Im trying to raise a 400 exception when the user does not provide a token or when the token is not valid my code is below : this is my exceptions.py file : from rest_framework.exceptions import APIException, PermissionDenied class MissingTokenException(APIException): status_code = 400 default_detail = 'Your request does not contain token' default_code = 'no_token' class InvalidTokenException(APIException): status_code = 400 default_detail = 'Your request contain invalid token' default_code = 'invalid_token' this is my views.py file : class ListProductsOfCategory(generics.ListAPIView): serializer_class = ProductSerializer lookup_url_kwarg = 'category_id' def dispatch(self, *args, **kwargs): token = self.request.META.get("HTTP_TOKEN", "") if not token: # here I wan to raise an error saying that no token provided. raise MissingTokenException if not UserAccess.objects.filter(accessToken=token).exists(): # here I wan to raise an error saying that token provided is not valid. raise InvalidTokenException return super().dispatch(*args, **kwargs) def get_queryset(self): category_id = self.kwargs.get(self.lookup_url_kwarg) return Product.objects.filter(category_id=category_id) Im using postman to test my APIs: please if any one can help Im new to django and python. -
How to disable username change in Djoser?
I haven't found any information in documentation about how to exclude/disable any of the endpoints provided by Djoser. I could just look for one in it's urlpatterns and remove it but I'm wondering if there's any less ugly way to do that. -
Emailing when a instance is created or updated using Django
Intro: I have 2 Django Rest Framework models Patient and Embryo There is only 1 user who is the superuser. All the patients belong to the superuser. A patient can have many ebryo's but each embryo can have only 1 patient. What I want to do: I am trying to send the patient an email when either the patient model or embryo model is created or updated. Below is my code what am I doing wrong Below is my views.py def send_email_confirmation(instance): patient = Patient.objects.get(id=instance) embryo = Embryo.objects.filter(patient=patient) try: '''Sending the Order to the patient''' subject = "Gemonic Prediction Create or Update record" to = ['{}'.format(patient.email)] from_email = "no_reply@genomicprediction.com/" order_information = { 'patient': patient, 'embryo': embryo } message = get_template('email/email.html').render(order_information) msg = EmailMessage(subject, message, to=to, from_email=from_email) msg.content_subtype = 'html' msg.send() except IOError as e: return e class PatientsApiView(viewsets.ModelViewSet): """Handles Creating, reading and updating Patients""" serializer_class = serializers.PatientsSerializer queryset = Patient.objects.all() authentication_classes = (TokenAuthentication,) filter_backends = (filters.SearchFilter,) permission_classes = (IsAuthenticated,) search_fields = ("first_name", "last_name", "phone", "email",) def perform_create(self, serializer): serializer.save(user=self.request.user) instance = serializer.save() try: send_email_confirmation(created=instance) print('An email has been sent to the customer.') except IOError as e: return e def perform_update(self, serializer): instance = serializer.save() try: send_email_confirmation(modified=instance) print('An email has been … -
django: how to model a game where actions could be known some time after they have been executed?
I want to write a Django App to track a real time game (that is, the players are required to do some tasks in real life as days pass). The main problem in design I'm experiencing is that the system could be informed of some action with a delay of some hours, and such actions could interfere with some other actions that were already registered on the website. Let's make an example: it is enough to know that every player has a money balance and if player A gets "killed" by player B, then player B "steals" all the money from player A. Such money can be used to buy some things that are helpful in the game. Suppose the following happends: (3 PM - Initial state) A has 5 money, B has 3 money (4 PM - Action) B "kills" A. This actions is inserted into the website at 6 PM (5 PM - Action) A buys a thing for 4 money. I would like that when we know what happened at 4 PM (B has killed A), the application should recompute the state from the initial one and then simply exclude A action at 5PM since at that … -
Django : Import javascript inside a template doesn't work
I'm facing a new problem with django. I'm developping a website (so I'm not in the production step) and I want to use javascript in my template. When I write my script directly on my template and link it to a button the script works. But when I want to import it from a .js file it doesn't works anymore. My static directory seems to work correctly, I can import css or even images from it. Here is my files : base.html : <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% load static %} <title>Title</title> <link rel="stylesheet" href="{% static 'webcalendar/css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'webcalendar/css/style.css' %}"> {% block script %} {% endblock %} </head> <body> {% block content %} {% endblock %} </body> </html> fonction_test.html : where the script is directly written in the template {% extends 'webcalendar/base.html' %} {% block script %} <script type="text/javascript"> function printInConsole(){ console.log("PRINTING...") } </script> {% endblock %} {% block content %} <button onclick="printInConsole()" class="btn btn-warning">Print in console</button> {% endblock %} So the previous one is working. But if I try to import the script from a .js file in the static folder of my app it doesn't works. … -
Access data form the internet [on hold]
I have a question (obviously). I want to build an e-reputation web app. In this e-reputation app, users will type in there name and last name and they will see what's on the internet. However, I can't manage to access public data. Is it possible to access public data from the internet ? If so, what language will be the most effective : java (Spring) or Python (Django) thanks! -
redirect old url to new url with django
I changed my website url to new one , but google is showing my old url , i have read that i need to make 301 redirect to help google to show my new url, but i don't know how to make it with django! my old url : path('<int:pk>/', views.ArticleDetail.as_view(), name='detail') my new url : path('<int:pk>/<slug>', views.ArticleDetail.as_view(), name='detail') more info : i'm using nginx -
Getting Bad Request 400 when sending data to django rest framework through axios
I am trying to make a web application in which django with django-rest-framework serves APIs and Vuejs2 is used for frontend purposes. Here is models.py class ClientEntry(models.Model): id = models.AutoField(primary_key=True) parent_name = models.CharField( max_length=30, blank=False, help_text="Enter parent's name" ) student_name = models.CharField( max_length=30, blank=True, help_text="Enter student's name" ) tutor_name = models.CharField( max_length=30, blank=False, help_text="Enter tutor's name" ) mode_payment = models.CharField( "mode of payment", max_length=30, blank=False, help_text="how are we getting paid" ) amount_recieved_parent = ArrayField( models.CharField( max_length=30 ), blank=True, null=True ) payment_mode_parent = ArrayField( models.CharField( max_length=30 ), blank=True, null=True ) date_payment_parent = ArrayField( models.DateField(), blank=True, null=True ) amount_payed_tutor = ArrayField( models.CharField( max_length=30 ), blank=True, null=True ) payment_mode_tutor = ArrayField( models.CharField( max_length=30 ), blank=True, null=True ) date_payment_tutor = ArrayField( models.DateField(), blank=True, null=True ) payment_status = models.CharField( max_length=30, blank=True, null=True ) tuition_status = models.CharField( max_length=30, blank=True, null=True ) payment_due_date = models.DateField( blank=True, null=True ) class Meta: ordering = ['id'] verbose_name_plural = "Client entries" def __str__(self): return str(self.parent_name) serializers.py class ClientEntrySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ClientEntry fields = ('url', 'id', 'parent_name','student_name', 'tutor_name', 'mode_payment', 'amount_recieved_parent', 'payment_mode_parent', 'date_payment_parent', 'amount_payed_tutor', 'payment_mode_tutor', 'date_payment_tutor', 'payment_status', 'tuition_status', 'payment_due_date') views.py class ClientEntryViewSet(viewsets.ModelViewSet): queryset = ClientEntry.objects.all() serializer_class = ClientEntrySerializer Here are three of the vue components which are directly related to my … -
how to create pdf file form template in django
I want to make a pdf file using Django. I found the ReportLab and I implemented but the main problem is that I want to create the pdf file from my template. How can do this ? This is the View from io import BytesIO from reportlab.pdfgen import canvas from django.http import HttpResponse import random def write_pdf_view(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="mypdf.pdf"' buffer = BytesIO() p = canvas.Canvas(buffer) papercustomization = ShortBlankDescriptionQuestions.objects.get(id=1) # Start writing the PDF here p.drawString(100, 100, papercustomization.sbd_question_text) # End writing p.showPage() p.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response -
Creating a model form to get data from a custom field i . Django
So, I am working on this project, where I am performing an upload to S3 bucket using javascript and for that, I have create a widget and created a ModelForm with URLField in it. I would like to use the URL Field(which is set by the Javascript at runtime) that I want to be used for saving in the model. My codes are below: widgets.py class S3DirectWidget(widgets.TextInput): class Media: js = ( 's3direct/js/bundled.js', 'https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js', ) css = { 'all': ( 's3direct/css/bootstrap-progress.min.css', 's3direct/css/styles.css', ) } def __init__(self, *args, **kwargs): self.upload_to = kwargs.pop('upload_to', None) super(S3DirectWidget, self).__init__(*args, **kwargs) def render(self, name, value, attrs=None, **kwargs): if value: file_name = os.path.basename(urlunquote_plus(value)) else: file_name = '' tpl = os.path.join('s3direct', 's3direct-widget.tpl') output = render_to_string(tpl, { 'signed_url': reverse('s3direct'), 'element_id': self.build_attrs(attrs).get('id', '') if attrs else '', 'file_name': file_name, 'upload_key': os.path.join(self.upload_to, file_name), 'file_url': value or '', 'name': name, 'style': self.build_attrs(attrs).get('style', '') if attrs else '', }) return mark_safe(output) models.py class Kitten(models.Model): video = models.URLField(editable=False) forms.py class S3DirectUploadForm(forms.ModelForm): misc = forms.URLField(widget=S3DirectWidget(upload_to='carousel/')) class Meta: model = Kitten exclude = ('video',) def save(self, commit=False): super(S3DirectUploadForm, self).__init__(commit) admin.py class KittenAdmin(admin.ModelAdmin): form = S3DirectUploadForm admin.site.register(Kitten, KittenAdmin) What my goal is to modify the misc(FormField) runtime and replace it as video(ModelField) to save an object. -
Custom Wagtail permissions
Hello my fellow developers. I need help with permissions for Wagtail site. So my situation is this, I need to create pages that required the user to be logged in. The problem is that django permissions revolve around views. Wagtail does not views but classes (Page Model). So these private pages will be under '/portal/'. I don't know how many pages there will be. I am hoping to continue wagtails for creating dynamic pages. -
django custom authentication not working (authenticate function nor called)
I have created a class to perform custom authentication with postgresql. The problem I have is the authenticate function is not called to perform authentication. I run in debug and I have no call to: def authenticate(self, username=None, password=None, **kwargs): Where is my problem? here is my custombackends.py from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend import psycopg2 class PostgresAuthBackend(ModelBackend): def authenticate(self, username=None, password=None, **kwargs): print('Try to login') connection_string = "host = '172.25.1.151' dbname='TMS' port = 5432" try: connection_string += " user='{}' password='{}'".format(username, password) connection = psycopg2.connect(connection_string) if connection: try: user = User.objects.get(username=username) except User.DoesNotExist: # Create a new user. There's no need to set a password # because only the password from settings.py is checked. user = User(username=username, password=password) user.is_staff = True user.is_superuser = True user.save() return user return None except psycopg2.Error as e: print("Unable to connect to the PostgreSQL server, check the connection string!") print(e.pgerror) print(e.diag.message_detail) except Exception as error: print("Unknown error", error) finally: if connection is not None: connection.close() and full settings.py """ Django settings for TMS_Services project. Generated by 'django-admin startproject' using Django 2.1.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os … -
How to mock a Django internal library using patch decorator
I'm mocking an internal library class (Server) of python that provides connection to HTTP JSON-RPC server. But when running the test the class is not mocking. The class is used calling a project class that is a wrapper for other class that effectively instantiates the Server class. I extract here the parts of the code that give sense for what I'm talking about. Unit test: @patch('jsonrpc_requests.jsonrpc.Server') def test_get_question_properties(self, mockServer): lime_survey = Questionnaires() # ... Class Questionnaires: class Questionnaires(ABCSearchEngine): """ Wrapper class for LimeSurvey API""" def get_question_properties(self, question_id, language): return super(Questionnaires, self).get_question_properties(question_id, language) Class Questionnaires calls the method get_question_properties from class ABCSearchEnginge(ABC). This class initializes the Server class to provide the connection to the external API. Class ABCSearchEnginge: class ABCSearchEngine(ABC): session_key = None server = None def __init__(self): self.get_session_key() def get_session_key(self): # HERE the self.server keep getting real Server class instead the mocked one self.server = Server( settings.LIMESURVEY['URL_API'] + '/index.php/admin/remotecontrol') As the test is mocking Server class why it's not mocking? What is the missing parts? -
How is passed this data structure?
I retrieve in a Django web application data from a database. I need to write this data in a CSV file when user click on a button and download the file. I pass the datastructure to a specific view as a hidden form field. When I parse in the view datastructres it has not the structure as in the template, if I print the datastructure it prints letter-by-letter. My code. def export_csv(request): logger.error('calling csv view') #Process the data as required response = HttpResponse(mimetype='application/csv') response['Content-Disposition'] = \ 'attachment; filename=report_mensile_%s.csv' % \ (datetime.now().strftime('%Y%m%d-%H%M%S'),) w = csv.writer(response, dialect=csv.excel, delimiter=';', quoting=csv.QUOTE_NONNUMERIC) w.writerow(map(lambda x: x.encode('utf-8'), ['Mese', 'Anno', 'Prima emissione Token USB', 'Prima emissione CNS', 'Prima emissione Firma Remota', 'Totale Prima emissione', 'Rinnovo Token USB', 'Rinnovo CNS', 'Totale rinnovo'])) data = request.POST.get('dataset') for value in data_dej: #print letter by letter logger.debug('dataset row x row: %s ', value) template.html {% if dataset %} <form action="export_csv" method="post" enctype="multipart/form-data" class="form-stacked"> {% csrf_token %} <table> <input id="dataset" type="hidden" name="dataset" value="{{ dataset }}"> <tr> <td></td> <td colspan="4" style="width: 228px; text-align: center;"><strong>Nuove emissioni</strong></td> <td colspan="3" style="width: 228px; text-align: center;"><strong>Rinnovi</strong></td> </tr> <tr> <td><strong>Mese</strong></td> <td>USB</td> <td>CN</td> <td>FR</td> <td><strong>Totale</strong></td> <td>USB</td> <td>CN</td> <td><strong>Totale</strong></td> </tr> <tr> {% for value in dataset %} <td>{{ value.mese }}</td> <td>{{ value.p_usb …