Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sqlite3 custom sql operational error when passing more than one parameter
I am trying to run a custom sql query in django on an sqlite3 database and get an operational error when I try and pass more than one parameter into my sql statement. I'm not sure why, I've tried using cursor.fetchall() instead of namedtuplefetchall but that didn't work. My database is named cardholders.sqlite3 and I have a table also name cardholders that I'm trying to pull data out of. below is the relevant code from django.db import connections from collections import namedtuple def namedtuplefetchall(cursor): "Return all rows from a cursor as a namedtuple" desc = cursor.description nt_result = namedtuple('Result', [col[0] for col in desc]) return [nt_result(*row) for row in cursor.fetchall()] then some views in between @login_required def databaseTest(request): if request.method == 'POST': postid = request.POST.get("id") with connections['cardholders'].cursor() as cursor: cursor.execute("SELECT * FROM %s WHERE ID = %s",['cardholders',postid]) row = namedtuplefetchall(cursor) cursor.close() return render(request, 'LibreBadge/databaseTest.html', context = {"AlertMessage":AlertMessage.objects.all, "row":row}) row = "none" else: return render(request, 'LibreBadge/databaseTest.html', context = {"AlertMessage":AlertMessage.objects.all}) and the traceback Environment: Request Method: POST Request URL: http://localhost:8000/databaseTest/ Django Version: 3.0.5 Python Version: 3.8.2 Installed Applications: ['LibreBadge', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/micah/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line … -
In django using jquery how to retrieve user photo from database
''' function setUserResponse(message) { var UserResponse = '' + message + ' '; $(UserResponse).appendTo(".chats").show("slow"); ''' -
Is there an equivalent of 'list_editable' for FileFields in django?
I'm making a website with django where you can basically upload a file to the django admin and download it whenever you need to view it. Very simple (making it for my dad which wants to organize his excel files for his work). This is the problem, I hard coded the download path to the file I uploaded, which makes me have to modify the path every time I upload a new file with the same name (since django adds a random string of digits and characters every time you upload a file with the same name as before). What i'm currently doing is really inefficient, and would like to change that as soon as possible. My idea is to make the FileField name editable in the django admin. I've come across this: list_editable = ['asd']. I thought that might work and so I tried it. The results were interesting. I immediately saw a 'Save' button on the bottom of the admin site, which wasn't there before. But I still couldn't edit the FileField. I've searched this on multiple forums, the django documentation and more forums, only to not find anything useful. This is a picture of how the admin … -
Django models: Access to a multilevel link between tables
I have a problem to access certain data in my models. I have a User model giving its id to a Profile model which is giving its id to a ProfileA model. And when I create a User it automatically creates a Profile. Here is my user_model from django.db import models from django.contrib.auth.models import AbstractUser from django_countries.fields import CountryField from .model_custom_user_manager import CustomUserManager class User(AbstractUser): """auth/login-related fields""" is_a = models.BooleanField('a status', default=False) is_e = models.BooleanField('e status', default=False) # objects = CustomUserManager() def __str__(self): return "{} {}".format(self.first_name, self.last_name) My profile_model: from django.db import models from django_countries.fields import CountryField from django.contrib.auth import get_user_model User = get_user_model() from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): """non-auth-related/cosmetic fields""" user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') birth_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) nationality = CountryField(null=True) def __str__(self): return f'{self.user.username} Profile' """receivers to add a Profile for newly created users""" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) And what I'm trying to do is create a ProfileA when a Profile is created AND when a User has is_a==True. Here is my profilea_model: from django.db import models from .model_profile import * from django.db.models.signals import post_save from django.dispatch import receiver class ProfileA(models.Model): profile = models.ForeignKey(Profile, null=True, … -
What's the right procfile / requirements for heroku with django channels?
tl;dr - django channels app runs local with manage.py runserver but not on heroku. I'm new to django channels - trying to deploy a very basic django app using channels to heroku. I initially built the project using the standard django polls tutorial and deployed that to heroku. Then i added in a chat app using the django channels tutorial. Managed to get that running fine locally using docker to run a redis server as they suggested and "python manage.py runserver". I'm getting stuck trying to deploy this to heroku or run it locally using heroku local. I've already added the redis addon in heroku and modified settings.py to point to the REDIS_URL environment variable. I also modified my template to use wss if appropriate (I believe that's necessary for heroku): var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var target = ws_scheme + '://' + window.location.host + '/ws/chat/' + roomName + '/'; const chatSocket = new WebSocket( target ); ... Thus I'm concluding that the problem is with the procfile. I'm not sure what the instructions to use there are. The initial polls tutorial used: web: gunicorn gettingstarted.wsgi --log-file - If I just use that 'heroku local' … -
Django Channels configuration websocket timing out
I have a situation with my configuration in which I am completely lost as to why it is not working. My test code has an issue where the Websocket connection is timing out: WebSocket network error: The operation couldn’t be completed. Operation timed out What is it I could have got wrong in the config for the deployed websocket configuration to not be responding? These are my critical configurations: settings.py ASGI_APPLICATION = 'tracking.routing.application' use_websockets = True CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis://:password@127.0.0.1:6379/0")], }, }, } consumers.py from django.contrib.auth.models import User from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async import json, asyncio class TestConsumer(AsyncWebsocketConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) await asyncio.sleep(5) await self.send({ "type": "websocket.close" }) .html <script> var loc = window.location console.log(loc) var path = '/ws/channels-test/' var wsStart = 'wss://' var port = ':6379' var endpoint = wsStart + loc.host + port + path console.log(endpoint) var socket = new WebSocket(endpoint) socket.onmessage = function(e){ console.log("message", e) } socket.onopen = function(e){ console.log("open", e) } socket.onerror = function(e){ console.log("error", e) } socket.onclose = function(e){ console.log("close", e) } </script> routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, … -
Django admin: __str__ returned non-string (type int)
I'm working on a homework assignment to create an API in Django. I am getting the following error on two of my models when I click the link in the Django admin framework: TypeError at /officer/ __str__ returned non-string (type int) Request Method: GET Request URL: http://127.0.0.1:8000/officer/ Django Version: 3.0.4 Exception Type: TypeError Exception Value: __str__ returned non-string (type int) Exception Location: /usr/local/lib/python3.7/dist-packages/rest_framework/relations.py in display_value, line 221 Python Executable: /usr/bin/python3 Python Version: 3.7.5 Python Path: Error during template rendering In template /usr/local/lib/python3.7/dist-packages/rest_framework/templates/rest_framework/horizontal/select.html, error at line 15 __str__ returned non-string (type int) My other models appear to be working correctly. Here is some code from models.py: class Subscriber(models.Model): subscriberID = models.IntegerField(primary_key=True) username = models.ForeignKey(UserInfo, on_delete=models.CASCADE) subscriptiontypecode = models.ForeignKey(SubscriptionType, on_delete=models.CASCADE) servicecode = models.ForeignKey(Service, on_delete=models.CASCADE) requestdate = models.DateField() startdate = models.DateField() enddate = models.DateField() motifofcancellation = models.CharField(max_length=64) beneficiaryID = models.IntegerField() def __str__(self): return self.subscriberID class TransferredSubscription(models.Model): transferID = models.IntegerField(primary_key=True) transferfrom = models.CharField(max_length=64) transferto = models.CharField(max_length=64) requestdate = models.DateField() transferdate = models.DateField() subscriberID = models.ForeignKey(Subscriber, on_delete=models.CASCADE) def __str__(self): return self.transferID class Officer(models.Model): officecode = models.ForeignKey(Office, on_delete=models.CASCADE) subscriberID = models.ForeignKey(Subscriber, on_delete=models.CASCADE) startdate = models.DateField() enddate = models.DateField() def __str__(self): return self.officecode TransferredSubscription works fine. I tried adding return str(self.officecode) and that still gives the same … -
Django - After submit button in Template with only one field of model the others got null
What I want to do is update in a popup template, only the comments field and show not all the fields ion model, but when I submit the form, the field that are not in the template are getting null in DB. I am using the UpdateView, am I correct using this or is better doing it in another way, I am open to suggestions. This fields are getting Null: idSupervisor_cotas idSupervisor_juntas fecha_sup_cotas fecha_sup_juntas Model: class Pieza(ClaseModelo): reporte = models.ForeignKey(Reporte, on_delete=models.CASCADE) noPieza = models.PositiveIntegerField() descripcion = models.CharField( max_length=100, help_text="Descripcion de la Pieza", unique=False ) comentarios = models.CharField( max_length=255, help_text="Comentarios de la Pieza", blank=True, null=True, unique=False ) idSupervisor_cotas = models.ForeignKey( Supervisor, on_delete=models.CASCADE, blank=True, null=True, related_name='sup_cotas' ) fecha_sup_cotas = models.DateTimeField(blank=True, null=True) idSupervisor_juntas = models.ForeignKey( Supervisor, on_delete=models.CASCADE, blank=True, null=True, related_name='sup_juntas') fecha_sup_juntas = models.DateTimeField(blank=True, null=True) noCotas = models.IntegerField(null=True, blank=True) noJuntas = models.IntegerField(null=True, blank=True) def __str__(self): return '{}:[{}]({})'.format(self.reporte.numeroReporte, self.noPieza, self.descripcion) def save(self, **kwargs): if not self.noPieza: noPieza = cal_key(self.reporte, 1) self.noPieza = noPieza+1 self.descripcion = self.descripcion.upper() super(Pieza, self).save() class Meta: verbose_name_plural="Piezas" unique_together = ("noPieza", "reporte") form: class PiezaForm(forms.ModelForm): # MOstramos solo los reportes que no esten Terminados. reporte = forms.ModelChoiceField( queryset=Reporte.objects.filter(state=False) ) #fecha_sup_juntas = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M']) class Meta: model= Pieza fields = ['reporte', 'descripcion', 'comentarios', … -
Best way to make a instance of mongodb client in pymongo
So, first of all, I want to use django, django rest framework, mongoengine and pymongo together. Mongoengine for ODM, Pymongo for interact with the db and DRF for a restful API. The problem is the following: from pymongo import MongoClient from bson.json_util import dumps class MongoConnector: username = 'user' password = 'pass' host = 'localhost' port = '27017' url = host + ':' + port client = MongoClient(mongo_url,username=username,password=password,authSource='admin',authMechanism='SCRAM-SHA-256') def find(self,db, collection, name): db = client[db] collection = db[collection] response = collection.find_one({"name":str(name)}) return dumps(response) I got it from: https://stackoverflow.com/a/55638199/11449132 The point with this piece of code is that I can put it into some file of my project and then, import the class to my API endpoints and do the db interaction, like creating instance of the MongoClient. It looks easy to work with, but my questions are: ¿Is it safe? ¿Does it have some problem with uwsgi or something related to production? like the threads, multiprocessing or something, I mean, I've read some documents and questions about but is not clear it all, for example: https://api.mongodb.com/python/current/faq.html?highlight=wsgi#using-pymongo-with-multiprocessing I know pymongo doesn't work with fork, but I'm not sure if it is important in this escenario. Thanks if someone can help me … -
Does 'list_editable' work with FileField in the django admin?
I'm trying to find a way to rename my uploaded files in the django admin using list_editable. I tried it, but it doesn't seem to be working, since it only shows a 'Save' button below, but nowhere where I can edit my files names. Is this even possible or does it not work with FileFields? I looked it up on forums but nothing to help my case. Thanks in advance! -
My django keep looping the code when runserver
Sorry if the question is really newbie, just learn programming i put this in my models.py from django.db import models from . import func class Materials(models.Model): typeId = models.IntegerField() typeName = models.CharField(max_length=250) price = models.FloatField() updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-typeId') def __str__(Self): return self.typeId def insert_data_once(): rows = func.material_id() for row in rows: data = Materials(typeId = row[0], typeName = row[1], price = func.sell_min(row[0])) data.save() insert_data_once() here is func.py import requests from xml.etree import ElementTree import sqlite3 def material_id(): conn = sqlite3.connect('eve.db') command = 'SELECT DISTINCT invTypeMaterials.materialTypeID, invTypes.typeName FROM invTypeMaterials ' \ 'INNER JOIN invTypes ON invTypeMaterials.materialTypeID = invTypes.typeID ' \ 'WHERE invTypes.Published = 1' result = conn.execute(command) rows = result.fetchall() return rows def sell_min(type_id): URL = 'https://api.evemarketer.com/ec/marketstat?typeid=' + str( type_id) + '&regionlimit=10000002&usesystem=30000142' minerals_price = requests.get(URL) root = ElementTree.fromstring(minerals_price.content) for child in root[0][0][1].iter('min'): sell_min = child.text return float(sell_min) where i should run the insert_data_once function in models.py, the fuction keep looping and cant run manage.py runserver thank you -
Files not uploaded in Django form - encoding type incorrect
We use Django with Crispy forms in our websites. I have a form rendered by {% crispy form %}. Here is the code of the form: class ProfileForm(AddAttributesToFieldsMixin, CleanDateOfBirthMixin, LocalizedFirstLastNameMixin, forms.ModelForm): profile_picture = forms.ImageField(required=False, widget=CustomPhotoWidget, label=_('Update your profile picture'), error_messages={'required': _("A profile picture is required.")}) class Meta: model = User fields = ('slug', 'gender', 'date_of_birth', 'profile_picture') The form uses CustomPhotoWidget which is defined like this: class CustomPhotoWidget(forms.widgets.Widget): def render(self, name, value, attrs=None, renderer=None): return render_to_string(template_name='accounts/edit_profile/widgets/photo_widget.html', context={ 'name': name, 'user_photo': self.attrs['user'].photo, }) But the problem is, when I upload a file from my browser, I receive an error message "No file was submitted. Check the encoding type on the form." and the file is not saved. The encoding type of the form is incorrect. How do I change the encoding type with Crispy forms? -
Django MoneyField: Invalid value for MoneyField
I'm having slight of a problem while using MoneyField in Django. I have 2 models: Work and Price. And Price gets Work id as a Foreign Key. In Postman I'm trying to post a Work with a Price, but I keep getting an error. Here is my work_model: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Work(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200) length = models.IntegerField(null=True) width = models.IntegerField(null=True) def __str__(self): return "{}".format(self.name) And here my price_model from django.db import models from .model_work import * from djmoney.models.fields import MoneyField class Price(models.Model): work = models.OneToOneField(Work, on_delete=models.CASCADE, related_name='price') price = MoneyField(max_digits=19, decimal_places=4, default_currency='USD', null=True) shipping = models.IntegerField(null=True) total = models.IntegerField(null=True) def __str__(self): return "{}".format(self.price) When I'm posting a Work in Postman: { "user":"2", "name":"work 20", "price": [ { "price":20, "price_currency":"USD", "shipping":12, "total":32 } ], "length":"50", "width":"60" } I keep getting this error: ValidationError at /works/ ["Invalid value for MoneyField: [OrderedDict([('price', <Money: 20.0000 USD>), ('shipping', 12), ('total', 32)])]."] I've looked everywhere but can't manage to understand my error, does anyone have a clue? Thanks for your responses! -
form for formset object has no attribute 'cleaned deta'
i have genericview which handle 3 difference form(2 formsets), when i try check cleaned_data, i have error, but when i try make the same by debugger i didnt see anything problem, who may know why i can`t make it? My View : class CompanyCreateView(LoginRequiredMixin, CreateView): model = Company template_name = 'main/company/create_page.html' form_class = CompanyCreateForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['page'] = Page.objects.active().filter(slug='add_company').first() if self.request.POST: context['images'] = ImageGalleryFormSet(self.request.POST, self.request.FILES) context['company_locations'] = CompanyLocationFormset(self.request.POST) else: context['images'] = ImageGalleryFormSet(self.request.GET or None) context['company_locations'] = CompanyLocationFormset(self.request.GET or None) return context @transaction.atomic def form_valid(self, form): context = self.get_context_data() images = context['images'] company_locations = context['company_locations'] self.object = form.save() self.object.active = False self.object.status = CompanyConstants.CompanyStatus.NEW self.object.owner = self.request.user self.object.save() for image in range(len(images)): key_image = 'gallery_items-' + str(image) + '-image' form_image = self.request.FILES.get(key_image) if form_image: ImageGallery(image=form_image, company_id=int(self.object.id)).save() print(company_locations.forms[0].get_cleaned_data) for location in range(len(company_locations)): key_locations = 'form-' + str(location) + '-location' key_address = 'form-' + str(location) + '-address' if self.request.POST.get(key_locations): location = self.request.POST.get(key_locations) address = self.request.POST.get(key_address) company = self.object CompanyLocation.objects.create(location=clean_location(location), address=address, company=company) return super().form_valid(form) def get_success_url(self): return reverse('main:profile', args=[self.request.user.username]) when i try print this i have error, this code that i have works correc but, he is bad. MY FORM: class CompanyLocationForm(forms.ModelForm): location = geo_forms.PointField(widget=GooglePointFieldWidget) class Meta: model = CompanyLocation … -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/catalog/
I got the follwoing error whenever I run the project and automatically catalog/ is added to the url: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/catalog/ Using the URLconf defined in first_project.urls, Django tried these URL patterns, in this order: [name='index'] admin/ first_app/ The current path, catalog/, didn't match any of these. 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. Here is my project urls.py from django.contrib import admin from django.urls import path, include from first_app import views urlpatterns = [ path('', views.index, name='index'), path('admin/', admin.site.urls), path('first_app/', include('first_app.urls')), ] Here is first_app urls.py code: from django.urls import path from first_app import views urlpatterns = [ path('', views.index, name='index'), ] How to get the index page as a default and get rid of the catalog. -
Decorators for authentication using oauth in Django
I am trying to complete Oauth2 using a Decorator in Django. Until before I tried using decorator, I was doing it using this endpoint oauth (which works alright): Note: OSCAR_CALLBACK_URL is URL for oauth endpoint only def oauth(request): if not request.GET.get('oauth_verifier'): return oscar_oauth_init(request) else: res = oscar_oauth_accesstoken(request) return res def oscar_oauth_init(request): oauth = OAuth1(OSCAR_CLIENT_ID, client_secret=OSCAR_CLIENT_SECRET) url=OSCAR_INIT_URL+OSCAR_CALLBACK_URL r = requests.get(url=url, auth=oauth) credentials = convert(parse_qs(r.content)) resource_owner_key = str(credentials.get('oauth_token')[0]) resource_owner_secret = str(credentials.get('oauth_token_secret')[0]) verifier = oscar_oauth_auth(resource_owner_key) request.session['resource_owner_key'] = str(resource_owner_key) request.session['resource_owner_secret'] = str(resource_owner_secret) request.session['verifier'] = str(verifier) return verifier def oscar_oauth_accesstoken(request): verifier = request.GET.get('oauth_verifier') resource_owner_key = request.GET.get('oauth_token') resource_owner_secret = request.session.get('resource_owner_secret') oauth = OAuth1(OSCAR_CLIENT_ID, client_secret=OSCAR_CLIENT_SECRET, resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret, verifier=verifier) r = requests.get(url=OSCAR_TOKEN_URL+verifier, auth=oauth) credentials = convert(parse_qs(r.content)) resource_owner_key = credentials.get('oauth_token')[0] resource_owner_secret = credentials.get('oauth_token_secret')[0] request.session['resource_owner_key'] = str(resource_owner_key) request.session['resource_owner_secret'] = str(resource_owner_secret) return credentials This endpoint was required to be called before other API calls that needed user to be authorized. I am trying to refactor this using the following decorator now: def oscar_login(view_func): def _wrapped_view_func(request, *args, **kwargs): if not request.GET.get('oauth_verifier'): return oscar_oauth_init(request) else: return oscar_oauth_accesstoken(request) return view_func(request, *args, **kwargs) I am not sure how to complete the redirection bit using the decorator. I allowed redirection to the same endpoint oauth (shared above) but the flow stops at end of the endpoint … -
which framework is better for build an audio library site such as soundcloud?
I have a name_cheap regular hosting and I would like to build a web site for users who want to share audio files such as podcast and listening online and maybe using an mobile app, very similar to soundcloud, but I am not sure which is the best framework to do it. Django? Node.js? any other idea. Thanks in advance for help me out. -
Django form gets image data but not text
I have Django form that displays information about the property and the idea of this form is to allow users to amend information about their properties. When displaying the form only image data is displayed, everything else is blank. From if request.user.landlord_profile.landlord_id == project.landlord_id: is the code for the form. views.py def project_detail(request, pk): project = Properties.objects.get(pk=pk) applyButton = Property_Applications.objects.filter(listing=project) propertyReview = Property_Reviews.objects.filter(property=project) # getting the urls property_images = Property_Images.objects.filter(property=project) context = { 'project': project, 'propertyReview': propertyReview, 'property_images' : property_images, } if request.user.is_authenticated: if request.user.last_name == 'False': # allows to tenant to view ads and apply for them if they meet the requirements tenant_profile = Tenant_Profile.objects.get(tenant=request.user.tenant_profile.tenant_id) if request.method == "POST": applyButton = Property_Applications( user=request.user, listing=project,) applyButton.save() context['applyButton'] = applyButton context['tenant_profile']= tenant_profile if request.user.landlord_profile.landlord_id == project.landlord_id: # if the landlord owns this ad, this let's him edit the ad change_listing_form = CreatingListingForm(request.POST, request.FILES, instance=project) if request.method == 'POST': if change_listing_form.is_valid(): change_listing_form.landlord = request.user.landlord_profile change_listing_form.save() messages.success(request, f'Your account has been updated!') else: change_listing_form = CreatingListingForm() context['change_listing_form'] = change_listing_form return render(request, 'project_detail.html', context) project_detail.html - this is what displays the form {% elif request.user.landlord_profile.landlord_id == project.landlord_id%} <p></p> <div style="text-align: center"> <button class="open-button" onclick="openForm()">Manage your Spot</button> </div> <div class="form-popup" id="myForm"> <form class="form-container text-dark" method="POST" … -
How to exchange base docker images safely, when image is down?
I'm learning Docker. Right now I'm working on a Django app and I want to make a container. I'm on Windows 10. When I run docker-compose build, I get: $ docker-compose build Building movies Step 1/9 : FROM python:3.8.2-alpine 3.8.2-alpine: Pulling from library/python Service 'movies' failed to build: no matching manifest for windows/amd64 10.0.18363 in the manifest list entries As far as I've investigated, I'm getting that error because the image is down (because of a bug of docker?) a) https://github.com/nginxinc/docker-nginx/issues/230 b) https://github.com/docker-library/official-images/issues/3835 So what image can replace this one: FROM python:3.8.2-alpine??? I'm following this tutorial Test-Driven Development with Django, Django REST Framework, and Docker from https://testdriven.io/. Dockerfile: # pull official base image FROM python:3.8.2-alpine # set work directory RUN mkdir -p /usr/src/app WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt /usr/src/app/requirements.txt RUN pip install -r requirements.txt # copy project COPY . /usr/src/app/ -
How to receive Empty files in djnago views and save it even if the file is not uploaded as it is optional?
As my image option is optional , I want to save it even if the file is not uploaded as it is optional, but it is giving me error as it is not able to receive the image. How can I save it in the database even if that field is empty? #Model class Recommendations(models.Model): Name = models.CharField(max_length=100) Company = models.CharField(max_length=100, null=True) Designation = models.CharField(max_length=100, default='Null') Message = models.TextField(null=False) image = models.ImageField(upload_to='Recommender', default='default.png', blank=True) check = models.BooleanField(default=False) # Views Code to receive the data through a form def recommend(request): if request.method == 'POST': try: name = request.POST['name'] company = request.POST['company'] designation = request.POST['designation'] message = request.POST['message'] image = request.FILES['photo'] recom = Recommendations(Name=name,Company=company,Designation=designation, Message=message, image=image) recom.save() messages.success(request,'Recommendation Recieved') return redirect('/') except Exception as problem: print(problem) messages.error(request, problem) return redirect('/') -
How to mock out custom throttle class for testing in django-rest-framework?
I have a custom throttle class like: (print statements are for debugging :)) in api.throttle.py print("befor CustomThrottle class") class CustomThrottle(BaseThrottle): def __init__(self): super().__init__() print("initializing CustomThrottle", self) self._wait = 0 def allow_request(self, request, view): print("CustomThrottle.allow_request") if request.method in SAFE_METHODS: return True # some checking here if wait > 0: self._wait = wait return False return True def wait(self): return self._wait my api.views.py is like: from api.throttle import CustomThrottle print("views module") class SomeView(APIView): print("in view") throttle_classes = [CustomThrottle] def post(self, request, should_exist): # some processing return Response({"message": "Done."}) and my tests is api/tests/test_views.py: @patch.object(api.views.CustomThrottle, "allow_request") def test_can_get_confirmation_code_for_registered_user(self, throttle): throttle.return_value = True response = self.client.post(path, data=data) self.assertEqual( response.status_code, status.HTTP_200_OK, "Should be successful", ) @patch("api.views.PhoneConfirmationThrottle") def test_learn(self, throttle): throttle.return_value.allow_request.return_value = True response = self.client.post(path, data=data) self.assertEqual( response.status_code, status.HTTP_200_OK, "Should be successful", ) the first test passes correctly but still the CustomThrottle class is instantiated but the allow_request method is mocked; the second test shows that neither CustomThrottle class is mocked nor the allow_request method and it fails with status 429 (CustomThrottle has a throttle rate of 2 minutes). -
django: css files not loading in production with nginx
I have seen many similar posts but nothing has been able to make the trick for me. Browser throws me this kind of error for all my css files when i load my static. GET https://www.exostock.net/staticfiles/vendor/font-awesome/css/font-awesome.min.css net::ERR_ABORTED 404 (Not Found) and Home:136 GET https://www.exostock.net/staticfiles/img/logo8.png 404 (Not Found) from the information I read and the django + nginx documentations, I am not able to spot where I am making a mistake. I have been on it for a few days now and I hope that someone could see what I cannot. nginx/sites-available/app.conf server { server_name exostock.net www.exostock.net; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/exostocksaas/app.sock; } location /static/ { alias /home/ubuntu/exostocksaas/collected_static/; } location ~ \.css { add_header Content-Type text/css; } location ~ \.js { add_header Content-Type application/x-javascript; } } settings.py in django STATIC_URL = '/staticfiles/' # STATICFILES_FINDERS = ( # 'django.contrib.staticfiles.finders.FileSystemFinder', # ) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles') ] STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') and my html links to statics <!-- Bootstrap CSS--> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}"> <!-- Font Awesome CSS--> <link href="{% static 'vendor/font-awesome/css/font-awesome.min.css' %}"> <!-- Custom Font Icons CSS--> <link href="{% static 'css3/font.css' %}"> -
How do I allow users of Django to create their own personal blog?
I have created a Django site that allows users to post and comment on these posts. I thought it would be a good idea to allow each user to have their own "page" where they can allow invited members this page to basically use the blog feature that I've designed. The only thing I can't figure out is how to allow users to dynamically create a page that is specific to them. Can this be done with one template? -
django views: How to get the desired column name?
I would like to ask the same question again because my previous was not answered. Here is the link: How to get the desired column name? Thanks very much for the help. -
Why is Django using version 2.0.3 while I have 3.0.5 installed?
I have django installed in a virtual environment, everything works, however when you start a server it starts django 2 instead of 3. (venv) C:\Users\Patrick\PycharmProjects\OptionDetails.com>cd optiondetails (venv) C:\Users\Patrick\PycharmProjects\OptionDetails.com\OptionDetails>py manage.py runserver Performing system checks... System check identified no issues (0 silenced). April 30, 2020 - 18:53:56 Django version 2.0.3, using settings 'OptionDetails.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. (venv) C:\Users\Patrick\PycharmProjects\OptionDetails.com\OptionDetails>py -m pip install -U Django Requirement already up-to-date: Django in c:\users\patrick\pycharmprojects\optiondetails.com\venv\lib\site-packages (3.0.5) Requirement already satisfied, skipping upgrade: asgiref~=3.2 in c:\users\patrick\pycharmprojects\optiondetails.com\venv\lib\site-packages (from Django) (3.2.7) Requirement already satisfied, skipping upgrade: sqlparse>=0.2.2 in c:\users\patrick\pycharmprojects\optiondetails.com\venv\lib\site-packages (from Django) (0.3.1) Requirement already satisfied, skipping upgrade: pytz in c:\users\patrick\pycharmprojects\optiondetails.com\venv\lib\site-packages (from Django) (2020.1) Could not build wheels for Django, since package 'wheel' is not installed. Could not build wheels for asgiref, since package 'wheel' is not installed. Could not build wheels for sqlparse, since package 'wheel' is not installed. Could not build wheels for pytz, since package 'wheel' is not installed.