Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django Elasticbeanstalk Application returns 404 during autoscale
I have a django application running on elastic beanstalk. The application deploys and works fine when I deploy from the command line. However, during an autoscale, healthcheck on the new instance created always return 404 from the access_logs. "GET /health/ HTTP/1.1" 404 221 "-" "ELB-HealthChecker/1.0" Interestingly, the application eventually loads after about 20 minutes. See my wsgi.conf file below. Is there something I am doing wrong? LoadModule wsgi_module modules/mod_wsgi.so WSGIPythonHome /opt/python/run/baselinenv WSGISocketPrefix run/wsgi WSGIRestrictEmbedded On <VirtualHost *:80> Alias /static/ /opt/python/current/app/staticfiles/ <Directory /opt/python/current/app/staticfiles/> Require all granted </Directory> WSGIScriptAlias / /opt/python/current/app/myapp/wsgi.py <Directory /opt/python/current/app/> Require all granted </Directory> Header always set Access-Control-Allow-Methods "POST,GET,OPTIONS,PUT,DELETE, PATCH" Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, Accept, origin, authorization, accept, client-security-token, Authorization" WSGIDaemonProcess wsgi processes=3 threads=20 display-name=%{GROUP} \ python-path=/opt/python/current/app:/opt/python/run/venv/lib/python2.7/site-packages:/opt/python/run/venv/lib64/python2.7/site-packages user=wsgi group=wsgi \ home=/opt/python/current/app WSGIProcessGroup wsgi RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule !/api/v1.0/church/health/ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301] </VirtualHost> WSGIPassAuthorization On -
Django app deployed to Digitalocean 502 Bad Gateway
I have copyed my django app (that works locally) to a droplet from Digitalocean where I have installed the django 1-click app. I get 502 Bad Gateway and can't manage to understand why. 2018/03/13 22:25:06 [error] 2104#2104: *44 upstream prematurely closed connection while reading response header from upstream, client: 139.162.251.201, server: _, request: "GET / HTTP/1.0", upstream: "http://unix:/home/django/gunicorn.socket:/" 2018/03/13 22:28:19 [error] 2104#2104: *46 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "46.101.7.245" 2018/03/13 22:31:51 [error] 2104#2104: *49 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "46.101.7.245" 2018/03/13 22:32:05 [error] 2104#2104: *52 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 93.55.242.118, server: _, request: "GET /admin HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/admin", host: "46.101.7.245" 2018/03/13 22:40:18 [error] 2104#2104: *55 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET /admin HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/admin", host: "46.101.7.245" 2018/03/13 22:40:23 [error] 2104#2104: *55 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET … -
Django - call view method when including template
Is it possible in Django to have a view method associated to template, so when I {% include %} a child template in my parent template, the child template can call it's view method and get some data? Or the only way is to have a single view method associated to url that collects data for every template? -
Spaces in url query not getting decoded in django
I have the following URL query - http://localhost:8000/api/passenger-census/?public_location_description==SW%206th%20&%20Salmon however, the spaces are not being decoded and the resulting query that django parses is GET /api/passenger-census/?public_location_description=SW%206th%20&%20Salmon which returns a null since the string to be found is "SW 6th & Salmon". Django code views.py - class PassengerCensusViewSet(viewsets.ModelViewSet): queryset = PassengerCensus.objects.all() serializer_class = PassengerCensusSerializer filter_backends = (SearchFilter,DjangoFilterBackend,OrderingFilter,) search_fields = ('route_number', 'direction','service_key','stop_seq', 'location_id','public_location_description',) filter_fields = ('summary_begin_date','route_number','direction','service_key','stop_seq','location_id', 'public_location_description','ons','offs','x_coord','y_coord','geom_2913','geom_4326',) ordering_fields = '__all__' serializer.py class PassengerCensusSerializer(serializers.ModelSerializer): class Meta: model = PassengerCensus fields = '__all__' What is the issue here? -
Django 2.0 ipn callback => Forbidden (CSRF cookie not set) despite @csrf_exempt
I use Django 2.0 and I want to accept an IPN from a remote third-party on my url http://example.com/ipn/ This is my url: urlpatterns = [ ... # url for ipn url(r'^ipn/$', views.index, name='ipn'), ... ] This is my view: # decorator from django.views.decorators.csrf import csrf_exempt @csrf_exempt def ipn(request): ''' process ipn call from merchant''' ipn = get_data_from_ipn(request) in my settings.py: ALLOWED_HOSTS = ['ipnsender.net'] ... I'd like that only the ipn view does not use csrf, but I can not understand why I do have the following error although the documentation only tells you need @csrf_exempt decorator. My log tells me every time: Forbidden (CSRF cookie not set.): /ipn/ [13/Mar/2018 22:36:50] "POST /ipn/ HTTP/1.1" 403 2868 -
Django Admin looks ugly - Impossible to load any static files
I'm working on a Django REST project and I used to send my code on Git server. Every css and static files was working fine. Now that I've fetch the project on a new pc, it's now impossible to load any css or js files either on the admin page or the home page. Whenever I load the Django admin page, I get this kind of error in the console: GET http://localhost:8080/static/admin/css/base.css net::ERR_ABORTED And the css doesn't load I also got a similar error when I load the home page: GET http://localhost:8080/static/css/main.css net::ERR_ABORTED I run my project on ubuntu 16.0.4 in a virtualenv (using vagrant) and I use Django 3.5. Here is my directory tree And here is a sample of my settings/base.py file : STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join('./', 'static'),] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join('./', 'media') The images on media folder load very well. I don't know what's wrong, I've tried many workarounds on Google and many other SO related issues and nothing work. I'm lost, please help ! -
Django multiple image upload is possible?
Firstly sory for my bad english. I use python Django framework and ı am use StackedInline when uploading photos. I need to upload the images collectively, not individually. Is this possible? -
media files aren't served to template in django
I trying to serve media files to the template but make them inaccessible from url, and the opposite is happening when i do: http://localhost:8000/media/210000002A.tif I get prompted to download the files so it is being served when accessing from the address bar but in the template I have: <img src="{{ MEDIA_URL }}210000002A.tif"/> and it is not working my dir contains -project -app -media -static -template and i have this is my urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and this in my settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media')