Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to map a value to another in Django Rest
The class_name is a numeric field corresponding to the player's character class. I want to map those values to the character class name and display it in the serializer. class Character(models.Model): name = models.CharField(primary_key=True, max_length=10) level = models.IntegerField(blank=True, null=True) class_name= models.SmallIntegerField(blank=True, null=True) pk_count = models.IntegerField(blank=True, null=True) resets = models.SmallIntegerField(blank=True, null=True) class CharacterSerializer(serializers.ModelSerializer): class Meta: model = models.Character fields = ('name', 'level', 'class_name', 'pk_count', 'resets') Current Output { "name": "Player1", "level": 250, "class_name": 1, "pk_count": 200, "resets": 27 } Desired Output { "name": "Player1", "level": 250, "class_name": "Warrior", "pk_count": 200, "resets": 27 } Is it possible to map this values? Thanks everyone. -
Mezzanine Debug = False issue
In my mezzanine based django project I have Debug = False set within my settings.py file However, when visiting a url that does not exist my project still throws this error: You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Is there a second location where Debug needs to be set? -
Creating a YAML file in a certain format
I'm trying to create a YAML file in a certain format. A already tried the official Django forum. But in the meantime I have the feeling here are more people who could help :-) from django.db import models # Create your models here. # class NameManager(models.Manager): # def get_by_natural_key(self, name): # return self.get(name=name) class FactoryName(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Option(models.Model): name = models.CharField(max_length=100, unique=True) factory = models.ForeignKey(FactoryName, on_delete=models.CASCADE) def __str__(self): return self.name class AbstractOptionPackage(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField() options = models.ManyToManyField(Option) class Meta: abstract = True def __str__(self): return self.name class InteriorPackage(AbstractOptionPackage): def __str__(self): return self.name class ExteriorColor(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Export(models.Model): name = models.CharField(max_length=100, unique=True) exterior_colors = models.ManyToManyField(ExteriorColor) interior_package = models.ForeignKey(InteriorPackage, on_delete=models.CASCADE) def __str__(self): return self.name Now I would like to create a YAML file which looks roughly like this (it will be processed in other software, "# ..." are just comments here in this posting): Filename: {{Export.name}}.yaml # I think I already found "open(...)" example code also for serialization. {{Factory[0].name}}: # Name of first factory - {{ options[0] from any class derived from AbstractOptionPackage where Option.factory = Factory[0].name }} - {{ options[1] from any … -
How do I predict what the users input will be in an HTML form using Python and Django?
On my website I have a text input field where Rick Ross method equals post and I want to find out how I can predict or autocomplete the form as the user is typing so they may be able to select something that already exists. My method up to this point was to try and use JavaScript with an integration with Django and python code in the HTML form. It looked like the following. var all{ {% for i in items %} {{ i }}, {% endfor %} } With JavaScript. I'm sorry I don't have it handy right now. Is there an easy way to go about completing this text field or popping up suggestions while the user is typing? -
Could'nt import Django
I started my django project without activating my virtualenv django-admin startproject my_project and django-admin startapp my_app. Everythiing went fine, till i closed my terminal, and stopped the serveer. I wanted to restart my server, but this message is still coming up. i tried to install the virtualenv still the same problem, File "./manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Please what could be the problem and how to fix this ?? -
Angular not defined in production
I am having a weird issue where angular is undefined when application is deployed in AWS but locally there are no issues in my angular or javascript code. -
Blocked by CORS Policy - S3 Bucket Access from Django App
I am having an issue with my application accessing the font files in my S3 bucket. Here is my CORS Policy on the S3 bucket: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>HEAD</AllowedMethod> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <AllowedHeader>*</AllowedHeader> <ExposeHeader>ETag</ExposeHeader> </CORSRule> </CORSConfiguration> But in the console when accessing my website I am getting the following: has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource -
AttributeError: type object 'MyUser' has no attribute '_base_manager'
I have a project which is already running and I'm trying to allow spaces in usernames. I've created an abstract class MyUser according to this answer and set AUTH_USER_MODEL = 'dolava_app.MyUser' in settings.py. class MyUser(AbstractUser): validators=[ RegexValidator( r'^[\w.@+-\s]+$', _('Enter a valid username. This value may contain only ' 'letters, numbers, spaces ' 'and @/./+/-/_ characters.') ), ], class Meta: proxy = True # If no new field is added. Now it raises: File "/home/milano/dolava_venv/local/lib/python2.7/site-packages/django/db/models/base.py", line 154, in new new_class._base_manager = new_class._base_manager._copy_to_model(new_class) AttributeError: type object 'MyUser' has no attribute '_base_manager' So I tried to extend User instead of AbstractUser: TypeError: MyUser cannot proxy the swapped model 'dolava_app.MyUser'. Do you know how to make it work? -
Post comments via Ajax, Django
I want to give a user the possibility to "instant" comment on a Post (like you do here on SO in comments) without refreshing the Page. So I found this and this answer. They both suggest to use <input type="submit"... and call a ajax when the button is clicked. The problem is no matter what as soon as I click the button the page is reloading and the point of doing the whole thing is not to reload the page. Then I found this Solution it suggests to use <a onclick="AjaxFormSubmit()" >Submit</a>instead of the <input type="submit"... so I can live with that but I have no idea how to save the output. I have to validate the form somehow and need to get the input of the comment and the content_type and the ID of the Post the comment was made for. In the answer he just suggested to use return HttpResponse(json.dumps(your_data)) but how do I get the view to render the data? Im a bit confused with the view anyway. Some answers suggest to to the form validation inside the template view other wrote a view just for the ajaxCall. Currently im trying to combine the two answers somehow. … -
How to iterate a dict of dynamic “depths” in django template?
I have a json variable attached in the image for instance.This json may be dynamic dict of any depth.I want to render it in django template.Thanks. -
Pass along data when directing to a new template in Django
In one template, I collect a string called name. Once collected, I have a simple link sending you towards another page: <a href='/next/'> Continue </a> How can I send name along, so that the variable is availabe in /next/? -
How to get data from another table(model) in rest api html form using django rest api form?
Please view attached screenshot and below code sample, View.py class UniversityForAdminSerializer(serializers.ModelSerializer): organisation_type = serializers.ChoiceField( choices=[('university', 'University')]) #address = SearchLocationSerializer(many=True, queryset=Location.objects.all()) class Meta: model = Organisation fields = ('id', 'name', 'on_trial', 'logo', 'industry_type', 'organisation_type', 'description', 'website', 'email', 'contact_number', 'is_active', 'owner', 'address', 'max_tuition_fee','min_tuition_fee' ) Serlisers.py class AddUniversity(views.APIView): serializer_class = UniversityForAdminSerializer def post(self, request, *args, **kwargs): serializer = UniversityForAdminSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Location Serlisers.py class SearchLocationSerializer(serializers.ModelSerializer): """ """ id = serializers.ReadOnlyField(source='place_id') class Meta: fields = ('id', 'display_name') model = Location Organization.py (University) class Organisation(TenantMixin, S3FileFieldMixin): """ """ ORGANISATION_TYPE_CHOICES = ( ('company', 'Company'), ('university', 'University'), ) INDUSTRY_TYPE_CHOICES = ( ('ad_agency', 'Ad Agency'), ('aviation_mockups', 'Aviation Mockups'), ('camera_rental', 'Camera Rental'), ('car_truck_rental', 'Car & Truck Rental'), ('casting_agency', 'Casting Agency'), ('caterer', 'Caterer'), ('costume_makers_rentals', 'Costume Makers & Rentals'), ('craft_services', 'Craft Services'), ('digital_platform', 'Digital Platform'), ('equipment_rental_house', 'Equipment Rental House'), ('film_distributor', 'Film Distributor'), ('film_festival', 'Film Festival'), ('film_financier', 'Film Financier'), ('film_organization', 'Film Organization'), ('film_stock_hard_drives', 'Film Stock & Hard Drives'), ('film_fraternity', 'Film Fraternity'), ('motion_graphics', 'Motion Graphics'), ('green_screen_stages', 'Green Screen Stages'), ('grip_lighting_rentals', 'Grip & Lighting Rentals'), ('insurance', 'Insurance'), ('legal_counsel', 'Legal Counsel'), ('management_company', 'Management Company'), ('media_new_company', 'Media/New Company'), ('media_production_company', 'Media Production Company'), ('movie_studio', 'Movie Studio'), ('music_libraries_licensing', 'Music Libraries & Licensing'), ('music_production_sound_design', 'Music Production & Sound Design'), ('network', 'Network'), ('non_profit', … -
Django - How to extend the swagger with additional functionalities?
I am using Django with Swagger documentation. I wonder if there is any way to extend functionalities. At this moment I have just base schema in settings. I see only URLs. When I click Django Logout it doesn't work. Is there a possibility to add an option to send an example body in methods? For instance I have also optional searching like GET /users/{user_id}/object?sth=123 is it possible to include it in swagger documentation, too? I was looking in the documentation but there isn't much information. My settings at this moment look in this way: schema_view = get_swagger_view(title='PRI API') urlpatterns = [ url(r'^', schema_view), ] -
my creatview can't save, I'm using the GenericRelations to link the Post model to the users
I have been challenged by the createview, and its not saving the information. Hope someone can help me to fill in the missing pieces or direct me on how to solve it, thanks Views.py class UserPostCreatView(CreateView): form_class = PostModelForm queryset = authomodel.User.objects.all() template_name = 'posts/post_form.html' def form_valid(self,form): user_slug = self.kwargs.get('user_slug') auth_user = get_object_or_404(authomodel.User, user_slug=user_slug) form.instance.auth_user = auth_user return super(UserPostCreatView, self).form_valid(form) posts/models class Post(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') image = models.ImageField(upload_to=imageupload_location, width_field='max_width', height_field='max_height', null=True, blank=True) max_width = models.CharField(max_length=100, null=True, blank=True) max_height = models.CharField(max_length=100, null=True, blank=True) content = models.TextField() timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) user/models.py user_slug = models.SlugField(unique=True, null=True, blank=True) my_user = GenericRelation(Post, object_id_field="object_id", related_query_name="User") -
What will be the alternative for `forms.RadioSelect.renderer` in new version of Django?
I copied this code from another old project. On latest version of django it is not working. The code: class HorizontalRadioRenderer(forms.RadioSelect.renderer): def render(self): return mark_safe( u'\n'.join([u'%s\n' % w for w in self]) ) This gives following error: AttributeError: type object 'RadioSelect' has no attribute 'renderer' -
How i can upload an image with CreateView on my post?
I have had some problems, I can upload text like the field 'text' and the field 'video' in which I place a URLField, the problem is that from the administration panel I can upload the image without any problem. But at the time of doing it by CreateView from a view I am not possible. I was told to add the tag (enctype = "multipart / form-data") to the form and it works, but instead of uploading it to /media/posts/image.jpg it attempts to upload it to (/ media / image .jpg) and the end of it all is that it does not upload the image. I really just want to upload the images to my posts as you can see here https://plxapp.herokuapp.com/ and later do so with the avatar and the header of the UserProfile. If they have any procedure or validation that should be done, they can tell me here. I leave my code: Template: <form action="" enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="form-group"> <label for="{{ form.subject.id_text }}">Text</label> {{ form.text }} </div> <div class="form-group"> <label for="{{ form.subject.id_image }}">Image</label> {{ form.image }} </div> <div class="form-group"> <label for="{{ form.subject.video }}">Video</label> {{ form.video }} </div> <button type="submit" class="btn btn-success">Publish <span class="glyphicon glyphicon-edit" … -
Django didn't return an HttpResponse object error?
ValueError at /blog/1/comment/new/ The view blog.views.comment_new didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://localhost:8000/blog/1/comment/new/ why is request method get? HTML <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" /> </form> VIEWS @login_required def comment_new(request, post_pk): post = get_object_or_404(Post, pk=post_pk) if request.method == 'post': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user comment.save() return redirect('blog:post_detail', post.pk) else: form = CommentForm() return render(request, 'blog/comment_form.html', { 'form': form, })` thanks -
Django. delete() don't work: Models aren't loaded yet
I want to delete several existing records from the database. Using Django administration it is easy to make it. But if I use the method delete()- I fail. But if just get object - success. models.py from django.db import models class Specification(models.Model): main_type = models.CharField(max_length=20, blank=True, null=True, default=None) number = models.CharField(max_length=20, blank=True, null=True, default=None) name = models.CharField(max_length=100, blank=True, null=True, default=None) def __str__(self): return "%s %s" % (self.number, self.name) class Meta: verbose_name = 'Спецификация' verbose_name_plural = 'Спецификации' class Component(models.Model): main_type = models.CharField(max_length=20, blank=True, null=True, default=None) number = models.CharField(max_length=20, blank=True, null=True, default=None) name = models.CharField(max_length=100, blank=True, null=True, default=None) def __str__(self): return "%s %s" % (self.number, self.name) class Meta: verbose_name = 'Компонент' verbose_name_plural = 'Компоненты' class Relation(models.Model): specification = models.ForeignKey(Specification) component = models.ForeignKey(Component) quantity = models.CharField(max_length=10, blank=True, null=True, default=None) notice = models.CharField(max_length=250, blank=True, null=True, default=None) def __str__(self): return "Позиция %s в %s" % (self.component.number, self.specification.number) class Meta: verbose_name = 'Входимость' verbose_name_plural = 'Входимости' union = Relation.objects.get(pk=1000) #for example union.delete() Error traceback C:\Projects\14.07\sui_0107>python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\core\management\__init__.py", line 337, in execute django.setup() File "C:\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\apps\registry.py", line 108, in populate … -
Request header field Cache-Control is not allowed by Access-Control-Allow-Headers in preflight response
I use react/express with django as backend.I am trying to integrate s3 fine uploader and i am getting this issue :Request header field Cache-Control is not allowed by Access-Control-Allow-Headers in preflight response. when i try to make a post request. Normally i make all my request in code using fetch but here i make use of the package https://github.com/FineUploader/react-fine-uploader and it make use of xhr ? any one ran into this issue Synopsis ERROR: Request header field Cache-Control is not allowed by Access-Control-Allow-Headers in preflight response. Frontend:React/express/webpack Backend:Dajngo Environment:Local (django server,react local api) cause: xhr? -
How to retrieve data from extended user model
I am trying to make a simple signup/login page through django. I have used UserCreationForm and used a model UserProfile to extend the user model. I want to retrieve the data posted from form i.e department at my home page after user logged in. I am new to django so brief explanation would be appreciated. Thanks in advance forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from mysite.core.models import UserProfile from django.db import models class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') department = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email','password1', 'password2', 'department',) def save(self, commit=True): # Save the provided password in hashed format user = super(SignUpForm, self).save(commit=False) user_profile = UserProfile(user=user, department=self.cleaned_data['department']) user.save() user_profile.save() return user, user_profile views.py from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from mysite.core.forms import SignUpForm @login_required def home(request): return render(request, 'home.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user,user_profile = form.save(commit=False) username = user.cleaned_data.get('username') raw_password = user.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', … -
Errors installing requirements for django cookiecutter template
I'm learning how to use cookiecutter templates for my django project but after I generated a boilerplate project then run the command $ pip install -r requirements/local.txt within a virtualenvironment, I'm getting errors. building '_regex' extension creating build/temp.linux-x86_64-3.5 creating build/temp.linux-x86_64-3.5/Python3 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict- prototypes -g -fstack-protector-strong -Wformat -Werror=format- security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC - I/usr/include/python3.5m -I/home/rayrenz/Envs/env2/include/python3.5m -c Python3/_regex.c -o build/temp.linux-x86_64-3.5/Python3/_regex.o Python3/_regex.c:46:20: fatal error: Python.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for regex Running setup.py clean for regex Failed to build regex Installing collected packages: django, six, django-environ, whitenoise, django-braces, django-crispy-forms, django-model-utils, olefile, Pillow, pycparser, cffi, argon2-cffi, defusedxml, python3- openid, urllib3, idna, chardet, certifi, requests, oauthlib, requests- oauthlib, django-allauth, psycopg2, Unidecode, regex, awesome-slugify, pytz, redis, django-redis, coverage, django-coverage-plugin, snowballstemmer, imagesize, alabaster, sphinxcontrib-websupport, babel, Pygments, docutils, MarkupSafe, Jinja2, Sphinx, django- extensions, Werkzeug, django-test-plus, python-dateutil, Faker, factory-boy, sqlparse, django-debug-toolbar, ipython-genutils, decorator, traitlets, wcwidth, prompt-toolkit, simplegeneric, jedi, pickleshare, ptyprocess, pexpect, ipython, ipdb, py, pytest, pytest- django, termcolor, pytest-sugar Running setup.py install for regex ... error Complete output from command /home/rayrenz/Envs/env2/bin/python3.5 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build- hmmrfoqr/regex/setup.py';f=getattr(tokenize, 'open', open) (__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install -- record /tmp/pip-jg06yrb9-record/install-record.txt --single-version- … -
uploading file in unique directory using django
I have uploaded file using Django form in unique directory.Now i want that as soon as file is uploaded 4 files (Randomforest.R,decisiontree.R,svm.R,linearModel.R) should also get uploaded in the same unique directory.These 4 files are stored at Desktop in my computer. How can i achieve this? Here is model.py and views.py views.py -
Django Admin Panel Hide Field
I wanna hide 'yazar' field but at the same time, I wanna current author. I did these; admin.py class PageAdmin(admin.ModelAdmin): def get_form(self, request, *args, **kwargs): form = super(PageAdmin, self).get_form(request, *args, **kwargs) form.base_fields['yazar'].initial = request.user return form models.py class Makale(models.Model): baslik = models.CharField(max_length=200) yazi = models.TextField() tarih = models.DateTimeField(default=timezone.now) kategori = models.ForeignKey('Blog.Kategori') #resim = models.ImageField(upload_to = 'makale_image/', default = '') yazar = models.ForeignKey(User) what should I do for this ? Thanx. -
Django server not sending logs to logstash
i am using ELK stack for centralised logging from my django server. My ELK stack is on a remote server and logstash.conf looks like this input { tcp { port => 5959 codec => json } } output { elasticsearch { hosts => ["xx.xx.xx.xx:9200"] } } both services elasticsearch and logstash are working (checked using docker-compose logs logstash). my django server's settings file have logging conf like below LOGGING = { 'version': 1, 'handlers': { 'logstash': { 'level': 'INFO', 'class': 'logstash.TCPLogstashHandler', 'host': 'xx.xx.xx.xx', 'port': 5959, # Default value: 5959 'version': 0, # Version of logstash event schema. Default value: 0 (for backward compatibility of the library) 'message_type': 'django', # 'type' field in logstash message. Default value: 'logstash'. 'fqdn': True, # Fully qualified domain name. Default value: false. 'tags': ['django.request'], # list of tags. Default: None. }, }, 'loggers': { 'django.request': { 'handlers': ['logstash'], 'level': 'DEBUG', }, } } I run my django server and logstash handler handles the logs as console shows no logs.I used python-logstash library in django server to construct above conf but logs are not sent to my remote server I checked through many question, verified that services are running are ports are correct but no clue … -
How to properly pass JSON in django
I'm writing tests for views in my django app. The view accepts POST request. It should be JSON data. I've already tested it with Postman, but when i try to pass it in tests.py in doesn't work and says JSON must be enclosed in double quotes. The thing is it is in double quotes. What am i doing wrong? Check the code below. Thanks! views.py """This registration app-module generates views for register and auth pages.""" from json import loads from django.http import HttpResponse from django.contrib import auth from django.core.exceptions import ValidationError from django.core.validators import validate_email from .models import CustomUser def register(request): """ Registration method for CustomUser registration. Args: request: http request. Returns: If new user gets successfully registered - returns HttpResponse(201). If not - returns HttpResponse(400). """ if request.method == 'POST': data = loads(request.body.decode('utf-8')) email = data["email"] password = data["password"] if CustomUser.get_by_email(email) is None: try: validate_email(email) CustomUser.create(email, password) return HttpResponse("User successfully created.", status=201) except ValidationError: return HttpResponse("This email is not valid format.", status=400) return HttpResponse("This email is already registered.", status=400) return HttpResponse(status=400) tests.py from django.test import TestCase from django.urls import reverse from registration.models import CustomUser class RegisterViewTests(TestCase): """ Test CustomUser model methods. """ def test_create(self): """ Test CustomUser.create(). """ response …