Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create Django DRF API to Upload file and pass it to function in Views.py?
I'm trying to create an API using DRF where PDF documents are uploaded and stored in separate Directory "/media/documents". Once during it's uploading I want it to pass it through an function where I will need it to convert into a new format and then save it to the "/media/documents". The function as follows. Function for processing Uploaded File -
Gunicorn throws error 403 when accessing static files
python==2.7.5, django==1.11.10, gunicorn==19.7.1, RHEL 7.4 I have a django project at my job written not by me. It was in eventcat user's home directory and with time we ran out of available space on the disk. I was to move the project to /data/. After I moved the project directory and set up a new environment I faced the problem that static files are not loaded and throwing 403 forbidden error. Well, I know that gunicorn is not supposed to serve static files on production, but this is an internal project with low load. I have to deal with it as is. The server is started with a selfwritten script (I changed the environment line to new path): #!/bin/sh . ~/.bash_profile . /data/eventcat/env/bin/activate exec gunicorn -c gunicorn.conf.py eventcat.wsgi:application The gunicorn.conf.py consists of: bind = '127.0.0.1:8000' backlog = 2048 workers = 1 worker_class = 'sync' worker_connections = 1000 timeout = 120 keepalive = 2 spew = False daemon = True pidfile = 'eventcat.pid' umask = 0 user = None group = None tmp_upload_dir = None errorlog = 'er.log' loglevel = 'debug' accesslog = 'ac.log' access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' proc_name = None def post_fork(server, worker): … -
ModuleNotFoundError: No module named 'acl.validators.login_validator'; 'acl.validators' is not a package
I try to write a custom validator under validators folder I have login_validator.py file and I defined it here: def validate_field(username, password): if username == "": raise ValidationError(_('Username may not be blank'),params={'username': username},) then I called this validator in my login view like this: def login(request): try: username = request.data.get('username', validators=[validate_field]) but when I run the project I get this error: ModuleNotFoundError: No module named 'acl.validators.login_validator'; 'acl.validators' is not a package I am not sure how I should use my validator to check if a user in login page entered any data or other things. -
Django (DRF) & React - Forbidden (CSRF cookie not set)
There are tens of questions that are essentially identical to the one I'm asking. However, none of their answers seem to be working for me. I have a React front-end where I am using axios to send requests to the back-end. Example const request = await axios.post('${BASE_URL}/logout/') Most of the Django Rest Framework endpoints are made with ViewSets. However, I have a few that are custom and mostly made for authentication. path('createaccount/', views.create_account), path('me/', views.current_user), path('logout/', views.logout), path('login/', views.login), path('resetpassword', views.reset_password), For the development of this project I've included @csrf_exempt above these views because I didn't want to deal with it at the time. Now I'm nearing deployment and it's time to figure it out. Some answers say I need to get a CSRF Token from Django which is stored in cookies and I need to pass that in the header of each request. Some answers say all I need to do is configure axios like axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "XCSRF-TOKEN"; And it will "just work". I've tried adjusting my CSRF_COOKIE_NAME to various values to get this to work too. Some answers even say to keep @csrf_exempt but that sounds like a very, very bad idea. Do I actually … -
Django new user with email confirm
I am super new to Django and currently working on a training project. Question 1 - I want new registered user can receive a confirm email. Referring to https://docs.djangoproject.com/en/2.1/topics/auth/customizing/, I create my User model as below and I hope create_user() in UserManager been called on new user creation but it turns out it never been called. Is my implementation wrong? from authtools.models import AbstractEmailUser from django.db import models from authtools.models import UserManager as BaseUserManager from mysite.models import UserType from mysite.models import Organisation class UserManager(BaseUserManager): def create_superuser(self, **kwargs): user = self.create_user(**kwargs) user.is_superuser = True user.is_staff = True user.user_type = UserType.objects.get(name='ADMIN') user.save(using=self._db) return user def create_user(self, email, password=None, **kwargs): user = super().create_user(email, password, kwargs) user.email_user("Register Confirm", "welcome", "admin@mysite.com") class User(AbstractEmailUser): first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) user_type = models.ForeignKey(UserType, on_delete=models.CASCADE) organisation = models.ForeignKey(Organisation, null=True, blank=True, on_delete=models.CASCADE) modified = models.DateTimeField(auto_now=True) objects = UserManager() REQUIRED_FIELDS = ['first_name', 'last_name'] class Meta: db_table = 'users' Question 2 - Can anybody explains how Django framework works on triggering to create a new user? Say receiving api call /users/add, how create_user() been called? -
How to save a django model into json file
I would like to save a Django model into a json file into a specific directory. How can I do that? My code is below in views.py. def JSON(request): with open(r'C:\Users\Savas\Desktop\DOCUMENTS\file.json', "w") as out: mast_point = serializers.serialize("json", Poi.objects.all()) out.write(mast_point) -
Model Property as a Search Field - Invalid Lookup
I have a model property and I am trying to use the same as a search field in Django admin but it gives me an invalid field lookup. class RentableSpace(models.Model): @property def reference_code(self): if self.parent: return f'{self.parent.reference_code}-{self.internal_code}' return f'{self.hmlet_code}' Admin.py list_display = ('name', 'space_type','reference_code',) search_fields = ('name', 'space_type', 'id', 'reference_code',) -
Refreshing displayed data
I have this view working and displaying everything correctly. Though when I update the db the displayed data doesn't update in the view. By restarting the httpd server it then updates the displayed data. from django.views.generic import ListView from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render_to_response from player.models import . list = [123,155,166,445] class Stats(LoginRequiredMixin, ListView): model = Table template_name = 'stats.html' object_list = Table.objects.all() data = object_list.filter(id__in= list) contract = [x.Contract for x in data] will = [x.Will for x in data] def get(self, request,): context = locals() context['contract'] = self.contract.count('Deed1') context['will'] = self.will.count('Death') return render_to_response(self.template_name, context) I was hoping to get it to display the new count anytime the page refreshes. Any nudge in the right direction greatly appreciated. -
docker-compose/django TypeError: expected str, bytes or os.PathLike object, not NoneType
I'm trying to set up my Django and postgres dev environment with docker so I can run it on other machines more easily as well as run everything from 1 terminal window (I'll be adding my react front end once I figure out this Django error). I feel like I'm close, but getting hung up on this error. Looks like this is the output when it runs start.sh. I've been following a lot of different guides on this setup and maybe I've just got things out of whack because of that. Not sure where to go from this error. I am able to successfully execute the runserver command outside of the container so this seems to be isolated to the container. Error: django_server | Traceback (most recent call last): django_server | File "manage.py", line 15, in <module> django_server | execute_from_command_line(sys.argv) django_server | File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line django_server | utility.execute() django_server | File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute django_server | self.fetch_command(subcommand).run_from_argv(self.argv) django_server | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv django_server | self.execute(*args, **cmd_options) django_server | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute django_server | output = self.handle(*args, **options) django_server | File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 79, in handle django_server | executor = … -
Why is Django-CMS not directly linking to my Cloudfront CDN and getting 404's for CKEditors static files?
I am trying to set up hosting for a DjangoCMS application using AWS. I'm currently utilizing Cloudfront with S3 as the CDN for media and static files, however, I've run into trouble when trying to use the ckeditor inside of the CMS plugins. I will get 404 errors that prevent it from loading at all. This is because Django CMS appears to be inappropriately building the URL's for ckeditor's static files. The urls look like this: http://example.com/en/admin/cms/page/add-plugin/my.cloudfront.net/static/djangocms_text_ckeditor/ckeditor/skins/moono-lisa/editor.css/change/ When not using the CDN and storing the files locally it looks like DjangoCMS creates a 304 redirect to the proper location, but when using a CDN it seems to be mangling the url for some reason. Is there anyway to configure the way DjangoCMS is building this url, or some standard way to implement CDN's for DjangoCMS that I may be mishandling? The current way I have the CDN setup is to have Django redirect static and media requests to the CDN. -
How to validate in UpdateView without validating through a form?
My company is currently using a custom task management library (viewflow) and I am given an UpdateProcessView. The view updates the process that governs all the tasks and I would like to override this to verify call form_valid only if certain conditions are met. Since I do not have control over the form that gets submitted to this view, writing a custom form to validate is out of the question (we tried this before and it got very messy). Given this circumstances, where is the next best place to insert my validation logic? I am checking if certain fields in self.model are present. -
Django Rest Framework viewset - ForeignKey filtering filter based on Username Issue
I have a django project and i have integrated the Django Rest Framework into the project for the back end. I have a Profile model. In the profile model, I have a user foreignkey that has a username field. The username is what I am currently using for filtering profiles. I had everything working perfectly when the ListAPIView and RetrieveAPIView were seperated. class ProfileListView(ListAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer class ProfileDetailView(RetrieveAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer def get_object(self): return self.queryset.get(user__username=self.kwargs.get('username')) Another thing is that when the views were seperated, I set a username parameter in the url that was passed into the view. I am not sure how to integrrate that into viewsets. path('users/', UserListView.as_view()), path('users/<username>', UserDetailView.as_view()), this is what it I have now router = DefaultRouter() router.register(r'users', UserViewSet, basename='user') router.register(r'profiles', ProfileViewSet, basename='profile') urlpatterns = router.urls I am trying to change my code so that rather than each view sperate I want to use a generic view set that is a single point with all views. When I use look at the API in my web browser, the list view works but when I try to search a specific username, I get an error. DoesNotExist at /api/users/profiles/omarjandali/ Profile … -
How to use pg_trgm operators(e.g. %>) in django framework?
I'm using the pg_trgm for similarity search on postgreslq DB and i need return the results to the front by using the django model.But I got a problem that the operator [%>] can not be recognized by the django framework. Any advise? thank you I using the model.objects.raw() to execute sql. And got a error response:unsupported format character '>' (0x3e) at index 52 searchParam ='test' mymodel.objects.raw('select * from mytable where columnname %> %s', [searchParam]) ValueError: response:unsupported format character '>' (0x3e) at index 52 -
Problems with querying multiple tables
I am having problems with query multiple tables this is my model: class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True) name = models.CharField(max_length=255, unique=True) img_src = models.CharField(max_length=255, null=True) price = models.IntegerField(blank=False, null=True) sale_price = models.IntegerField(blank=False, null=True) description = models.TextField(blank=False, null=True) amount = models.IntegerField(blank=False, null=True) avg_rating = models.DecimalField(blank=True, max_digits=2, decimal_places=1, null=True) total_rating = models.IntegerField(blank=False, null=True) is_delete = models.BooleanField(default=False, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) I want to convert sql query: select * from Product where product.is_delete=0 and company_id = 1 and company.is_delete = 0 to code query in django Please help me! Thank you -
Displaying one record from one to many table for each user in user list
I have a list of users. Every user has a contract history, all contracts stored in same table. Every user has 1 contract that is currently active. I'm trying to display some details from the currently active contract in the user list. Model: class Contract(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) contract_start = models.DateField(null = True, blank = True) contract_end = models.DateField(null = True, blank = True) View: def get(self, request): users = User.objects.all() date_today = timezone.now().date() active_contract = Contract.objects.filter(contract_start__lte=date_today, contract_end__gte=date_today) return render(request, 'user/list.html', { 'users': users, 'active_contract': active_contract, }) Template: {% for user in users %} <tr> <td>{{ user.last_name }}</td> <td>{{ user.first_name }}</td> <td>{{ user.employee.location }}</td> <td>{{ ?? }}</td> </tr> {% endfor %} In an other view where there is one user, I can add user_id = id to the filter and I can display the details that I want. I can't seem to get this to work in my user list though. -
Turnkey Django throwing 404 with altered apache config file
I am setting up a Turnkey Django solution and it works perfectly fine if you use the pre-built Django project they provide. But it's a pain to work with and breaks many of the rules and guidelines in the Django documentation and includes so much bloat that it breaks the moment you upgrade or install a new package. So I am trying to setup it up so that I can make my own Django project from the ground up with my own file paths. All my databases, dependencies, packages and Django files are in working order within a virtualenv but when I go to edit my Apache config file with my custom directories it throws a 404. Here is what I am using and the versions: PuTTy, SSH into the server (Windows 10 --SSH-> Linux) virtualenv, contains the Django project and several packages Django (2, 1, 6, 'final', 0) Python 3.6.8 Turnkey GNU/Linux 9.6 sql_server.pyodbc with ODBC Driver 17 for SQL Server for MSSQL Note: In Turnkey Django the Apache config files is a little different from standard Apache. 000-default.conf does nothing in Turnkey Django. So when I change django.conf in /root/etc/apache2/sites-available from the defualt: serverName localhost WSGIScriptAlias / /var/www/turnkey_project/turnkey_project/wsgi.py … -
Is this a valid approach to sharing a function between Python classes?
My goal is to use the same function from multiple classes in Python. I've seen discussion about mixins and inheritance etc but they all seem to come with caveats and cautions about doing things just right. So I wondered if I could just call another plain old function that lives outsides the classes. It seems to work, but maybe I'm failing to understand something important? So my question is - is this a valid approach to sharing a function between Python classes? def clean_reference_url(self): if not self.cleaned_data['reference_url']: return '' try: if 'illegaltext' in self.cleaned_data['reference_url']: raise Exception except: raise forms.ValidationError('You cannot put illegaltext in this field.') return self.cleaned_data['reference_url'] class ContactForm(forms.ModelForm): def clean_reference_url(self): return clean_reference_url(self) class TripForm(forms.ModelForm): def clean_reference_url(self): return clean_reference_url(self) -
ImportError: cannot import name url
I'm upgrading a django app from v1.3 to 1.11.18. We are running Python v2.7.12 and running an nginx server to serve the pages. I've been making code changes to account for all of the deprecated methods as a result of the upgrade. So far, so good. After making another run of updates, I ran into this error notice after starting the server: File "/home/bat/application.com/wsgi.py", line 12, in <module> application = get_wsgi_application() File "./django/core/wsgi.py", line 14, in get_wsgi_application return WSGIHandler() File "./django/core/handlers/wsgi.py", line 151, in __init__ self.load_middleware() File "./django/core/handlers/base.py", line 56, in load_middleware mw_class = import_string(middleware_path) File "./django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "./django/middleware/locale.py", line 4, in <module> from django.conf.urls.i18n import is_language_prefix_patterns_used File "./django/conf/urls/i18n.py", line 2, in <module> from django.conf.urls import url ImportError: cannot import name url I'm not sure why I would be getting this error as the code referenced is all core code. It doesn't appear to be referencing any of the project code at all, except for the opening line. I've double-checked to be sure we do not have any "left over" code sitting in the core django folder: it's clean. We also rebooted the linux server just … -
How to upload image as base64 in django-rest? i converted but. image still saves as regular image
so here i am trying to convert it and then passing to the post request. Although i can send the image and the image is being converted the string it does not save into the database or send into the API def create(self, validated_data): #image_to_encode = validated_data['image'] #encoded_string = base64.b64encode(image_to_encode.read() ) #print(encoded_string) return Evento.objects.create(**validated_data) this is part from my serializer -
Django 2.0 server error occurred. Please contact the administrator " Error:UnicodeDecodeError
I have a small issue with Django and it's when I make run python manage.py runserver to the server I show this error in CMD : 1 and in Browser : server error occurred. Please contact the administrator Note : I run this project on virtualenv and I don't write any code on this project . How i can fix that :) Thank you . file : settings.py DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
How to make customize able django templates
How do I make django templates customize able? Basically a template where users can change the look and layout easily like wordpress or shopify allows users to do. I have some ideas but they all seem to involve using django forms and then updating the template with a POST.get request, I'm very sure this isn't the best way to do this. I also tried using wordpress themes directly with django but that didn't work, word-press is built on php. -
React/Webpack/Django - Uncaught TypeError: Cannot read property 'XXX' of undefined
I am trying to create a React component called 'Proposals' that will render a tabular list of information received from the Django backend. I am using the Reactable-Search component to form the table, but I've kept getting an error when I try to map the this.props.proposals values such as id, and proj_name to the table cells - Uncaught TypeError: Cannot read property 'cells' of undefined Really not sure why because when I map this.props.proposals directly in the render return of a typical html table tags it is working i.e. rendering the backend data ok. and I've also used the Reactable-Search component with the mapping in other cases and it's worked fine. Really appreciate if someone can nudge me in the right direction, thanks! The Proposals component: import React, { Component } from "react"; import { connect } from "react-redux"; import SearchTable from "reactable-search"; import { proposals } from "../actions"; class Proposals extends Component { componentDidMount() { this.props.fetchProposals(); } constructor(props) { super(props); this.state = {}; } render() { var rows = this.props.proposals.map(p => ({ selected: this.state.selectedRow === p.id, onClick: () => { this.setState({ selectedRow: p.id }); }, cells: { "#": p.id, "Project Name": p.proj_name } })); return ( <SearchTable showExportCSVBtn={true} searchPrompt="Type … -
Django: Formset doesn't save as entry already exists
I have a formset that faces one of these situations. 1) No database entry exists. New entry for each 'form' is made. 2) Database entry exists, but will be updated. 1) Works with my code, I attached here. 2) Doesn't work. I always receive the error 'already exists'. (It's okay that it already exists, but in that case it should just update the entry, instead of showing me an error) Anyone who can help me? forms.py class SocialTixForm(forms.ModelForm): class Meta: model = SocialTix fields = ( 'coin_mode', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for visible_field in self.visible_fields(): visible_field.field.widget.attrs['class'] = 'form-control' class SocialTixCoinAllocationForm(forms.ModelForm): class Meta: model = Coins fields = ( 'ticket', 'coins', ) views.py class AdminIncluencerPreferences(AdminPermissionRequiredMixin, AdminBaseAmbassadorView, TemplateView): """ This view will show the ambassador preferences """ template_name = 'influencer/admin/preferences.html' success_message = _("Settings have been successfully created.") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['social_form'] = self.social_form context['social_coin_allocation_formset'] = self.social_coin_allocation_formset return context @cached_property def social_form(self): return SocialTicketingForm( instance=self.request.event.event_extension, data=self.request.POST or None, ) @cached_property def social_coin_allocation_formset(self): CoinAllocationFormset = formset_factory( SocialTicketingCoinAllocationForm, extra=0 ) return CoinAllocationFormset( data=self.request.POST or None, initial=self.request.event.tickets.tickets_as_list(), ) @transaction.atomic def post(self, request, *args, **kwargs): if (self.social_form.is_valid() and self.social_coin_allocation_formset.is_valid()): self.social_form.save() self.social_coin_allocation_formset.save() models.py class Coins(TimeStampedModel): ticket = models.OneToOneField( Ticket, on_delete=models.PROTECT, related_name='coins', ) … -
Wagtial: How to properly rename a wagtail page model
There are two existing wagtailpages models I'd like make changes to - "MyModelName" and "NewName". My goals are to remove "MyModelName" model and make "NewName" the new "MyModelName" I was able to get Goal #1 working but have been stuck for Goal #2. What I tried for Goal #2 (renaming a model) Updated occurrences of "NewName" in files under /wagtailpages directory to "MyModelName". Ran makemigrations / migrate Ran runserver However, when I visited Wagtail admin interface I got errors [2019-01-22 23:20:26,344] [ERROR] Internal Server Error: /cms/ Traceback (most recent call last): File "/.../python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/.../python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) [...snip...] File "/.../python3.6/site-packages/django/db/models/query.py", line 1121, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/.../python3.6/site-packages/wagtail/core/query.py", line 397, in specific_iterator yield pages_by_type[content_type][pk] KeyError: 278 It seems like something didn't get updated automatically by Django's built-in migration handling. I couldn't tell what steps I'm missing here so would love to get some help. Thanks! -
Python script in sublime text 3
Hey i am new to programming, and i have a question: I have sublime text 3 set up with python and running though Django i think so that i can see it in my web browser. But i just made my first python script in a new file in sublime text and i can preview it by pressing Ctrl:b and it looks fine, but i don´t know how to include it into my other html site, and when i try to copy it in, it looks like i cant do both html and python in one file? Anyone knows what i do wrong? thanks in regards