Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to figure out which app calls get_absolute_url in Django
I have a model class named Store in my boutique/models.py boutique/models.py def get_absolute_url(self): return "/%s/" % self.domainKey def get_absolute_url(self): return reverse('cms:store_edit', args=[self.pk]) The first get_absolute_url function is used when it's called in boutique app. The second one is used when it's called in cms app. def get_absolute_url(self): if boutique_called: return "/%s/" % self.domainKey else cms_called: return reverse('cms:store_edit', args=[self.pk]) I wanna do something like above. How can I distinguish they each call the function? -
Fatest way to export Django model with calculated extra fields
I am currently at the task when I need the fastest way to export model fields, but with custom calculated fields in Django. I try to use this Django plugin (django-queryset-csv) to export QuerySet with annotations to achieve this task. Because it is really fast way to get CSV from model. Problem But now I am stuck because I need to use formatting on one of the fields. Here is part of the code: qs = User.objects.all().annotate( country=Value('CZ', output_field=CharField()), epos_id=Concat(Value("%04d" % epos_id_prefix), Value('-'), F('ldap_id'), output_field=CharField()), physical_delivery_office_name=Concat(F('ldap__floor'), Value(', '), F('ldap__door')), ) Variable epos_id_prefix is passed as function parameter. So it can be used as a source for formatting. But I also need to pass one of the values from QS just like 'ldap__id'. Basically I need to format number to a number with leading zeros and with length of 8 numbers. Approach I wanted to use it this way: qs = User.objects.all().annotate( country=Value('CZ', output_field=CharField()), epos_id=Concat(Value("%04d" % epos_id_prefix), Value('-'), Value("%08d" % F('ldap__id'), output_field=CharField()), physical_delivery_office_name=Concat(F('ldap__floor'), Value(', '), F('ldap__door')), ) but it obviously gives me an error: TypeError: %d format: a number is required, not F Questions I understand that, but can I CAST value as number? Is it possible to achieve using this … -
Many to Many Nested Relationship as List in Django Rest Framework
I'm building an API using the Django Rest Framework and I have two models that share a many to many relationship. The models are Contacts and Tasks. A Task can be shared with several Contacts and a Contact can have many Tasks shared with it. I'm also using a manual join table, rather than Django's built-in many-to-many relationship. In the API, I'd like to have the method for retrieving Tasks include a list of Contacts with whom the Task has been shared. I have a way of accomplishing this currently, but it isn't great. The serialized Task has an attribute shared_with, which is a related field that goes through the SharedWithSerializer class (which is the version of the ContactTaskJoin serializer for this side of the relationship). So the output is quite clunky. The SharedWithSerializer has just one attribute—contact—which references the ContactSerializer class. An example Task returned by the API: { 'id': 100, 'shared_with': [ { 'contact': { 'id': 1, 'name': 'Alice' } }, { 'contact': { 'id': 2, 'name': 'Bob' } } ] } What I would like is to just have a plain list of the Contacts with whom the Task was shared. Something like: { 'id': 100, 'shared_with': … -
Can my Local Eclipse Install Access Libraries in Docker Container?
I have a Docker image that I use for Django development, and via some xauthority file mechanics, I use Eclipse from within the container. For the most part, Eclipse works well, but there are a few nagging issues that seem to be related to the fact it's running inside a container; after all, Docker wasn't really developed for this purpose. So, I wonder... If I run an instance of Eclipse on my local machine, can I configure a given project to access the libraries installed in a running container? That is, have it resolve imports, run code using Python 2 or 3/Django 1 or 2 depending on the individual project and the container it's accessing? Host Machine: CentOS 7 Base Image: Ubuntu 16.04 -
myfile.html not found, how to make properly the path
ok, my_first_site.html works fine with my site.py but when i try to take a link it just ignore the fact that the file exists someone have a guess?, i tried changing with the complete file location, used /path then path and then /path/ any of then work, but if i try just using the .html file it magically works (if i change the paths to /path/file.html there is the files my_first_site.html: <html> <head> <title>my first page</title> </head> <body> <h1>my first web page</h1> <p>my officially first page</p> <blockquote><h1>links</h1></blockquote> <li><a href="/gramatica/" target="_blank">list of text edit of HTML</a></li> <li><a href="/uso de imagens/" target="_blank">images work</a></li> <li><a href="/tabelas/" target="_blank">charts work</a></li> <li><a href="/formularios/" target="_blank">boxes of information</a></li> </body> </html> site.py from flask import Flask from flask import render_template from flask import request import pickle from django import forms TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.contrib.messages.context_processors.messages", "django.core.context_processors.request", ) app = Flask(__name__, template_folder='C:/Users/Lucas/Desktop/programming/site_work/') @app.route('/') def meu_primeiro_site(): return render_template("meu_primeiro_site.html") @app.route('/gramatica/') def gramatica(): return render_template('gramatica.html') @app.route('/formularios/',methods=['GET', 'POST']) def preencher(): if request.method == 'POST': form_input = request.form['e-mail'] form_input1 = request.form['password'] form_input2 = request.form['comments'] form_input3 = request.form['genre'] form_input4 = request.form['soomee'] form_input5 = request.form['devices'] form_input6 = request.form['things'] info ={'password':form_input1, 'comments':form_input2, 'genre':form_input3, 'checked':form_input4, 'devises':form_input5, 'things':form_input6} #it dont warn if user exist also … -
How to add a Many-To-Many object to an existing object in django
I have a few simple classes: Visitor, Student and Visit The Visit model looks like this: class Visit(models.Model): visitor = models.ForeignKey(Visitor, on_delete=models.PROTECT) students = models.ManyToManyField( Student, blank=True) check_in = models.DateTimeField(auto_now_add=True) check_out = models.DateTimeField(null=True, blank=True) def __str__(self): return "%s : %s" % (self.visitor, self.students) For testing purposes - I'm trying to test the creation of a Visit class VisitModelTest(TestCase): """Test class for the Visit model""" def create_visit(self): visitor = Visitor.objects.create(type='P', first_name='Test', last_name='McTest', birth_date=date(1981, 10, 16)) student = visitor.student_set.create(first_name='Tester', last_name='McJrTest') visit = visitor.visit_set.create(visitor=visitor) visit.students.add(student) return visit def test_visit_creation(self): visit = self.create_visit() self.visitor = mixer.blend(Visitor, type='P', first_name='Test', last_name='McTest', birth_date=date(1981, 10, 16)) self.students = self.visitor.student_set.create(first_name='Tester', last_name='McJrTest') self.assertTrue(isinstance(visit, Visit)) self.assertEqual(visit.__str__(), "%s : %s" % (self.visitor, self.students)) In my line where I call visit.students.add(student) nothing is happening. My assertions fail with this error: self.assertEqual(visit.__str__(), "%s : %s" % (self.visitor, self.students)) AssertionError: 'McTest, Test : visitor_check_in.Student.None' != 'McTest, Test : McJrTest, Tester' - McTest, Test : visitor_check_in.Student.None + McTest, Test : McJrTest, Tester What is the appropriate way to add a student to that Visit instance? -
Django Attribute error:'function' object has no attribute '__self__'
Django Attribute error:'function' object has no attribute 'self' This is my model.py file and I am getting following error: from django.db import models # Create your models here. import uuid from rgbfield.fields import RGBColorField class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) index = models.IntegerField(unique=True, db_index=True) name = models.CharField(unique=True, max_length=100) abbreviation = models.CharField(max_length=4, unique=True) theme_color = RGBColorField(default="#fff") text_color = RGBColorField(default="#000") def __str__(self): return self.name class Tool(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(unique=True, db_index=True, max_length=100, help_text="The name of your tool (must be unique)") byline = models.CharField(max_length=100,help_text="The byline of your tool (can contain HTML)") description = models.TextField(help_text="A description of your tool (can contain HTML)") logo_image = models.ImageField(upload_to='image', blank=True, help_text="Use to upload an (optional) logo image for your tool") logo_link = models.URLField(blank=True, help_text="An (optional) link to be associated with your tool's logo") about_link = models.URLField(blank=True, help_text="An (optional) link to further information about your tool") install_link = models.URLField(blank=True, help_text="An (optional) link to local installation information for your tool") launch_link = models.URLField(blank=True, help_text="An (optional) link to launch your tool. If hosted by EMAC, leave this blank.") categories = models.ManyToManyField(Category, related_name="tools") is_external = models.BooleanField(default=True) def tool_directory_path(instance, filename): # Image file will be uploaded to MEDIA_ROOT/tools/<id>/<filename> return "tools/{0}/{1}".format(instance.id, filename) def __str__(self): return self.name I have checked … -
Django Rest Framework api test upload text file application/x-www-form-urlencoded
I'm trying to test my Django REST API for file uploading. The catch is that my server tries to validate the file so that the file has a recognised file type. Currently only text-based filetypes are allowed, like: docs, pdf, txt. I've tried using a temporary file and now I just tried to read a file from the disk then gave up. Whenever I use a temporary file the server responds with: { "cover_letter": [ "The submitted data was not a file. Check the encoding type on the form." ], "manuscript": [ "The submitted data was not a file. Check the encoding type on the form." ] } This is my test: def test_user_can_submit_a_paper(self): """ Ensure that an user is able to upload a paper. This test is not working.. yet """ tmp_file = open("__init__.py", "w") data = { "title": "paper", "authors": "me", "description": "ma detailed description", "manuscript": base64.b64encode(tmp_file.read()).decode(), "cover_letter": base64.b64encode(tmp_file.read()).decode() } tmp_file.close() response = self.client.post(self.papers_submitted, data=urlencode(MultiValueDict(data)), content_type='application/x-www-form-urlencoded', HTTP_AUTHORIZATION=self.authorization_header) print(response.data) self.assertEqual(response.status_code, status.HTTP_200_OK) del data["cover_letter"] response = self.client.post(self.papers_submitted, data=urlencode(MultiValueDict(data)), content_type='application/x-www-form-urlencoded', HTTP_AUTHORIZATION=self.authorization_header) print(response.data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) I have successfully tested this endpoint via postman but I don't know how to do it in Python. -
Django Model: ValueError: Missing staticfiles manifest entry for "file_name.ext"
I have the following model: from django.contrib.staticfiles.templatetags.staticfiles import static class Profile(models.Model): user = models.ForeignKey(SocialUser, on_delete=models.PROTECT) avatar_url = models.URLField( default=static('pledges/images/no-profile-photo.png')) I am using Codeship for CI, and when I run: $ python manage.py collectstatic --noinput I am getting the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/rof/.pyenv/versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/rof/.pyenv/versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/home/rof/.pyenv/versions/3.6/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/rof/.pyenv/versions/3.6/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/rof/.pyenv/versions/3.6/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/home/rof/.pyenv/versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/rof/src/github.com/company-name/project-name/pledges/models.py", line 106, in <module> class Profile(models.Model): File "/home/rof/src/github.com/company-name/project-name/pledges/models.py", line 109, in Profile default=static('pledges/images/no-profile-photo.png')) File "/home/rof/.pyenv/versions/3.6/lib/python3.6/site-packages/django/contrib/staticfiles/templatetags/staticfiles.py", line 12, in static return _static(path) File "/home/rof/.pyenv/versions/3.6/lib/python3.6/site-packages/django/templatetags/static.py", line 166, in static return StaticNode.handle_simple(path) File "/home/rof/.pyenv/versions/3.6/lib/python3.6/site-packages/django/templatetags/static.py", line 117, in handle_simple return staticfiles_storage.url(path) File "/home/rof/.pyenv/versions/3.6/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 162, in url return self._url(self.stored_name, name, force) File "/home/rof/.pyenv/versions/3.6/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 141, in _url hashed_name = hashed_name_func(*args) File … -
Return custom payload from default response
In Django 2.0 I am using the rest_auth and currently it returns a response like { "token": "foo_token", "user":{ "pk": 1, "username": "admin", "email": "test@test.com", "first_name": "John", "last_name": "Doe" } } I would like to change this to return something besides the default response django provides. Something like... { "token": "foo_token", "pk":1, "username": "admin", "somefield": "Foo Funk" } My urls.py look like this currently url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), url(r'^refresh-token/', refresh_jwt_token), url(r'^api/userlist', users.user_list), The only place I can find to possibly change the response is in library files which I am sure is not wise to change. Any help would be great. -
type object 'Album' has no attribute 'object'
I'm new to Django and web coding. I'm following Bucky tuts: Django Tutorial for Beginners - 29 - Generic Views & I'm trying to get my music ( index ) page , but it gives me that error in the browser : AttributeError at /music/ type object 'Album' has no attribute 'object' & here's my views.py : from django.http import HttpResponse, Http404 from django.shortcuts import render , get_object_or_404 from .models import Album,song from django.views import generic """ def index(request): all_albums = Album.objects.all() context = {'all_albums': all_albums} return render(request, 'music/index.html', context) """ class IndexView (generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.object.all() ''' class DetailView (generic.DetailView): model = Album template_name = "music/details.html" ''' def details(request, album_id): try: album = Album.objects.get(pk=album_id) except Album.DoesNotExist: raise Http404("Album Does Not Exists !") return render(request, 'music/details.html', {'album': album}) def favourite (request , album_id): album = get_object_or_404 (Album , pk=album_id) try: selected_song = album.song_set.get(pk=request.POST['song']) except(KeyError, song.DoesNotExist): return render(request, 'music/details.html', { 'album':album, 'error_message': "you entered wrong" }) else: selected_song.is_favorite = False selected_song.save() return render(request,'music/details.html' , {'album':album}) models.py from django.db import models # Create your models here. class Album (models.Model): artist = models.CharField(max_length = 100) album_title = models.CharField(max_length = 100) genre = models.CharField(max_length = 50) album_logo … -
Django rest frameworkd update Put not allowed
I'm trying to update an object of my database (but only one of the field), the problem is that when I try to make the update i get an error that says that the PUT method is not allowed. Here's my View: class DeviceViewSet(viewsets.ModelViewSet): """ Show, create and filter devices. """ queryset = Device.objects.all() serializer_class = DeviceSerializer def list(self, request, *args, **kwargs): devices = Device.objects.filter(user=request.user.pk, role='E') serializer = DeviceSerializer(devices, many=True) return Response(serializer.data) def create(self, request, *args, **kwargs): data = { 'registration_id': request.data['regId'], 'user': request.user.pk, 'device_id': request.data['imei'], 'type': 'android', 'label': request.data['label'], 'role': request.data['role'] } serializer = DeviceSerializer(data=data) if serializer.is_valid(): serializer.save() device = Device.objects.filter(device_id=request.data['imei']) device.send_message("Enhorabuena!", "El dispositivo se ha registrado correctamente.") return Response(serializer.data) return Response(serializer.errors) def update(self, request, *args, **kwargs): device = Device.objects.filter(device_id=request.data['imei']) device.registration_id = request.data['regId'] device.save() serializer = DeviceSerializer(device) return Response({'ok': 'oks'}) My serializer: class DeviceSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), required=False) class Meta: model = Device fields = '__all__' My url: from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from decaught import views urlpatterns = [ url(r'^devices/$', views.DeviceViewSet), ] urlpatterns = format_suffix_patterns(urlpatterns) I'm using Postman to send a PUT Request: { regId: "djasdjahdjhajhdjHHjh" imei: "000000000000000" } But I'm getting this as a response: { "detail": "Method \"PUT\" not allowed" } Any idea … -
SyntaxError: Non-ASCII character ' please help me
(untitled7) MacBook-Pro:roadBasket User$ python manage.py runserver localhost:8007 Unhandled exception in thread started by <function wrapper at 0x1103ac7d0> Traceback (most recent call last): File "/Users/Timur/Desktop/untitled7/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Users/Timur/Desktop/untitled7/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Users/Timur/Desktop/untitled7/lib/python2.7/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/Users/Timur/Desktop/untitled7/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Users/Timur/Desktop/untitled7/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/Timur/Desktop/untitled7/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/Timur/Desktop/untitled7/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/Timur/Desktop/roadBasket/orders/models.py", line 8 SyntaxError: Non-ASCII character '\xd0' in file /Users/Timur/Desktop/roadBasket/orders/models.py on line 8, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details Hi all! I cannot write a command to the moduls.py - I already tried to paste this #!/usr/bin/python # -*- coding: latin-1 -*- import os, sys but anyway doesn't work. -
View not showing when using modelform
I'm trying to display a form, using a model form in django. Everything looks like it's setup properly, and I'm not getting any error. Simply, the form is not showing, although the url is updated... views.py from rulz.models import Rulz class rules_create(CreateView): model = Rulz fields=['title', 'content'] models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Rulz(models.Model): title = models.CharField(max_length=255) content = models.TextField() country = models.CharField(max_length=255,default='France') city = models.CharField(max_length=255,default='Paris') player_num = models.IntegerField(default=2) complexity = models.IntegerField(default=1) created_on = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE,default=1) def get_absolute_url(self): return reverse('rulz:rulz_detail',kwargs={'pk':self.pk}) urls.py (in the app) app_name = 'rulz' urlpatterns = [ #/rulz/ url(r'^', views.rules_index.as_view(), name='rulz_index'), url(r'^index/$', views.rules_index.as_view(), name='rulz_index'), # /rulz/details url(r'^(?P<pk>[0-9]+)/$',views.rules_detail.as_view(),name='rulz_detail'), #rulz/create url(r'^create/',views.rules_create.as_view(),name='rulz_create'), ] urls.py (root folder) ... url(r'^rules/',include('rulz.urls')), ... app/templates/app/rulz_form.html {% extends 'rulz/Rulz_base.html' %} {% block body %} {% load staticfiles %} {% include 'rulz/form-template.html' %} {% endblock %} app/templates/app/form-template.html {% for field in form %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.errors }}</span> </div> <div class="validate-input m-b-26" > <label class="label-input100">{{ field.label_tag }}</label> <div class="input100">{{ field }}</div> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.help_text }}</span> </div> </div> </div> and finally the button with the link in my page to access the form : <a href="{% url 'rulz:rulz_create' %}" … -
Django: how can I display 1 field item as a header w/ remaining field items as the value?
I have a table displayed inside a collapsible, accordion style card component that contains three Fielditems (one per<td>). Using a forloop.counter, I am trying display each obj.frequency as the collapsible-header with all of the associated obj.product and obj.price items displaying within the collapsible-body. I recognize the current layout needs to be DRY-er by only using the object.rate_set.all loop once. I left the two obj forloops since this is the only way I can get the data within the collapsible-body section of the card, even though the data is not separated correctly. Question: How can I display the data associated with frequency inside a card body with the frequency obj output as the header? In addition to my template, a screenshot of my browser is included below for clarification if needed My Template: <div class="card"> <div class="card-body"> <ul class="collapsible popout"> {% for obj in object.rate_set.all %} <!-- ------------------------------------------------- displays each `frequency` obj in its own accordion card as the header. output: 1x, 3x, 6x, 12x, 24x.. ------------------------------------------------- --> {% if forloop.counter|divisibleby:3 %} <li> <div class="collapsible-header“>{{ obj.frequency }}</div> <div class ="collapsible-body"> {% endif %} {% endfor %} <div class="table-responsive card-text"> <table> <thead> <tr> <th>Product</th> <th>Rate</th> </tr> </thead> <tbody> <!-- ----------------------------------- displays all … -
How to decorate the ValidationError in Django
I'm using Django form to control the length of content.The function works,but the errors information contains some extra words and punctuation marks that I don't need. My question is how to delete the extra words and punctuation marks? Here is my form: def words_validator(comment): if len(comment) < 4: raise ValidationError("您输入的评论字数太短,请重新输入至少4个字符") class CommentForm(forms.Form): comment = forms.CharField(widget=forms.Textarea(), validators=[words_validator]) Here is my template: {% if comment_form.errors %} <div class="ui error" > {{comment_form.errors}} </div> {% endif %} The errors message is here: ·comment 。您输入的评论字数太短,请重新输入至少4个字符 I only need '您输入的评论字数太短,请重新输入至少4个字符',don't want the punctuation marks and the field name 'comment'. Any friend has a solution? -
Celery or without celery?
I have a use case wherein I have to process a lot many text blobs(10k or more), with each being not more than 500 characters. The processing code includes around 50 if conditions which eventually extracts and classifies the text blob and saves it to the DB(the processing code does not contain any request to any API, just old school python code written for Django). My current approach is to run every text blob through the processing code one by one. Will using celery improve the performance or the overhead for the message communication will eventually decrease it? -
Conditional Expression in Django 1.11
I have 3 models: Product, Brand, Shop. I want to count Products which are available for Brands in the given Shop. Like: Adidas 50 Puma 25 Now I have: queryset = Brand.objects .filter(brand_id__in=id_list) .order_by('brand_name') queryset = queryset.annotate(amount_of_products=Count('products')) But this gives me an amount of products from all shops. I have tried like here: queryset = queryset.annotate( amount_of_products=Count( Case(When(shops__shop_name__in=[shop], then=1)) )) But I get an amount_of_products = 1 for every Brand in the list. Is there a way to do this conditional expression in Django 1.11? -
Django complicated string representation of a model object (def __str__(self):)
I have been using str to handle human readable names for model objects for awhile now, but recently I have been running into some strange crashes and bugs that seem to be related to this function. I have two models SensorAssignment and SnComplex, both have OneToOne relationships to a column on a third model RadioSn. RadioSn is the master pool of all serial numbers. SnComplex is the list of serials assigned to a customer and SensorAssignment handles the metadata for a customer's serial assigned to a specific physical location. It is important to note that this is a legacy db that I inherited. Some relationships are not ideal IMHO. Below are simplified versions of the models with only relevant columns. RadioSn class RadioSn(models.Model): sn = models.AutoField(primary_key=True) role = models.ForeignKey('Roles', db_column='role', on_delete=models.DO_NOTHING) class Meta: managed = False db_table = 'radio_sn' ordering = ['sn'] def __str__(self): return '%s -- %s' % (self.sn, self.role) SnComplex class SnComplex(models.Model): sn = models.OneToOneField(RadioSn, on_delete=models.DO_NOTHING, db_column='sn', primary_key=True) complex = models.ForeignKey(Complex, on_delete=models.DO_NOTHING, db_column='complex') class Meta: managed = False db_table = 'sn_complex' SensorAssignment class SensorAssignment(models.Model): unit = models.ForeignKey('Unit', on_delete=models.DO_NOTHING, db_column='unit') sn = models.OneToOneField(RadioSn, on_delete=models.DO_NOTHING, db_column='sn') class Meta: managed = False db_table = 'sensor_assignment' ordering = ['sn'] def __str__(self): return … -
POST request in TemplateView Django
I'm using Django 2.0 I have a TemplateView that renders only the template. Since the template is rendered using ajax, I have to send token using POST just to verify and there is no need of form. I tried following Case 1: views.py class LearnQuestion(TemplateView): # form_class = SessionForm template_name = 'learn/learn_question.html' def get_context_data(self, **kwargs): context = super(LearnQuestion, self).get_context_data(**kwargs) # get session data session = self.request.POST.get('session') print(session) context['session'] = session return context @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(self.__class__, self).dispatch(request, *args, **kwargs) Ajaxrequest <input id="session-d" value="{{ session }}" type="hidden"> $(window).on('load', function() { console.log($('#session-id').val()) $('#question-box').load("{% url 'learn:question' course_learn.pk %}", {session:$('#session-id').val()}, function(){ runTimer(); }); }); But this gives error Forbidden (CSRF token missing or incorrect.): /learn/q/63aa909f-ffb4-462e-bdcc-018bc71d35d2 Case 2: same view with <form> in template <form id="sesion-form"> {% csrf_token %} <input id="session-d" value="{{ session }}" type="hidden"> </form> $(window).on('load', function() { console.log($('#session-id').val()) $('#question-box').load("{% url 'learn:question' course_learn.pk %}", $('#session-form').serializeArray(), function(){ runTimer(); }); }); This gives error Method Not Allowed (POST): /learn/q/63aa909f-ffb4-462e-bdcc-018bc71d35d2 Case 3: changed TemplateView to FormView and created a form in forms.py forms.py class SessionForm(forms.Form): session = forms.CharField() views.py class LearnQuestion(FormView): form_class = SessionForm template_name = 'learn/learn_question.html' ... ... But this gives error django.core.exceptions.ImproperlyConfigured: No URL to redirect to. Provide a success_url. But … -
Using an image in django/python
I want to add an image for every post and i already tried setting the static link <img src="{% static {{ post.img }}"> I also tried uploading the img by writing in the models.py image = models.ImageField(upload_to=.....) Any suggestions will be greatly apreciated -
Django Update all objects from file
Lets Suppose i have a model class SomeModel(models.Mode): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) age = models.IntegerField(default=10) also i have a settings file and declared a variable AGE_VALUE = 20 I'm wonder if it's possible whenever i change the value of AGE_VALUE all the age fields change to new value ?! tnx for your time -
What is the proper way to check an empty queryset in Django?
queryset = demo.objects.filter(name="non_existent_name") if queryset.exists(): serializer = DemoSerializer(queryset, many=True) return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND) With an empty queryset - I am expecting a 404, but instead get a 200 with an empty serialized Response. What is wrong with my code? Why does exists() not work as expected? -
UpdateView don't redirect to success_url defined in my class-based view
When I make a post in a update view this redirect to another url but not to that I want. I have an application called project. This is my project.urls.py: urlpatterns = [ ... path('edit/<int:pk>', ProjectUpdateView.as_view(), name='project_update'), path('detail/<int:pk>', ProjectDetailView.as_view(), name='project_detail'), ... ] And this is my views.py: class ProjectUpdateView(UpdateView): model = Project ... def get_success_url(self): return reverse_lazy('project_detail', kwargs={'pk': self.object.pk}) And my models.py: class Project(models.Model): name = models.CharField(max_length=100) ... def get_absolute_url(self): return reverse('project_detail', kwargs={'pk': self.pk}) how can i fix this? -
Choose one no empty of two field for __str__()
In my model I have two fields for the title, one for language. I want name the post with the title in the user language if there is, else in the other language. My model.py: class Post(models.Model): title_it = Model.CharField(_('title'), max_length=64, blank=True) title_en = Model.CharField(_('title'), max_length=64, blank=True) def __str__(self): name_traslated={'title_it': self.title_it, 'title_en': self.title_en} name_verbose=_('title_it') name=name_traslated[name_verbose] if name=='': name=name_traslated['title_it'] if name=='': name=name_traslated['title_en'] if name=='': name=ugettext('No Title') There is some faster way to do so?