Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Failed to load resource: Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin
I have a Vue.js frontend project, which start at the 8080 port. I access the site by: http://localhost:8080/register and I use the Python/Django write the backend site. using Django-Rest-Framework provide the APIs. My backend APIs server is start as: http://0.0.0.0:8001/ But when I register( access the api ), I get bellow Access-Control-Allow-Origin error: Failed to load resource: Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin. In my Python backend project settings.py code are: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '8cyiv%(rkpv33s_(n8x_5&+6-9&s!ddc!0)98la3=9(y8=k$4u' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_docs', # API docs 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', 'wx_numbers', 'users_management', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # corsheaders 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'http://localhost:8080', 'http://localhost:8081', 'http://localhost', 'http://localhost:8888', ) ROOT_URLCONF = 'wx_backup.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', ], }, }, ] WSGI_APPLICATION = 'wx_backup.wsgi.application' AUTH_USER_MODEL = … -
how to impliment Haystacksearch fetched autocomplete
I want implement fetching in autocomplete, here is my autocomplete function def autocomplete(request): fetch_field = request.GET.get('fetch_field') sqs = SearchQuerySet().autocomplete( content_auto=request.GET.get( 'query', ''))[ :5] s = [] for result in sqs: d = {"value": result.title, "data": result.object.slug} s.append(d) output = {'suggestions': s} print('hihi' ,output) return JsonResponse(output) Now I can get fetch fields but I don't know how to fetch with SearchQuerySet. -
Bootstrap-table How to make height adjust to shown data
I am using bootstrap-table to create my table, and it functions perfectly, but it looks a bit strange because the height seems to just be fixed, regardless of how much data is in it. So if I only have 6 records, there is just this awkward empty space underneath. Here is my html: <table class="table" data-toggle="table" data-page-size="10" data-pagination="true" data-search="true"> <thead> <tr> <th data-sortable="true">Username</th> <th data-sortable="true">Full Name</th> <th data-sortable="true">Points</th> {% for subject in subjects %} <th data-sortable="true">{{ subject }}</th> {% endfor %} </tr> </thead> <tbody> {% for user in users %} <tr> <td> <a href="{% url 'profile' username=user.username %}">{{ user.username }}</a> </td> <td>{{ user.first_name }} {{ user.last_name }}</td> {% for item in user.profile.points %} <td>{{ item.1 }}</td> {% endfor %} </tr> {% endfor %} </tbody> And here is a screenshot of my page: Any ideas on how to fix this? -
Hashes of static files collected with CachedFilesMixin as STATICFILES_STORAGE don't match between the collecstatic phase and the serve phase?
I'm trying to setup static file versioning in my django app that uses django-pipeline as a compressor. The documentation says that django-pipeline doesn't directly support versioning because django-storages supports cache-busting natively. So I simply did the following: STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' However, when I do collectstatic, my files are generated with a certain hash, e.g. /media/static/css/mycss.12345678.css, and when I subsequently serve my files, I get a different hash, e.g. /media/static/css/mycss.87654321.css. And that results in a 404. What might I be missing? -
How to use AWS Cognito in Django Application
How to replace Django Authentication with AWS Cognito. And also how to sync my Django users with AWS. Thanks in advance. -
Display User Profile getting ERROR: 'AnonymousUser' object has no attribute '_meta'
I have a simple view that is suppose to check if there is post data, if so update the user data using UserChangeForm. Else get the form data of user and display. Issue: AttributeError at /profile/edit 'AnonymousUser' object has no attribute '_meta' I think it might be this line in the edit_profile view # Handles the get request - if no post info is submitted then get the form and display it on the edit profile page. else: form = UserChangeForm(instance=request.user) args = {'form': form} return render(request, 'accounts/profile_edit.html', args) Not sure what. Here is the view.py edit_profile def edit_profile(request): # Handle post request - if the user submits a form change form details and pass the intance user if request.method == 'POST': form = UserChangeForm(request.POST, intance=request.user) if form.is_valid(): form.save() return redirect('accounts/profile') # Handles the get request - if no post info is submitted then get the form and display it on the edit profile page. else: form = UserChangeForm(instance=request.user) args = {'form': form} return render(request, 'accounts/profile_edit.html', args) profile_edit.html {% extends 'base.html' %} {% block head %} <title>Profile</title> {% endblock %} {% block body %} <div class="container"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save Changes</button> </form> </div> {% … -
How to style registration form in django using bootstrap
So I have set up a user registration portal for my website. It is in form of plain HTML text. I have downloaded a bootstrap file for registration portal but it simply does not work. from django import forms class UserRegistrationForm(forms.Form): username = forms.CharField( required=True, max_length=30, label='User Name', ) name = forms.CharField( required=True, max_length=30, label='Full Name', ) last = forms.CharField( required=True, max_length=30, label='Last Name', ), email = forms.CharField( required=True, max_length=30, label='Email', ) password = forms.CharField( required=True, max_length=30, label='Password', widget=forms.PasswordInput(), ) Below is my bootstrap. Can you tell me the error here. It simply does not work <body> <form method="POST" class = "signup"> {% csrf_token %} {{ form.as_p }} <div class="loginBox"> <img src="user.png" class="user"> <h2>Resgister Here</h2> <p>Email</p> <input type="text" name="email" placeholder=""> {{ form.email }} <p>Username</p> <input type="text" name="username" placeholder=""> {{ form.username }} <p>Name</p> <input type="text" name="name" placeholder=""> {{ form.name }} <p>Password</p> <input type="password" name="password" placeholder="••••••"> {{ form.password }} <input type="submit" name="" value="register"> </div> </form> </body> </html> -
Application's pages should not get open on pasting the url in a different browser in django
I have faced an issue like applcation pages should not get open on pasting the url in a different browser in django -
What is the best way to test drf serializer validate
I think two way how can i test drf serializer validate following is my serializer validate code def validate_md5(self, md5): if len(md5) != 40: raise serializers.ValidationError("Wrong md5") return md5 and it is test code 1) def test_wrong_validate_md5_2(self): url = reverse('apk-list') response = self.client.post(url, {'md5':'test'}, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) 2) def test_wrong_validate_md5(self): serializer = ApkSerializer(data=self.apk) if len(self.apk.get('md5')) != 40: self.assertEqual(serializer.is_valid(), False) else: self.assertEqual(serializer.is_valid(), True) what is better than another? or is there best solution? and ... I practice test-driven coding. is it necessary to write test code as above -
django / vue - receive and open dynamically generated PDF
I've been trying most of the related solutions that were posted here in SO, but none of them worked for me basically because as stated here, new versions of Chrome, Firefox, etc, don't accept loading data from URLs in the top frame anymore, meaning that it's no longer possible to open a pdf using window.open('data:application/pdf;base64,' + response.body) or similar approachs. The system I'm developing sends post requests from a Vue 2 front end (using Vue Resource to a Django backend that dynamically generates and returns the requested PDF. When testing the backend using postman, everything works fine; after sending the request the pdf is automatically downloaded. This is how the postman request looks like: This is part of the backend: pdf = generate_pdf(pdf_type, customer_id) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename='test.pdf' return response However, when I make the post request from Vue, which looks like this (symplified): return Vue.http.post(url, request) .then((response) => { var fileURL = URL.createObjectURL(response.data) window.open(fileURL) }) The displayed PDF is blank. Inspecting the response.data, the pdf string is exactly the same as postman gets. Any idea on how to download / open in a new tab this response? -
certbot nginx doesn't finish
question regarding letsencrypt.org certbot. Whenever I run the certbot --nginx command, it never finishes the process. Full output (running as root): $ certbot --nginx --agree-tos --redirect --uir --hsts --staple-ocsp --must-staple -d <DOMAINS> --email <EMAIL> Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator nginx, Installer nginx Starting new HTTPS connection (1): acme-v01.api.letsencrypt.org Obtaining a new certificate Performing the following challenges: http-01 challenge for <DOMAIN> http-01 challenge for <DOMAIN> nginx: [emerg] duplicate listen options for [::]:80 in /etc/nginx/sites-enabled/django:50 Cleaning up challenges nginx restart failed: b'' b'' Running certbot certificates: $ certbot certificates Saving debug log to /var/log/letsencrypt/letsencrypt.log ------------------------------------------------------------------------------- No certs found. ------------------------------------------------------------------------------- The only thing where I messed up was not properly configuring my DNS before running certbot the first time (messed up my A record, et al; I'm new at this :P), however I don't know what to do moving forward; this is my first web-server so I'm still in a bit of a learning curve. I'm not sure if this is a configuration error, or something else. For info, I'm running a DigitalOcean Django/Ubuntu 16.04 droplet (only edited /etc/nginx/sites-available/default, to change server_name). Will update below for any additional info needed; thanks in advance. ^_^ -
In Django, is a superuser also a mendatory active member or not?
In Django, a superuser is also a mendatory active member or not ? -
How can I submit and save all forms with one button
I am new to django and still learning so forgive me if I did everything completely wrong. I am trying to make a single page with multiple forms on it all submitted with one button and I successfully did do that but I am now trying to make it more dynamic by adding an "add more" button but when I did the form no longer submitted all of the formsets it only submits one formset how do I make it so I can add as many forms as i want and it will still save them? Do I need to use a queryset like update queryset or something? Any help or guidance would be greatly appreciated. Views.py class ScanCreateView(CreateView, LoginRequiredMixin): template_name = 'scanset.html' model = Scan_Info form_class = ScanForms success_url = 'success/' def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) Scan_form = ScanInlineFormSet() PostScan_form = PostScanFormSet() return self.render_to_response( self.get_context_data(form=form, Scan_form=Scan_form, PostScan_form=PostScan_form)) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) Scan_form = ScanInlineFormSet(self.request.POST) PostScan_form = PostScanFormSet(self.request.POST) if (form.is_valid() and Scan_form.is_valid() and PostScan_form.is_valid()): return self.form_valid(form, Scan_form, PostScan_form) else: return self.form_invalid(form, Scan_form, PostScan_form) def form_valid(self, form, Scan_form, PostScan_form): self.object = form.save() … -
How to combine few mutations in the if\else logic in order to get 'GetOrCreateUser'?
I use VueJS and Django + django-graphql-jwt (which returns tokens). I want to use email\password fields for registration and for login. On a server I want to check if provided email already exists -> use django-graphql-jwt's mutation token_auth = graphql_jwt.ObtainJSONWebToken.Field() to return token, else -> create a new user with provided email and password and return a text like "User is Created" in order to inform VueJS that this is a new user. For now I have: # schema.py import graphene import graphql_jwt from django.contrib.auth import get_user_model from graphene_django import DjangoObjectType class UserType(DjangoObjectType): class Meta: model = get_user_model() class CreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: password = graphene.String(required=True) email = graphene.String(required=True) def mutate(self, info, password, email): user = get_user_model()( username=email.split('@')[0], email=email, ) user.set_password(password) user.save() return CreateUser(user=user) # Want to combine two mutations here class GetOrCreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: password = graphene.String(required=True) email = graphene.String(required=True) def mutate(self, info, password, email): # Return token if get_user_model().objects.filter(email=email).exists(): return {'token': graphql_jwt.ObtainJSONWebToken.Field(), 'msg': 'Token Generated'} # Create new user else: CreateUser(???) return {'token': '', 'msg': 'User is Created'} class Mutation(graphene.ObjectType): create_user = CreateUser.Field() get_or_create_user = GetOrCreateUser.Field() I tried different variants, but it seems I do not understand fully graph's workflow or\and what magic … -
Using instance data in signal handler django
Can I user model instance data in signal handler to create different profile models as per user type? I tried it but its not working and only one kind of profile is being created the Student profile even if the user_type is institute. In models.py class User(AbstractUser): type_choices = ( ('Student', 'Student'), ('Institute', 'Institute') ) user_type = models.CharField(max_length=2,choices=type_choices,default='Student') class Profile(models.Model): bio = models.CharField(max_length = 200, null = True, blank = True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) image = models.ImageField(upload_to=user_image_path, blank=True) class Iprofile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_incorporation = models.DateField(null=True, blank=True) logo = models.ImageField(upload_to=user_image_path, blank=True) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def update_user_profile(sender, instance, created, **kwargs): if created: if instance.user_type == "Student": Profile.objects.create(user=instance) instance.profile.save() elif instance.user_type =="Institute": Iprofile.objects.create(user=instance) instance.iprofile.save() @receiver(post_save, sender=settings.AUTH_USER_MODEL) def save_user_profile(sender, instance, **kwargs): if instance.user_type == "Student": instance.profile.save() elif instance.user_type == "Institute": instance.iprofile.save() In forms.py user_type_choices = ( ('Student', 'Student'), ('Institute', 'Institute'), ) class SignUpForm(forms.Form): user_type = forms.ChoiceField(choices = user_type_choices) def signup(self, request, user): user.user_type = self.cleaned_data['user_type'] user.save() -
TypeError: a bytes-like object is required, not 'str' when using urlparse
I'm getting this error on my model function. Here's my model: def Post(models.Model): ... imageURL = models.URLField(null=True, blank=True) @property def video_source(self): print(self.imageURL) #https://www.youtube.com/watch?v=abcdefghi t = urlparse(self.imageURL).netloc #this line fires the error domain = '.'.join(t.split('.')[1:]) print(domain) return True I'm trying to create a function for my template like so: {% if instance.imageURL.video_source %} #something {% else %} #something else {% endif %} any idea what the problem is? -
parsed_pattern.pattern.groups = 1 AttributeError: can't set attribute
Here is my code def convert_regexp_to_noncapturing_parsed(parsed_pattern): res_data = [] for key, value in parsed_pattern.data: if key == sre_constants.SUBPATTERN: index, subpattern = value value = (None, convert_regexp_to_noncapturing_parsed(subpattern)) elif key == sre_constants.GROUPREF: raise ValueError('Regular expressions with back-references are not supported: {0}'.format(pattern)) res_data.append((key, value)) parsed_pattern.data = res_data parsed_pattern.pattern.groups = 1 parsed_pattern.pattern.groupdict = {} return parsed_pattern here in line parsed_pattern.groups = 1 i'm getting a error AttributeError: can't set attribute I dont know whats wrong -
"detail": "Method \"GET\" not allowed. on calling endpoint in django
I'm using django.rest_framework. I have a get_or_create method for a particular view, class LocationView(views.APIView): def get_or_create(self, request): try: location = Location.objects.get(country=request.data.get("country"), city=request.data.get("city")) Response(location, status=status.HTTP_200_OK) except Location.DoesNotExist: serializer = LocationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is the location Model, class Location(models.Model): country = models.CharField(max_length=255) city = models.CharField(max_length=255, unique=True) latitude = models.CharField(max_length=255) longitude = models.CharField(max_length=255) class Meta: unique_together = ('country', 'city') This is my url, url(r'^location/$', LocationView.as_view(), name='location'), When I call this endpoint in the following way, http://127.0.0.1:8000/api/v1/bouncer/location/?country=USA&&city=Sunnyvale&&latitude=122.0363&&longitude=37.3688 This is what I get, { "detail": "Method \"GET\" not allowed." } What am I missing here. -
Adding a variable into a a path in django
I am making my first website in Django but my tutorial was created long ago. I need to add the variable question_id into the following path: path('<question_id [0-9]>/',views.detail, name = "detail") the function detail looks like this: def detail(request, question_id): return HttpResponse('Leo is the best') This is what the error looks like: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ [name='index'] polls/ <question_id = [0-9]>/ [name='detail'] polls/ <question_id>[0-9]/result [name='result'] polls/ <question_id>[0-9]/vote [name='vote'] -
ValueError at /adm/appt/ Expected table or queryset, not str
Getting the following error when trying to use django_tables2 ValueError at /adm/appt/ Expected table or queryset, not str I have run all the updates and upgrades on the packages Error Request Method: GET Request URL: http://127.0.0.1:8000/adm/appt/ Django Version: 2.0.3 Exception Type: ValueError Exception Value: Expected table or queryset, not str Exception Location: C:\ProgramData\Anaconda3\lib\site-packages\django_tables2\templatetags\django_tables2.py in render, line 147 Python Executable: C:\ProgramData\Anaconda3\python.exe Python Version: 3.6.3 View: Think i'm initializing the table properly as well as sending the queryset def ApptView(request): table = AppointmentTable(Appointment.objects.all()) model = Appointment table_class = AppointmentTable filterset_class = AppointmentFilter RequestConfig(request).configure(table) return render(request,'adm/index2.html', {'table': table}) HTML {% load render_table from django_tables2 %} <body> {% render_table AppointmentTable %} </div> </body> Tables import django_tables2 as tables from .models import Appointment class AppointmentTable(tables.Table): class Meta: model = Appointment template_name = 'django_tables2/bootstrap.html' -
Get model name from instance
How can I get a model name as a "string" from a model instance. I know you can do something like type(model_instance) but this is returning the class itself as an object <Model_Name: > not as a string. -
Filter records from parent table to appear in the "Add new" page as a select list
Let's say I have two tables: customer and city. I have customer.city_id field as a foreign key that references city.id. class Customer(model.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) city_id = models.ForeignKey(City, models.DO_NOTHING, db_column='id' class Meta: managed = False db_table = 'customer' def __str__(self): return self.name class City(model.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=32) added = models.PositiveIntegerField() # value is 1 or 0 class Meta: managed = False db_table = 'city' def __str__(self): return self.name When I add a new customer, I can pull all the records (city names) and display them in the add new customer page. How can I get only the cities that their city.added value = 1 and ignore those with value 0, Preferably in the models.py file or in the admin.py file. -
How to get the slug STRING value in django models?
Basically, I have 3 classes (Vehicle, Car and Motorcycle, these 2 last extend the first one)... In the Vehicle class there's the main_image attribute which is a models.ImageField type, as you can see bellow: class Vehicle(models.Model): def __str__(self): return self.title [...] main_image = models.ImageField( upload_to = 'media/images/' + str(slug) + '/', verbose_name = 'Foto principal', null = False ) So, the str(slug) doesn't work properly, 'cause when I upload an image, it is always uploaded to /media/images/<django.db.models.fields.SlugField> when it should actually upload to /media/images/(object-slug-value)/ I've tried many different things but any of them worked the way I wanted. How can I get the string value from the slug attribute? -
Django on GAE - How to automatically 'migrate' on deploy?
Django v1.11 Postgresql v9.6 Currently, I use 2 Google CloudSQL databases, one for development and one for production. Whenever I make changes to my models, I run python manage.py migrate to update the tables in the development database. This migration does not affect the production database, however. Now, whenever I git push changes to my Django project, TravisCI automatically runs tests and deploys the code to Google App Engine. Currently, it runs on GAE flexible environment (so I can use Python 3.5) What I want to have is for Travis or GAE to automatically run python manage.py migrate on the production database before runserver. However, I can't figure out how to run custom commands during a deploy. I've tried looking around GAE and Travis documentation and adding scripts to .travis.yml and app.yaml, but to no avail. As of now, anytime there is a model change, I have to migrate the production database locally in a very hacky way. Ideally, GAE will migrate at the beginning of every deploy. -
Django 2, Celery 4.1 ModuleNotFoundError: No module named djcelery
I am running into a ModuleNotFound error using Django and Celery. I have a post endpoint using django rest framework that runs a celery task to parse and store json. I can serve pages fine, but when I do a post I get the following error: Exception Type: ModuleNotFoundError at /app/v1/results Exception Value: No module named 'djcelery' At first I thought that maybe I had a versioning issue, so I checked my packages, but I'm on the latest and don't see any outstanding conflicts. I do see the djcelery is reference in the loaders init.py of the celery projects: https://github.com/celery/celery/blob/master/celery/loaders/init.py amqp (2.2.2) billiard (3.5.0.3) celery (4.1.0) certifi (2018.1.18) Django (2.0.3) django-celery-results (1.0.1) django-filter (1.1.0) django-pyodbc-azure (2.0.3.0) djangorestframework (3.7.7) kombu (4.1.0) Markdown (2.6.11) mod-wsgi (4.6.2) pip (9.0.1) pyodbc (4.0.22) pytz (2018.3) setuptools (38.5.1) vine (1.1.4) wheel (0.30.0) My project follows the core of the Django first steps http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#django-first-steps: Proj - proj - __init__.py - celeryapp.py - settings.py - urls.py - app - models.py - tasks.py - views.py - urls.py - manage.py For all of my code I started with what was in the first steps tutorial, but have made a few changes running into issues and finding post as well as …