Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Insert data to sqlite3 - python - django
I'm new to django framework. I parsed data from WebAPI server to dict: key is product buys and value is list that contains info about product. Code: def get_best_products(self): dict_of_items = {} for x in range (0, self.max_range): itemId = self.fresh_data.item[x].itemId itemTitle = self.fresh_data.item[x].itemTitle photoUrl = self._get_main_item_photo(x) itemPrice = self._get_item_price(x) dict_of_items[self.fresh_data.item[x].bidsCount] = [itemId, itemTitle, itemPrice, photoUrl] return self._sort_parsed_item_data(dict_of_items) def _sort_parsed_item_data(self, data): return OrderedDict(sorted(data.items(), reverse=True, key=lambda t: t[0])) So i have dict of sorted items by product buys with info as value. What is best way to put this data to database? Should i build a model? And if yes how to do it? any tips? On internet i can find examples of models that allows to edit data... or "how to build mail registration". I want to make a model that shows all the data in a table from all the auctions but i dont want to add more. I want to have only 100 records and they will be updated when a buys change. (and maybe later when i build table that table i will try to do... lets say you click on "itemID" it will take you to edit manager, where you can change what you want about … -
Gallery Slider Images Too Big
This is my first post on stackoverflow. So I am sorry for some untypical stuff in this post. I have programmed a Django Website with a gallery slider, but I have no idea why the images are way too big. Look Here: https://imgur.com/a/YNxu7 I have spent a lot of hours to fix it but, but without sucess. {% block content %} <!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script --> <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <!-- Pictures --> <div class="item active"> <img src="/static/img/portfolio/1.jpg" class="img-responsive" alt="Cover1"> <div class="carousel-caption"> <h3>Picture 1</h3> <p>Some details to it</p> </div> </div> <div class="item"> <img src="/static/img/portfolio/2.jpg" class="img-responsive" alt="Cover2"> <div class="carousel-caption"> <h3>Picture 2</h3> <p>Also some details</p> </div> </div> </div> </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> <span class="sr-only">Next</span> </a> </div> {% endblock %} -
Is there a standard way to mock Django models?
I have a model called Pdb: class Pdb(models.Model): id = models.TextField(primary_key=True) title = models.TextField() It is in a one-to-many relationship with the model Residue: class Residue(models.Model): id = models.TextField(primary_key=True) name = models.TextField() pdb = models.ForeignKey(Pdb) Unit tesing Pdb is fine: def test_can_create_pdb(self): pdb = Pdb(pk="1XXY", title="The PDB Title") pdb.save() self.assertEqual(Pdb.objects.all().count(), 1) retrieved_pdb = Pdb.objects.first() self.assertEqual(retrieved_pdb, pdb) When I unit test Residue I just want to use a mock Pdb object: def test_can_create_residue(self): pdb = Mock(Pdb) residue = Residue(pk="1RRRA1", name="VAL", pdb=mock_pdb) residue.save() But this fails because it needs some attribute called _state: AttributeError: Mock object has no attribute '_state' So I keep adding mock attributes to make it look like a real model, but eventually I get: django.db.utils.ConnectionDoesNotExist: The connection db doesn't exist I don't know how to mock the actual call to the database. Is there a standard way to do this? I really don't want to have to actually create a Pdb record in the test database because then the test won't be isolated. Is there an established best practices way to do this? Most of the SF and google results I get for this relate to mocking particular methods of a model. Any help would be appreciated. -
Django View function. Can't get a value from Dictionary, only full dictionary
I want to get a value from a dictionary which I get from request session words = request.session['words'] In the Python console I get my excepted result: >>> words {0: "value_0", 1: "value_1", 2: "value_2", 3: "value_3", 4: "value_4"} >>> words[0] 'value_0' I have a variable called wordcount = 0 and get the result exactly as expected, whatever else. >>> words[wordcount] 'value_0' But, If I try to get a value in my Django view function, it doesn't work Here are my two view functions: def first_view(request): words = {} wordcount = 0 request.session['wordcount'] = wordcount for i in range(5): words[i] = "value_" + str(i) request.session['words'] = words def second_view(request): if request.method == "POST": message = "checkpoint_1" words = request.session['words'] wordcount = request.session['wordcount'] if request.POST.get("input"): input = request.POST.get("input").upper() message = words[wordcount] data = {'message': message} return JsonResponse(data) The second view is called by an Ajax-Request $(button).on('click', function(event) { event.preventDefault(); var input = $('#input').val(); $.ajax({ method: "POST", url: "/second_view/", data: { "input": input }, dataType: "json", context: this, success: function (data) { output.innerHTML = data.message; } }); }); My exception is, that the Response data.message is 'value_1', but I get the 'checkpoint_1' message. If I replace the following part: if request.POST.get("input"): input … -
How to have different serializers for read_only & write_only with the same name in DRF?
After you create a Django object in a CreateAPI of DRF, you get a status 201 created and the object is returned with the same serializer you used to create the Django object with. Wanted: on create: Serializer.comments = Textfield(write_only=True) and on created (201 status) Serializer.comments = a list of commments I know it's possible by overriding the CreateAPIView.create function. However, I'd like to know if it's possible by using write_only=True and read_only=True attributes to serializer fields. For now I think it's not possible because they both have the same name. I'd have liked to do something like this: class CreateEventSerializer(serializers.ModelSerializer): comments_readonly = serializers.SerializerMethodField(read_only=True, label='comments') class Meta: model = Event fields = ('id', 'comments', 'comments_readon) def __init__(self, *args, **kwargs): super(CreateEventSerializer, self).__init__(*args, **kwargs) self.fields['comments'].write_only = True def get_comments_readonly(self, obj): comments = obj.comments.replace('\r', '\n') return [x for x in comments.split('\n') if x != ''] But this way, the JSON that is returned still contains the key "comments_readonly" instead of the expected key "comments". Using latest DRF, 3.7.1 In other words: Is it possible to create a serializer field that behaves differently based on read and write? -
No JSON object could be decoded - Need to upload file to Django
I'm working on an existing Django app and need to be able to upload a file. I'm sending it a multi-part form so I can send a file and some fields, but the server responds back No JSON object could be decoded How can I allow my view to accept a multi-part form? My route function definition is simply: @api_view(['POST']) def upload(request, pk) print "hello" It doesn't get to hello, so somewhere in the magical box of Django this JSON error is occuring. Can anyone give me a clue where to look? I've checked our urls.py file and see nothing that would make this decision or interrupt a request and our init.py file is empty. runserver isn't even a file... I guess it's just more django magic. (Python: 2.7, Django: 1.10.6) -
Django POST request does not organize data as expected
So I have a form that I'm posting to a Django app. The field names are such as: field[section][name][attr] where section, name, etc. can have any number of values. When I attempt to access the data in the POST request these are the exact keys in the QueryDict, so to access the data I have to do something like request.POST.get('field[section][name][attr]'). Why doesn't Django create the hierarchy so I can do something like fields = request.POST.getlist('field') and then go deeper from there with something like for section, value in fields: for field_name, attributes in value: It seems I have to use regex's to process the form data. Am I missing something? -
How to pass Django filter args as arguments to other function
I want to make a class function that returns the result of a filter, but I want to be able to use it as if the function was a django filter too: This is what I've tried: def section_set_with_compound(self, *args, **kwargs): print args print kwargs return self.section_set.filter(Q(args) |Q(course__is_compound=True)) But im getting an error as if args and kwags are empty: I want to be able to do: myobject.section_set_with_compound(param1=1,param2__param3__=x,param4__icontains="ha..") How can I accomplish this? -
My form fields are no longer coming though on the update page?
I have a model 'Partner' with a one-to-many relationship to 'Product'. When I added the 'Product' formset I broke something to do with the relationships - the html still shows up eg <h3>Products</h3>, and the submit button remains but there are no longer any of the form boxes. So it looks like the form is being loaded but something isn't being passed anymore maybe. Any help would be greatly appreciated. Here is my code below. my forms.py <div class="container"> <div class='col-sm-6'> <h1>Preview</h1> <hr/> <div class='content-preview'> <h3 id='preview-name'></h3> <p id='preview-mission'></p> <p id='preview-vision'></p> <p id='preview-website-link'></p> <p id='preview-fb-link'></p> <p id='preview-twitter-link'></p> <p id='preview-ig-link'></p> </div> </div> <div class='col-sm-6'> <h1>Form</h1> <hr/> <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %} {{ partnerForm|crispy }} {{ formset.management_form }} <br> <h3>Products</h3> {% for form in formset %} {{ form|crispy }} {% endfor %} <input type='submit' class='btn btn-default' value='Create Partner' /> </form> </div> </div> my form.html class PartnerForm(forms.ModelForm): mission = forms.CharField(widget=PagedownWidget(show_preview=False)) vision = forms.CharField(widget=PagedownWidget(show_preview=False)) # publish = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Partner fields = [ "name", "logo", "banner_image", "mission", "vision", "website_link", "store_link", "fb_link", "twitter_link", "ig_link", ] class ProductForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Product fields = [ "name", "link", "description", "price", "image", ] my views.py from django.contrib import messages from … -
Gunicorn can't create .sock file using .BASH script
We have two ways to start gunicorn: Use command 'systemctl start gunicorn' and config file 'gunicorn.service', then it create .sock file as it should be. I can see myproject.sock file using use command 'ls /webapps/myproject'. [Unit] Description=gunicorn daemon After=network.target [Service] User=myproject Group=nginx WorkingDirectory=/webapps/myproject ExecStart=/usr/bin/gunicorn —access-logfile - —workers 3 —bind unix:/webapps/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target Create and use .BASH script 'gunicorn_start.bash', becouse it`s good way with 'virtualenv', but then we start gunicorn at this script, .sock file not create. I not see myproject.sock file using command 'ls /webapps/myproject'. Can't configure nginx without gunicorn myproject.sock. How to fix this? - Tell me, please. #!/bin/bash NAME="tdkennel" # Name of the application DJANGODIR=/webapps/myproject/ # Django project directory SOCKFILE=/webapps/myproject/myproject.sock # we will communicte using this unix socket USER=myproject # the user to run as GROUP=webapps # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=myproject.settings # which settings file should Django use DJANGO_WSGI_MODULE=myproject.wsgi # WSGI module name echo "Starting $NAME as myproject" # Activate the virtual environment cd $DJANGODIR export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to … -
How to calculate events per hour by route and daterange
How can I calculate stops per hour by route and date model: MyModel(models.Model): route = models.Integer(... on_route_time = models.TimeField(... dropoff_stops = models.Integer(... pickup_stops = models.Integer(... date = models.DateTime(... My query: def stops_per_hour(date): query_set = MyModel.objects.filter(date=date).values( 'route', 'dropoff_stops','pickup_stops','on_route_time').annotate( total=(Sum('actual_stops') + Sum('pickup_stops'))).order_by('route') which gives me: <<QuerySet [{'route': 226, 'dropoff_stops': 84, 'pickup_stops': 0, 'on_route_time': datetime.time(5, 23), 'total': 84},{'route': 242, 'dropoff_stops': 33, 'pickup_stops': 0, 'on_route_time': datetime.time(3, 24), 'total': 33}]>> I'm stuggling with how calculating stops/hour for each route and passing this to the view (e.g. route 226 stops/hour = 15.18. Suggestions? Thanks. -
Filtering select field options in django-xadmin
I am using django-xadmin for one of my project. I need help in a case. Suppose, i have two models like this - class Foo(models.Model): CHOICES = ( ('a', 'Option A'), ('b', 'Option B') ) status = models.CharField(max_length=10, choices=CHOICES) class Bar(models.Model): foo = models.ForeignKey(Foo) remarks = models.CharField(max_length=200) In xadmin, when i try to add Bar via default form provided by xadmin, in the select Field Foo, all Foos (both with Option A and Option B) become available to select. I want to filter the options and only provide, say, Foos of Option A. How can i do that ? Is there any method in xadmin, i should call or customize to achieve it ? -
Trying to use Docker with Django but server not starting
I'm trying to start a Django app using Docker on Windows 10. I'm following the Quickstart Tutorial here: https://docs.docker.com/compose/django/#connect-the-database When it gets to the docker-compose up part, to actually start the app, it gets stuck. This is the docker-compose.yml: version: '3' services: db: image: postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db This is the Dockerfile: FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ when I use docker-compose up it gets stuck in: web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). -
How can I reverse django admin url with url parameters to prepopulate some fields?
I have Transaction app and Transaction model. Transaction model has foreign key to User model. I noticed that I can prepopulate some fields with data through GET parameters. For example to choose user for my transaction in admin form I can use this url: transactions/transaction/add/?user=1 It work fine, but I want to user reverse function to generate that kind of urls. Tried this: from django.urls import reverse reverse('admin:transactions_transaction_add', kwargs={'user': 1}) But got this error: Reverse for 'transactions_transaction_add' with arguments '()' and keyword arguments '{'user': 1}' not found. 1 pattern(s) tried: ['admin/transactions/transaction/add/$'] I made this work to use concatenate generated link: change_url = reverse( "admin:transactions_transaction_add", ) + "?user=" + str(obj.pk) But would be very kind to know if the more clear solution for this. Note that 'transactions/transaction/add/?user=1' works just fine if use it from browser, error appears for reverse function. Thanks! -
Does a foreign key object have a unique id value?
I am creating a job board site, where all jobs are displayed in a list and each one is a link that leads to a page displaying more information about the job. I have the following models: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.first_name @receiver(post_save, sender=User) def create_employer(sender, instance, created, **kwargs): if created: Employer.objects.create(user=instance) @receiver(post_save, sender=User) def save_employer(sender, instance, **kwargs): instance.employer.save() class Job(models.Model): poster = models.ForeignKey(Employer, on_delete=models.CASCADE) job_title = models.CharField(max_length=50) establishment_name = models.CharField(max_length = 50) address = models.CharField(max_length = 50) state = models.CharField(max_length = 20) zip_code = models.CharField(max_length = 10) def __str__(self): return self.job_title + " - " + self.establishment_name \ + ", " + self.poster.user.first_name + " " +self.poster.user.last_name Views.py: def index(request): jobs = Job.objects.all return render(request, 'core/index.html', {'jobs' :jobs }) On index.html, the available jobs are listed as so: <table> <tbody> {% for job in jobs %} <tr> <td><a href="#">{{ job.job_title}} - {{ job.establishment_name }}</a></td> </tr> {% endfor %} </tbody> </table> I want these to be clickable links, that will bring the user to another page giving them more details about the job. I … -
TypeError at /notes/index/ context must be a dict rather than RequestContext
hello guys i have a error with django i dont know where exactly the error is please have a look at my code and help me solving this is my views.py from notes app from django.shortcuts import render from django.http import HttpResponse from django.template import loader,RequestContext # Create your views here. def index(request): template=loader.get_template("index.html") rc=RequestContext(request,{'username':'hello'}) return HttpResponse(template.render(rc)) this is my settings.py configuration from appsuite project folder BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '&1hv71rr0e7b!m)7sv(p7of0p7q0%-mb9o*^r*amw$d1o3%=s_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'appsuite.urls' WSGI_APPLICATION = 'appsuite.wsgi.application' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'notes/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', ], }, }, ] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, … -
UnboundedLocalError in Django
I'm getting UnboundedLocalError in django. Exception-value:local variable 'comment_form' refrenced before assignment. I used ModelForms from forms to create a comment form.So this is the views.py file of the comment form. def post_detail(request,year,month,day,post): '''post=get_object_or_404(Post,slug=post,status='published',publish__year=year, publish__month=month,publish__day=day)''' try: post=Post.published.get(slug=post) except Post.DoesNotExist: raise Http404("Post Doesnot Exist") #list of active comments for the post comments=post.comments.filter(active=True) if request.method=='POST': #a comment was posted comment_form=CommentForm(data=request.POST) if comment_form.is_valid(): #create comment object but dont save to database yet new_comment=comment_form.save(commit=False) #assign the current post to the comment new_comment.post=post #save the comment to database new_comment.save() else: print (form.error) comment_form=CommentForm() return render(request,'blog/post/detail.html',{'post':post,'comments':comments,'comment_form':comment_form}) '''return render(request,'blog/post/detail.html',{'post':post})''' template detail.html {% extends "blog/base.html" %} {% block title %}{{ post.title }}{% endblock %} {% block content %} <h1>{{ post.title }}</h1> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|linebreaks }} (% with comments.count as total_comments %} <h2> {{total_comments}}comment{{total_comments|pluralize}} </h2> {% endwith %} {% for comment in comments %} <div class="comment"> <p class="info"> Comment {{forloop.counter }} by {{comment.name}} {{comment.created}} </p> {{comment.body|linebreaks}} </div> {%empty%} <p>There are nocomments yet.</p> {% endfor %} {% if new_comment %} <h2>Your comment has been added.</h2> {% else %} <h2>Add a new comment.</h2> <form action="." method="post"> {{comment_form.as_p }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> {% endif %} {% endblock %} … -
Running tensorflow application using django with wsgi
I deployed my application which runs with Tesorflow object detection API on Ubuntu 16.04LTS. It is a web application running on django and i want to serve it with apache and wsgi. When i access the apache server through my server's IP address i get the following error: ImportError at / Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in from tensorflow.python.pywrap_tensorflow_internal import * File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) ImportError: /usr/local/lib/python3.5/dist-packages/tensorflow/python/_pywrap_tensorflow_internal.so: undefined symbol: PyBytes_AsStringAndSize Failed to load the native TensorFlow runtime. -
Truncated text in django template filter with an href link
I want to truncate my post content using a Django template tag filter such as (|truncatewords_html: my_number) But with an href link for the dots that redirect the user to the detailed post url. I know I can build a custom template tag to perform this functionality. But I just wanted to check (since I did not found any) if there is a built-in method to do what I want. -
Why is the Django decimal max_digits validation failing with strange behaviour?
I have a model field full_time_equivalent: full_time_equivalent = models.DecimalField( max_digits=5, decimal_places=2, default=100, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(100)) ] ) To ensure that the validators fire I have override save with: def save(self, *args, **kwargs): # Run validations self.full_clean() return super().save(*args, **kwargs) With the following test: project2_membership = ProjectMembership( user=self.new_user, project=project2, is_project_manager=False, full_time_equivalent=10.01 ) When I step into the validation the following value is shown and respective error: Decimal('10.0099999999999997868371792719699442386627197265625') django.core.exceptions.ValidationError: {'full_time_equivalent': ['Ensure that there are no more than 5 digits in total.'] What am I doing wrong? -
How to get field[] in django?
I'm trying to use array field in django to dynamically add fields using javascript like user clicks on button and a new field appear However I cannot figure out how to make django to render field as "field[]" name, neither I can't get that field value in django view. I was thinking in FormSets but it doesn't seems to be what I need -
DJANGO how to send one of the model parameters instead of it's url to .json
I am a Django beginner and I believe this is a rather simple question, still, i couldn't find anything on it. Thanks in advance! I am trying to get the parameter "nome" from the "Especie" model to appear on the .json file: My models.py: from django.db import models class Zona(models.Model): codigo = models.CharField(max_length=120) especies = models.ForeignKey('Especie') def __str__(self): return self.codigo class Especie(models.Model): nome = models.CharField(max_length=120) zonas = models.ForeignKey(Zona) def __str__(self): return self.nome My serialisers.py(using django rest framework): class EspecieSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Especie fields = ('nome', 'nome_latino', 'zonas', 'id') class ZonaSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Zona fields = ('codigo', 'area', 'especies', 'id') views.py: from django.shortcuts import render from species.models import Especie, Zona from rest_framework import viewsets from rest.serializers import ZonaSerializer, EspecieSerializer class EspecieViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Especie.objects.all().order_by('-data_insercao') serializer_class = EspecieSerializer class ZonaViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Zona.objects.all() serializer_class = ZonaSerializer Instead im getting the URL to the "especie" in question, as you can see here: "codigo": "A1", "area": "Alvalade", "especies": "http://127.0.0.1:8000/especies/1/", "id": 1 thank you! -
Django sqlite3 timeout has no effect
I have a simple integration test in Django that spawns a single Celery worker to run a job, which writes a record to the database. The Django thread also writes a record to the database. Because its a test, I use the in-memory sqlite database. There are no transactions being used. I often get this error: django.db.utils.OperationalError: database table is locked which according to the Django docs is due to one connection timing out while waiting for another to finish. It's "more concurrency than sqlite can handle in default configuration". This seems strange given that it's two records in two threads. Nevertheless, the same docs say to increase the timeout option to force connections to wait longer. Ok, I change my database settings to this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'OPTIONS': {'timeout': 10000000}, } } This has no effect. The error still appears and it clearly has not waited 1e7 seconds or 1e7 milliseconds or 1e7 microseconds before doing so. Is there an additional setting I'm missing? This is in Python 3.5 and I tried both Django 1.11 and Django 2.0. -
django haystack elasticsearch wont give correct result
I have a problem with django-haystack elasticsearch. I have a search for question where one field is study_level which is an int of 1 to 13. When I try to make a search to include question within a range like 10-12 it also gives questions with other study_level. It seems like study_level don't matter in the search. I have this index class QuestionIndex(indexes.SearchIndex, indexes.Indexable): """ A Haystack search index for Questions. """ text = indexes.EdgeNgramField(document=True, use_template=True) id = indexes.IntegerField(model_attr='id') user_id = indexes.IntegerField(model_attr='user_id') question = indexes.EdgeNgramField(model_attr='question', boost=1.15) study_level = indexes.IntegerField(model_attr='study_level') is_answered = indexes.IntegerField(model_attr='is_answered') is_archived = indexes.BooleanField(model_attr='is_archived') created_at = indexes.DateTimeField(model_attr='created_at') tags = indexes.MultiValueField() schools = indexes.MultiValueField() answers = indexes.IntegerField(indexed=False) has_answer = indexes.IntegerField(indexed=False) content = indexes.CharField(indexed=False) content_short = indexes.CharField(indexed=True) def get_model(self): return Question def prepare_study_level(self, obj): study_level = obj.study_level There is more def prepare_x but study_level is where my problem is. Then it is used in this code class QuestionSearch(object): # Plain old Python object for question search. MAX_RESULT_LENGTH = 12 def __init__(self, user, query='', limit=MAX_RESULT_LENGTH, subjects=[], study_level_min=None, study_level_max=None): self.user = user self.query = query self.limit = limit self.subjects = subjects self.study_level_min = study_level_min self.study_level_max = study_level_max # Swaps the min and max values if they are in the wrong order. if study_level_min … -
Why do I get not allowed access when using keycloak JavaScript adapter?
I have a Django app authenticating via Keycloak as described here. From this Django app I now wants to call a microservice also protected by Keycloak using the same login. I don't want the suer to have to login again. I am trying to yse the JavaScript adapter. I am trying to configure it something like: <script> var keycloak = Keycloak({ url: "{{Keycloakurl}}/auth", realm: 'myrealm', clientId: 'myclient' }); keycloak.init({ onLoad: 'login-required' }).success(function(authenticated) { alert(authenticated ? 'authenticated' : 'not authenticated'); }).error(function() { alert('failed to initialize'); }); </script> But when I load the page I get this sort of error messages: Failed to load http://keycloak.FOO.com/auth/realms/toxhq/protocol/openid-connect/token: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myapp.Foo.com' is therefore not allowed access. I am not fully sure why this is but I am beginning to wonder if it is because of same-origin policy in some way. How can I set up the functionality I want with Keycloak protected microservices sharing one Keycloak authentication?