Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
passing form arguments in django
I am trying to implement a simple search function in django but somehow I can't pass the argument from my template to my view function. I've got a key error: KeyError at /artdb/search/ because kwargs is empty: url.py: path('search/',views.Search.as_view(),name='search'), base,.html: <form class="form-inline my-2 my-lg-0" name="search" action="{% url 'artdb:search' %}" {{ form.as_p }} method="get">{% csrf_token %} <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" value="{{seastr}}"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" value="{{seastr}}">Search</button> </form> views.py: class Search(ListView): print("class Search") model=Person template_name='artdb/search.html' context_object_name='ans' def get_queryset(self): Pdb().set_trace() self.seastr=get_object_or_404(Person,name=self.kwargs['seastr']) return Person.objects.filter(seastr=self.seastr) -
Django using an object in an ORM query, within its __init__ function
I have a model which exists only to combine a number of other models. There are a series of 'payable' objects, with need to be clubbed together into a 'payment' object, called 'ClubbedPayment'. The model is given a list of payable objects, and it uses them to calculate various attributes. This works fine, so far. These payable objects have a foreign key to ClubbedPayment. Rather than going through the payable objects and adding the new ClubbedPayment object to each of them as a foreign key, it seems easier to add them to ClubbedPayment.payable_set(). I've tried to do this, but it fails because in the __init__ function, the ClubbedPayment object is not yet saved: class ClubbedPayment(models.Model): recipient = models.ForeignKey(User, on_delete=models.PROTECT) paid_at = models.DateTimeField(null=True) is_unpaid = models.BooleanField(default=True) total = models.DecimalField(max_digits=6, decimal_places=2) payment_id = models.UUIDField(null=True, editable=False) response = models.CharField(null=True, max_length=140) payment_type = models.CharField(max_length=2, choices=PAYMENT_TYPES) def __init__(self, *args, **kwargs): super().__init__() objects = kwargs["objects"] recipients = set([x.recipient for x in objects]) types = set([type(x) for x in objects]) if len(recipients) > 1: raise Exception("Cannot club payments to more than one recipient") self.total = sum([x.total for x in objects]) self.recipient = list(recipients)[0] for x in objects: self.payable_set.add(x) Now, I know that overriding __init__ with non optional … -
Best practice for defining default app settings for custom django module?
Is there a defined best practice for defining custom settings that come with a django app. What I have at the moment is a separate file called app_settings.py that looks like this: from django.conf import settings # MY_SETTING_1 is required and will brake the application if not defined try: MY_SETTING_1 = str(getattr(settings, 'MY_SETTING_1')) except AttributeError: raise ImproperlyConfigured ('MY_SETTING_1 not defined in settings.py.') # MY_SETTING_2 is not required and has a default value MY_SETTING_2 = getattr(settings, 'MY_SETTING_2', ['default_value']) Then I am importing this in my views.py, and using it like this: from my_app import app_settings print (app_settings.MY_SETTING_1) print (app_settings.MY_SETTING_2) This works ok, but I am not quite happy with the design. I am assuming that I can somehow use the class defined in apps.py, but I am not sure how. Is there a best (or better) practice for this? -
Response ZIP file by Django
I try to download img from url, add it to zip archive and then response this archive by Django HttpResponse. import os import requests import zipfile from django.http import HttpResponse url = 'http://some.link/img.jpg' file = requests.get(url) data = file.content rf = open('tmp/pic1.jpg', 'wb') rf.write(data) rf.close() zipf = zipfile.ZipFile('tmp/album.zip', 'w') # This file is ok filename = os.path.basename(os.path.normpath('tmp/pic1.jpg')) zipf.write('tmp/pic1.jpg', filename) zipf.close() resp = HttpResponse(open('tmp/album.zip', 'rb')) resp['Content-Disposition'] = 'attachment; filename=album.zip' resp['Content-Type'] = 'application/zip' return resp # Got corrupted zip file When I save file to tmp folder - it's ok, I can extract it. But when I response this file I get 'Error 1/2/21' on MacOS or Unexpected EOF if I try to open in Atom editor (just for test). I also used StringIO instead of saving zip file, but it doesn't influence the result. -
Intertwined problems with Django Time fields force hacks to edit/display time
Django 2 There's alot of info here. I'll try to summarise the essence of the issues. Background fact: Setting a default for a Time field requires that a datetime.time be set in the model reference: https://code.djangoproject.com/ticket/6754 There are two problems here that are related. Problem 1: the data type of the time field changes First problem is that the initial GET of the Django page below returns a time field with a data type of <class 'datetime.time'>. This is fine and expected. BUT If you submit that form via POST, and there is a field validation error, then the data type of the Time field CHANGES to a string. Have a look at the server log at the bottom of this question to see. As a consequence, the format os the data changes too - note that the seconds are dropped. This can also be seen in the server log below. This leads to problem 2: Problem 2: Django's time formatting tag returns None when there are no seconds on the data passed into it. In the HTML template below you can see the line containing: time:'H:i' This is a formatting tag, which accepts a time and it should output … -
How to handle JSON Decode Error without getting Django typical html error in Python
I have Django application running. When I'm sending POST request with nothing in it or with wrong JSON I want to handle the error myself. But Django gives me html page with error rather than my custom try except block. Here is my code: if request.method == 'POST': temp_request = request.body if not isValidJson(temp_request): return JsonResponse({"Error": "Error"}) def isValidJson(received_json): try: json.loads(received_json) except ValueError as e: return False return True And I'm getting Django html error page with Json Decode Error than JsonResponse