Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: App in subdirectory relative import
I'm settings up a Django project following the structure of this cookiecutter template but I'm having problems with explicit relative imports in my apps. I'm trying to import my models using from .model import ModelA but I'm getting this error from Django: RuntimeError: Model class core.models.ModelA doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. My project is structured like this: my_project - config - __init__.py - settings.py - urls.py - my_project - __init__.py - core # this is an app - __init__.py - models.py # remaining app files manage.py I have of course put my app in INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'my_projects.core.apps.CoreConfig', # my app ] And CoreConfig is setup as: class CoreConfig(AppConfig): name = 'my_project.core' It feels like django is not loading the AppConfig when using explicit relative import. Everything works perfectly if I change my imports to absolute paths from my_project.core.models import ModelA What am I missing? -
react-django csrf token error using react-cookie package
import cookie from 'react-cookies'; const csrfToken = cookie.load('csrftoken') onSubmitSignUp = () => { fetch('http://127.0.0.1:8000/register/', { method: 'post', headers:{ 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken }, body: JSON.stringify({ username: this.state.username, email: this.state.email, password: this.state.password }) }) .then(response => response.json()) .then(res => { console.log(res) }) } Here i am sending some data to django.to send csrf token i am using 'react-cookie' as per the documentation. but in python side it is showing Forbidden (CSRF cookie not set.): /register/ [11/Nov/2018 11:56:33] "POST /register/ HTTP/1.1" 403 2868 -
I have an Celery' object has no attribute 'on_after_configure' error
@app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(5, smart_home_manager.s(), name='Check Smart Home') Celery version 3.1.26.post2 (Cipater) -
How to connect mysql with django
I m tryin' to connect mysql database with django, for that, I did this:- python manage.py runserver but, this new mess came around sayin' :- (django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?). But when I m tryin' to install mysqlclient through pip as:- pip install mysqlclient another creepy thing comes up:- _mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Comm unity\\VC\\Tools\\MSVC\\14.15.26726\\bin\\HostX86\\x86\\cl.exe' failed with exit status 2 For installing mysql.h, I have downloaded mysql connector too, but the error continues. I don't know how to proceed furher. Any help would be appreciated. -
how to assign variable choices to a form field in django 2.1
i have a problem with a formModel class that should update a form, the problem is that i want the field (ara_book) choices to be variable according to another field (level) (which is a list of values), than generate the choices from a json file and fill the choices tuple with and make a form with multiple select according to the length of the list in the value of the field (level). EX: if user level field is set to ['01','02'], the form should generate two select elements the first will have options of the json_file['ara_book']['01'] and the other with options of json_file['ara_book']['02'] Here is the class class BooksUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): FILE_PATH = os.path.join(BASE_DIR, "dashboard/static/json/books.json") BOOKS = () with open(FILE_PATH, 'r', encoding='utf-8') as f: JSON_FILE = json.load(f) user_level = kwargs['instance'].level for item in user_level: for key in JSON_FILE[item]['ara_book']: BOOKS.append(JSON_FILE[item]['ara_book'][key]) super(BooksUpdateForm, self).__init__(*args, **kwargs) ara_book = forms.ChoiceField(choices=BOOKS) class Meta: model = Profile fields = ['ara_book'] Here is the view def books(request): if request.user.profile.level == '': messages.warning(request, f'يجب تحديث المستوى المُدَرَّسْ قبل تحديث الكتب المقررة') return redirect('level') if request.method == 'POST': books_form = BooksUpdateForm(request.POST, instance=request.user.profile) if books_form.is_valid(): books_form.save() messages.success(request, f'لقد تم تحديث المستوى المُدَرَّسْ بنجاح') return redirect('profile') else: books_form = BooksUpdateForm(instance=request.user.profile) … -
Incorrect redirection for a single post category
I'm developing my personal blog; it has only two categories and I would like to have a specific list of posts for both categories. For this reason I've expand get_absolute_url as you can see below: from django.db import models from django.urls import reverse CATEGORY_CHOICES = ( ('G.I.S.', 'G.I.S.'), ('Sustainable Mobility', 'Sustainable Mobility'), ) class Blog(models.Model): """ Blog's post definition """ title = models.CharField( max_length=70, unique=True, ) slug = models.SlugField( unique=True, ) contents = models.TextField() publishing_date = models.DateTimeField() category = models.CharField( max_length=50, choices=CATEGORY_CHOICES, ) def __str__(self): return self.title def get_absolute_url(self): if Blog.objects.filter(category="G.I.S."): return reverse("gis_single_post", kwargs={"slug": self.slug}) if Blog.objects.filter(category="Sustainable Mobility"): return reverse("sumo_single_post", kwargs={"slug": self.slug}) Below you can see views.py; it has different model based on a category: from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Blog class GisSinglePost(DetailView): model = Blog queryset = Blog.objects.filter(category="G.I.S.") context_object_name = 'post' template_name = "gis_single_post.html" class GisListPost(ListView): model = Blog queryset = Blog.objects.filter(category="G.I.S.") context_object_name = 'posts' template_name = "gis_list_post.html" class SuMoSinglePost(DetailView): model = Blog queryset = Blog.objects.filter(category="Sustainable Mobility") context_object_name = 'post' template_name = "sumo_single_post.html" class SuMoListPost(ListView): model = Blog queryset = Blog.objects.filter(category="Sustainable Mobility") context_object_name = 'posts' template_name = "sumo_list_post.html" And below there is urls.py with its four path: from django.urls … -
Different user sessions per app in Django project
I have a Django project with 2 apps: public private I would like to allow users from the private app to login on the public app (as an other user), without them being logged out from the private app. Is there a way to do this (I'm not using the native admin site)? -
How to do a reusable sidebar app in Django, that does not produce a HttpResponse itself?
How to set up a reusable sidebar app in Django, that can just be "included" without the need to adjust the template? I read several tutorials. They all describe views that return a HttpResponse and extend a base template. That is useful for the main view. But how to set up a simple drop-in view, that just sits in the sidebar of other apps? I name this requirements: It must not return a HttpResponse, as this is done by the main view. It should be able to display a model. It is easy to include. It should run out-of-the-box without copying and adjusting a template first. How does the interface look like and how is this interface used by the project? I guess there are tons of answers, yet it is difficult to find them, as my search keywords are not specific enough. So please excuse to bring up this question, that may sound self-evident to the experienced Django developer. -
How to test a graphQL mutation for a update function in graphiQL interface?
I create crud functions inside a mutation: import graphene from .models import Channel as ChannelModel from .types import ChannelType class CreateChannel(graphene.Mutation): class Input: name = graphene.String(required=True,) description = graphene.String(required=True,) Output = ChannelType @staticmethod def mutate(root, info, **kwargs): channel = ChannelModel(**kwargs) channel.save() return channel class ChannelToUpdate(graphene.InputObjectType): name = graphene.String(required=False, default_value=None) description = graphene.String(required=False, default=None) class UpdateChannel(graphene.Mutation): class Meta: id = graphene.ID(required=True) to_update = graphene.NonNull(ChannelToUpdate) Output = ChannelType @staticmethod def mutate(root, info, **kwargs): channel = graphene.Node.get_node_from_global_id(info, kwargs['id']) if channel: channel.update(**kwargs['to_update']) channel.save() return channel class Mutation(graphene.ObjectType): create_channel = CreateChannel.Field() update_channel = UpdateChannel.Field() So when I want to test the createChannel, I go to the localhost/grapgql and do this: mutation{ createChannel( name:"myChannel" description:"this is mychannel" ) } This works just fine and shows the output: { "data": { "createChannel": { "id": "Q2hhbm5lbFR5cGU6OA==", "name": "myfirstChannel", "description": "this is mychannel" } } } Finally when I want to test the updateChannel what should I do? If there are problems associated with updateChannel class I will appreciated if anybody help me. -
This backend doesn't support absolute paths. in Python, Django
when I'm trying to upload the images through aiming I have faced some error please help me out. I have faced only this model so that mean S3 bucket is properly configured I am able to upload images or doc another model. This backend doesn't support absolute paths. Error Highlighted code is = photopath = str(a.path ) My Models class ProductImage(models.Model): fk_product=models.ForeignKey(Product) product_image_main=models.ImageField("Image", upload_to = product_main_upload_to ,null=True,blank=True) product_image_sub1=models.ImageField("Image", upload_to = product_sub1_upload_to ,null=True,blank=True) product_image_sub2=models.ImageField("Image", upload_to = product_sub2_upload_to,null=True,blank=True) product_image_sub3=models.ImageField("Image", upload_to = product_sub3_upload_to ,null=True,blank=True) product_image_sub4=models.ImageField("Image", upload_to = product_sub3_upload_to ,null=True,blank=True) product_image_sub5=models.ImageField("Image", upload_to = product_sub3_upload_to ,null=True,blank=True) product_image_sub6=models.ImageField("Image", upload_to = product_sub3_upload_to ,null=True,blank=True) def __unicode__(self): return self.fk_product.name def save(self): super(ProductImage, self).save() prod_img="" if self.product_image_main: a= self.product_image_main elif self.product_image_sub1: a=self.product_image_sub3 elif self.product_image_sub2: a=self.product_image_sub1 elif self.product_image_sub3: a=self.product_image_sub3 elif self.product_image_sub4: a=self.product_image_sub4 elif self.product_image_sub5: a=self.product_image_sub5 elif self.product_image_sub6: a=self.product_image_sub6 print a basewidth = 1000 photopath = str(a.path ) b=str_to_raw(photopath) c=re.sub(r'\\', "/", b) im = Image.open(c).convert('RGB') extension = c.rsplit('.', 1)[1] # the file extension filename = c.rsplit('/', 1)[1].rsplit('.', 1)[0] # the file name only (minus path or extension) fullpath = c.rsplit('/', 1)[0] # the path only (minus the filename.extension) medname = filename + ".jpg" wpercent = (basewidth/float(im.size[0])) hsize = int((float(im.size[1])*float(wpercent))) im = im.resize((basewidth,hsize), Image.ANTIALIAS) im.save(fullpath + '/' + medname,format="JPEG",optimize=True, quality=90) -
Two layer for loops to demonstrate list in django template
I want to demonstrate two layer "for" loops in one template html page in django. The first layer is topics and the second is entries under each topics. Here's the view.py for topics and topic. def topics(request): topics = Topic.objects.filter(owner=request.user).order_by("date_added") context = {"topics": topics} return render(request, "project/topics.html", context) def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) entries = topic.entries.order_by("-date_added") context = {"entries": entries} return render(request, "project/topic.html", context) In the topics.html template, I want to demonstrate topics and every entries under each topic as following. But how could I achieve that? {% for topic in topics %} <a href="{% url 'project:topic' topic.id %}">{{ topic.text }}</a> {% for entry in entries %} <a href="{% url 'project:entry' entry.id %}">{{ entry.text }}</a> -
Serving multiple Django applications with Nginx and Gunicorn under same domain
Now I have one Django project in one domain. I want to server three Django projects under one domain separated by / .For example: www.domain.com/firstone/, www.domain.com/secondone/ etc. How to configure nGinx to serve multiple Django-projects under one domain? How configure static-files serving in this case? My current nGinx config is: server { listen 80; listen [::]:80; server_name domain.com www.domain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; server_name domain.com www.domain.com; ssl_certificate /etc/nginx/ssl/Certificate.crt; ssl_certificate_key /etc/nginx/ssl/Certificate.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; root /home/admin/web/project; location /static { alias /home/admin/web/project/static; } location /media { alias /home/admin/web/project/media; } location /assets { alias /home/admin/web/project/assets; } location / { proxy_pass_header Server; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header X-Forwarded-Proto https; proxy_connect_timeout 75s; proxy_read_timeout 300s; proxy_pass http://127.0.0.1:8000/; client_max_body_size 100M; } # Proxies # location /first { # proxy_pass http://127.0.0.1:8001/; # } # # location /second { # proxy_pass http://127.0.0.1:8002/; # } error_page 500 502 503 504 /media/50x.html; -
Assigning value to foreign key field
I'm having difficulty assigning a title to the UserService model, which is a foreign key to another model. models.py class IndustryService(models.Model): industryname = models.ForeignKey(Industry, on_delete=models.CASCADE) title = models.CharField(max_length=120) class UserService(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) title = models.ForeignKey(IndustryService, on_delete=models.CASCADE) Here is the portion of code within the view that is failing: industryservices = IndustryService.objects.filter(industryname=industry) for service in industryservices: try: qs = UserService.objects.get(user=user, title=service.title) except: userserv = UserService.objects.create(user=request.user) userserv.title = service userserv.save() The error that I'm getting is as follows: NOT NULL constraint failed: accounts_userservice.title_id Based on my testing, the way in which I'm assigning the value to the 'title' foreign key field is wrong (i.e. these 2 lines of code). service2 = IndustryService.objects.get(title=service.title) userserv.title = service2 Any thoughts on how I can fix this? Thanks! -
Using user uploaded sqlite database in Django
I am new to Django and wanted to ask for best way to cater to the below scenario. I have generated models.py using inspectDb on a sqlite database. I am able to use the generated model classes to access the data from the database and display in a customized view. having successfully performed the above use case, now: allow users to upload their respective version of the sqlite file to be able to generate views for their data. <- I am looking for guidance on what is the best way to accomplish this. -
I want to do an online radio with Python
I want to make an online radio in my web page, in the web page I use django for the backend, (with video, I know that this is not a radio) and do a streming on the page and then use the Facebook APIs and twitch to transmit at the same time. what Python libraries should I use to do the atreming? -
How can i use OBD studio on so it can send data to Django server
Hello can anyone tell me how to stream data to Django server with ODB or some other streaming software? Thank you! -
Is there any way to use both SQL and NO-SQL databases together in Django?
I already have SQLite DB integrated with my web app (using Django web framework) but now I want to add MongoDB for NO-SQL component. Is there any way to use both SQL and NO-SQL together? -
Wagtail:How to have multiple types of admin
I am making a blogging website using wagtail so we have multiple writers so I need that no one can see drafts of other users and only the superadmin can post the blogs but I can't find that setting. -
Django Custom validation Organizing
New to django. Let a custom validation be: from django import forms class ContactForm(forms.Form): def clean_recipients(self): data = self.cleaned_data['recipients'] if "fred@example.com" not in data: raise forms.ValidationError("You have forgotten about Fred!") return data I want to make code clean. Thats why open a new file validators.py how to use the validation from validators.py -
DRF GnericViewset not accepting json data
I'm usig Django 2.x and Django REST Framework. I have a viewset defined like class UserSettingViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): serializer_class = UserSettingSerializer permission_classes = (IsAuthenticated, AdminAuthenticationPermission) def get_object(self): user_setting = UserSetting.objects.get(user=self.request.user) return user_setting def get_queryset(self): queryset = UserSetting.objects.filter( user=self.request.user ) return queryset def update(self, request, *args, **kwargs): iso3 = request.POST.get('country', None) if iso3 is None or not iso3: raise ValidationError({'country': 'Country iso3 is required'}) try: country = Country.objects.get(iso3=iso3.upper()) except ObjectDoesNotExist: raise ValidationError({'country': 'Country does not exists'}) user_setting = UserSetting.objects.get(user=request.user) user_setting.country = country user_setting.save() return super(UserSettingViewSet, self).update(request, *args, **kwargs) When I call update from Angular it is not accepting form data and gives the error {'country': 'Country iso3 is required'} While sending data as **form-data from postman is working fine.** The header of the Angular request is while that of Postman is How to setup Django to accept json data in PUT? -
django.core.exceptions.SuspiciousFileOperation: The joined path is located outside of the base path component
This worked fine everytime used to do django websites but this time it is giving me an error. Settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'portfolio/static/') ] STATIC_ROOT = os.path.join(BASE_DIR , 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I have a profile.jpg in my directory Portfolio-Project/Portfolio/static/profile.jpg. It should collectstatic from here and paste the staticfiles in Portfolio-project/static as mentioned in my code. but it is giving ,me some error. Error After using the command "Python manage.py collectstatic" django.core.exceptions.SuspiciousFileOperation: The joined path (C:\Users\Kiran\Desktop\portfolio-project\portfolio\static\Profile.jpg) is located outside of the base path component (C:\Users\Kiran\Desktop\portfolio- project\portfolio\static\) Please Help. Thanks -
Filter options in a input in respect of a field
I have this model class Personal(models.Model): Ldr = ( ('Yes', 'Yes'), ('No', 'No'), ) username = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) isLeader - models.CharField(max_length=100, choices=Ldr, default="No", null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.username) class Order(models.Model): product = models.CharField(max_length=30) leader = models.ForeignKey(Personal, on_delete=models.CASCADE) orderBy = models.ForeignKey(Personal, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.product And forms.py class FormOrder(forms.ModelForm): description = forms.CharField(label="" ,widget=forms.Textarea(attrs={"placeholder": "Descripcion", "class": "form-control"})) class Meta: model = Order fields = ["product","leader","orderBy"] If i use the form in a template, the input for the field leader shows all the Personal, and that's ok, but i want just to show the personal if the field "isLeader" have the value "Yes" -
Django XSS - can it happen in server side (views.py)?
My understanding is that Django has great default settings to minimize the risk that there is client size XSS attack, for example if you had <p>Hello {{ user.username }}</p> in your template, where the user could type in anything they want for their username. I don't see any references to XSS in client side Python files. Is my understanding correct that there is no major concern for a client side XSS attack? As an example situation, the user can input anything they want into an input box. The results from that input box are stored in a database. That input is then queried from a database and sent in an email. email = EmailMessage( ExtendedUser.objects.filter(user__username=username)[0].email_subject, ExtendedUser.objects.filter(user__username=username)[0].email_content, 'me@mysite.com', ['me@mysite.com'] ) email.content_subtype = "html" email.send() In situations like this, is there any need to strip any tags or sanitize anything anything? I'm not sure when I need to be concerned about malicious user inputted data. EDIT: I know Django project writes "XSS attacks allow a user to inject client side scripts into the browsers of other users." I'm interested if there are any client side reasons to strip user inputted data of malicious tags. -
Django Rest Framework - Check Password to Validate Form
I'm trying to validate a form through DRF, but it would require the user to enter their password for confirmation. I can't seem to get it to work. Here is my current View and Serializer. Its for a 'change email' form, two fields required, the email and user password. It's for a seperate email model. The serializer: class UpdateEmailAddressSerializer(serializers.ModelSerializer): class Meta: model = EmailAddress fields = ('email',) And the APIView: class UpdateEmailAPI(APIView): permission_classes = (IsAuthenticated,) serializer_class = UpdateEmailAddressSerializer def post(self, request, user, format=None): user = User.objects.get(username=user) serializer = UpdateEmailAddressSerializer(data=request.data, instance=user) if serializer.is_valid(): ## logic to check and send email serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I'm not sure where to place the password or what to do with it. Its from the User model itself. When I attempted to add password to the fields in the UpdateEmail serializer it ended up updating the User password with plain text and making that user object unable to use that password. I just want to check the password of the user for confirmation of this form. Is there an obvious way to do this? -
Using Django UserPassesTestMixin with LoginRequiredMixin to go to an authorized URL
I'm trying to write a mixin that will protect views by first checking if someone is logged in and then if they have been onboarded. It seems to work, by blocking views it's attached to, but it the URLjust goes to a 403 forbidden. Any ideas on how to get it to go to the named url? from django.contrib.auth.mixins import UserPassesTestMixin from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.contrib.auth.mixins import LoginRequiredMixin class OnboardedMixin(LoginRequiredMixin, UserPassesTestMixin): """ a custom mixin that checks to see if the user has been onboarded yet """ def test_func(self): if self.request.user.onboarded and self.request.user.is_active: return True def get_login_url(self): return redirect('onboarding',)