Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use dynamic value is URL description
I am trying to print some links using a list items in a jinja for-loop, but am failing to properly pass dynamic values into the url function {% for item in items %} <li> <a href="{% url 'my_namespace:{{item.href}}' {{id}} %}"> {{ item.name }} </a> </li> {% endfor %} Using the {{ }} syntax will get an error like Could not parse the remainder: '{{id}}' from '{{id}}' And leaving them out (which feels slightly more correct because I am already in the jinja <% %> block) gets an error like: Reverse for 'item.href' with arguments '(u'1',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I am trying to emulate this working hardcoded URL, so this is what I am basing my attempt off of. <a href="{% url 'my_namespace:my_route' id %}"> Where above my item.href would contain the value my_route How can I get this dynamic content into the url method to render the href correctly? -
List models containing foreign key in a detail view
I would like to have a Django detail view that shows all the models containing a foreign key for the detail view page for that foreign key value, linked from a list view. The model ActivityID contains a list of character id's (e.g. 'F1088HW'). There are several other models, each containing the contents of a storage facility, and each item has an ActivityID. So when F1088HW is clicked on, for example, a detail page should show all the facilities that has stuff from that ActivityID. So far I have the following view based on various other SO questions: class ActivityDetailView(generic.DetailView): model = ActivityID context_object_name = 'library_set' def get_queryset(self): pk = self.kwargs['pk'] return models.objects.filter(activityid = pk) And ActivityID_detail.html: {% extends "base_generic.html" %} {% block content %} <h1>Field Activity ID: {{ activity }} </h1> <div style="margin-left:20px;margin-top:20px"> <h4>Libraries</h4> <dl> {% for library in activity.library_set.all %} <dt><a href="{% url 'activity-detail' library.pk %}">{{library}}</a> ({{library.library_set.all.count}})</dt> {% endfor %} </dl> </div> {% endblock %} But clicking on an ActivityID in the list view then returns: AttributeError at /catalog/activities/2429 module 'django.db.models' has no attribute 'objects' Any idea what I'm doing wrong? -
Apache/Django/mod_wsgi - [Errno 13] Permission denied:
I am using Django + Apache + mod_wsgi and defined two applications: a test one - 'polls' and 'forecast'. Suddenly I got into a problem when I try to access from Django server the index.html (main) page of 'forecast' app - I get the error 'permission denied'. Initially everything worked fine and I do not identify an error which I made. To mention that the access to 'polls' app which is located into same project and directory 'myproject' works fine. ===error 'forecast' app ==== [Errno 13] Permission denied: '/home/florian/workdev/myproject/upload/index.html' Request Method: GET Request URL: http://localhost:8000/forecast/ Django Version: 2.1.4 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: '/home/florian/workdev/myproject/upload/index.html' Exception Location: /home/florian/workdev/venv/lib/python3.5/site-packages/django/template/loaders/filesystem.py in get_contents, line 23 Python Executable: /home/florian/workdev/venv/bin/python Python Version: 3.5.2 Python Path: ['/home/florian/workdev/myproject', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/florian/workdev/venv/lib/python3.5/site-packages'] Server time: Wed, 19 Dec 2018 18:57:44 +0000 Any idea?? -
django-ckeditor doesn't appear in inline models in Django
I'm trying to use django-ckeditor in my Django admin with django-grappelli. Like you see the image below, I'm using StackedInline for inline models. The problem is if I add a new inline model, then django-ckeditor doesn't appear, but if I save the inline model, then django-ckeditor appears. I don't think there is a problem for configuring django-ckeditor as it appears well when the inline model is saved. ckeditor doesn't appear only when a new form is added for a new inline model. I've already seen some similar issues on django-ckeditor github, but it was years ago, and it seems like they already solved them. However, for me the issues still shows up. Does anyone have idea for this? admin.py class StoreInline(admin.StackedInline): model = Store form = StoreForm ... @admin.register(Article) class ArticleAdmin(ImportExportModelAdmin): inlines = (StoreInline, ) ... forms.py class StoreForm(forms.ModelForm): description = forms.CharField(widget=CKEditorWidget()) class Meta: model = Store fields = '__all__' -
python django-import-export import model data even if there are not data
I'm using django-import-export package to import data from a csv file, basically following the getting started tutorial in readthedocs I'm confused with a behavior of the package in a simple configuration. My model is like: class Experiment(models.Model): title = models.CharField(max_length=255, blank=False) description = models.TextField(blank=False) research_project = models.ForeignKey( ResearchProject, null=False, blank=False ) I created a csv file to test import. The file /tmp/experiment.csv is simple: h1,h1,research_project v1,v2,66 (Note that the first two columns of csv have headers that not correspond to any of the fields models) Then, I created a Resource: class ExperimentResource(resources.ModelResource): class Meta: model = Experiment exclude = ('id', ) def export(self, queryset=None, *args, **kwargs): queryset = Experiment.objects.filter(id=kwargs['id']) return super(ExperimentResource, self).export(queryset, *args, **kwargs) def get_instance(self, instance_loader, row): return False Now, I can try to import /tmp/experiment.csv data, by calling: dataset = Dataset().load(open('/tmp/experiment.csv').read()) result = ExperimentResource().import_data(dataset) print(result.has_errors()) # for debug Last line prints False, as data has effectively imported and a line has added to the database. But title and description was filled with an empty string, even if in Experiment model this two attributes have blank=False. My questions are: why django-import-export allows saving empty strings for models that have fields with blank=False parameters? And why the package do not … -
How do I pass a variable from one django view to another if the variable wasn't saved to the database
I want to pass a variable from my home view to my offer view but I do not want to save the values from my home view to the database. How would I go around doing that? I've tried calling it in the sessions and also tried requesting it from the home variable which doesn't work but even if it does I keep getting a NoneType. Please note that I do not want to save any of the variables from the home function, I would just like to pass them over to the offer function. The variables I am trying to pass over are brand and model. def home(request): if request.method == 'POST': form = ContactForm(request.POST) posts = CustomUser.objects.all() if form.is_valid(): print(posts) #form.save() -- this is what is used to save the form unquote this to save form to custo user form = ContactForm() brand = request.POST.get('brand').upper model = request.POST.get('model').upper brandquote = str(brand) modelquote = str(model) args = {'form': form, 'posts':posts,} url1 ='https://www.ebay.com/sch/i.html?_from=R40&_sacat=0&LH_BIN=1&_nkw=' url2= '&_dcat=9355&rt=nc&LH_ItemCondition=3000' url = (url1 + str(request.POST.get('brand')) + '+' + str(request.POST.get('model')) + url2) source = requests.get(url).text print(url) soup =BeautifulSoup(source, 'lxml') total_price = 0 for post in soup.find_all("li",{"class" : "s-item"}): price = post.find_all("span", {"class" : "s-item__price"})[0].text price2 = … -
django-pyodbc-azure SQL Server Parameter Limitation
I am using django-pyodbc-azure as my Django backend. It is connecting to SQL Server 2012. SQL Server has a limit of 2,100 parameters. When I attempt to use prefetch_related on a queryset that will return more than 2,100 results... def object_search_list(request): objects = MyModel.objects.filter(some_field='filter value').select_related('another_field').prefetch_related('a_third_field') print(objects) return render(request, 'objects/object_list.html', {'objects':objects}) ...this error is returned: Exception Value: ('07002', '[07002] [Microsoft][SQL Server Native Client 11.0]COUNT field incorrect or syntax error (0) (SQLExecDirectW)') It points to the pyodbc backend used by django-pyodbc-azure. When looking at the features (https://github.com/michiya/django-pyodbc-azure/blob/azure-2.1/sql_server/pyodbc/features.py), there is no max_query_params set. I attempted to manually add max_query_params = 2100. This resulted in the same error. Setting that value to 2000 and 1000 resulted in the same error also. How do I adjust django-pyodbc-azure to automatically handle this SQL Server limitation? -
Django:error using get_or_create and unique_together
I'm creating an API which list and save transactions. My Transactions Model has a FK to a Category model. My goal when creating a Transaction is to also create the Category if the category is new. The first time I create the transaction it works. The next time I get an error that the category already exists. In my Transaction serializer I added a create method that should be using get_or_create to create the category. However I'm getting an error on my unique fields. My expectation is that it would be returning the existing Category. It seems like it's throwing the error before it gets to the create method in the Transaction serializer before it has a chance to use get_or_create Models: class Category(models.Model): name = models.CharField(max_length=128, null=False) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_time = models.DateTimeField(auto_now_add=True) modified_time = models.DateTimeField(auto_now=True) class Meta: unique_together = ('name', 'owner') class Transaction(models.Model): date = models.DateField() payee = models.CharField(max_length=256) category = models.ForeignKey(Category, related_name='category', on_delete=models.CASCADE) amount = MoneyField(max_digits=19, decimal_places=2, default_currency='USD') created_time = models.DateTimeField(db_index=True, auto_now_add=True) modified_time = models.DateTimeField(auto_now=True) Serializers: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name', 'owner', 'created_time', 'modified_time') class TransactionSerializer(serializers.ModelSerializer): balance = serializers.DecimalField( decimal_places=2, max_digits=19, read_only=True) category = CategorySerializer(many=False, read_only=False) class Meta: """Meta class … -
Django - SuspiciousFileOperation from image add on local development environment
I've been working on a personal photo website built on Django for the last several months and successfully deployed it with AWS. Til now I've done all my development on my Windows 10 desktop. I recently got a new Windows 10 laptop and have gotten stuck setting up a dev environment on it. I cloned my Github repo to my laptop and successfully gotten the site to run locally. However when I go to the admin page to upload a photo and every time I get a SuspiciousFileOperation exception. The joined path is located outside of the base path component. I've also gotten this error when running collectstatic. The settings are identical to my desktop setup, unless I'm overlooking an issue staring right at me. I think it might have something to do with the way I set up the virtualenv or how my MEDIA variables are set up, though they are the same as what works on my desktop. I've read through the Django documentation but haven't found anything definitive. Or maybe someone could explain a bit more about setting up virtualenv? Does Django/Python meed certain permissions I missed setting up on my laptop to move files around? Below … -
Retrieving the result of a task in Celery
I have a long running task in my Django application, and would like to display a progress bar and then output the task result to the user when finished. I've found easily how to start the task and produce a progress bar via messaging, but how do I retrieve the results from the task once it's finished and display these to the user? Using Redis as my message broker. -
Django testing an update post
I receive this message "feed.models.Post.DoesNotExist: Post matching query does not exist." I believe it to be in the UpdatePost class I dont understand as there is a post created with an id of one. Why is this? from django.test import TestCase, SimpleTestCase from django.contrib.auth.models import User from django.urls import reverse from feed.models import Post class Setup_Class(TestCase): def setUp(self): self.user = User.objects.create_user(username='jtur', email='jtur@accenture.com', password='onion') user = User.objects.first() Post.objects.create(title='test', content='more testing', author=user) class PostTests(Setup_Class): def test_content(self): post = Post.objects.get(id=1) expected_post_title = f'{post.title}' expected_post_content = f'{post.content}' self.assertEquals(expected_post_title, 'test') self.assertEquals(expected_post_content, 'more testing') def test_post_list_view(self): response = self.client.get(reverse('feed-home')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'more testing') self.assertTemplateUsed(response, 'feed/home.html') class UpdatePost(Setup_Class): def test_post_update(self): post = Post.objects.get(id=1) post.title = "This has been changed" expected_post_title = post.title self.assertEquals(expected_post_title, 'This has been changed') -
django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG
I am beginner in Python Django. My Django project were running correctly. But I do not know when I run command django-admin runserver I am getting below error Please help me what went wrong suddenly.? It happens in all Django Projects. How to solve this? django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Django Multiple join operations
I have the following model with tables related through a Many-to-One Relationship. class Reading(models.Model): reading = models.AutoField(primary_key=True) client_connection = models.ForeignKey(ClientConnection, models.DO_NOTHING, db_column='client_connection', blank=True, null=True) consumption = models.ForeignKey(Consumption, models.DO_NOTHING, db_column='consumption', blank=True, null=True) date = models.DateField(blank=True, null=True) class Client(models.Model): client = models.AutoField(primary_key=True) zone = models.ForeignKey('Zone', models.DO_NOTHING, db_column='zone', blank=True, null=True) code = models.CharField(unique=True, max_length=255, blank=True, null=True) order = models.IntegerField(blank=True, null=True) full_name = models.CharField(max_length=255, blank=True, null=True) class Zone(models.Model): zone = models.AutoField(primary_key=True) description = models.CharField(max_length=255, blank=True, null=True) code = models.CharField(unique=True, max_length=255, blank=True, null=True) Using Django ORM's select_related() I can create a QuerySet that will follow the foreign-key relationship selecting additional related-objects as follows. def client_meters(request): query = Reading.objects.filter(date__gte=datetime.date(2018,10,31)).select_related('client_connection__client__zone').all() c_c = query.client_connection However, I get the error c_c = query.client_connection AttributeError: 'QuerySet' object has no attribute 'client_connection' What am I missing. -
page not found error in Django using a filter query {return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')}
I am making my first django practice project I have a view called PostListview : from django.shortcuts import render from django.utils import timezone from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from blog.models import Post, Comment from blog.forms import PostForm,CommentForm from django.urls import reverse_lazy from django.views.generic import(TemplateView,ListView,DetailView,CreateView,UpdateView, DeleteView) class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') I have this in in the urls: from django.conf.urls import url from blog import views urlpatterns = [ url(r'^$',views.PostListView.as_view(), name= 'post_list'), And this is the template which is calling this view. <li class="navbar-brand bigbrand" ><a href="{% url 'post_list %'}">My Tech Blog</a></li> This view is also set as the default home view and it opens fine at the time i open the site url (localhost) but when I am clicking "My Tech blog " it gives a 404 error. -
Django over Docker does not install mysqlclient
I want to integrate MySQL with Django, MySQL is running over Docker and I put the config like this to connect to the db docker with Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'restaurant', 'HOST': 'db', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'root', 'default-character-set': 'utf8', 'OPTIONS': { 'init_command': 'SET default_storage_engine=INNODB', } } } But when Django is trying to connect to the mysql db, it throws me this error: I tried to install mysqlclient with pip, but I have this error: These are the docker-compose.dev.yml and Dockerfile configs. If someone needs the complete code, here you can find it, and test it with docker-compose -f docker-compose.dev.yml up --build. Thanks :). -
Django rest framework urls
I'm structuring a Django API with rest framework, I read the docs and DRF only makes a crud (get, post, patch, delete) from a model. Now the deal is how I can make custom actions with DRF. Example: api/v1/model/custom_action Code: class DistrictViewSet(viewsets.ModelViewSet): queryset = District.objects.all() serializer_class = DistrictSerializer def custom_action(request, param): # do many actions and return as Json Object urls.py url(r'api/v1/', include(router.urls)) Where router router.register(r'model',api.ModelViewSet) I'm correct with this or I need to create another modelview, customize the code and add it to router list? -
Redirect a user ater connecting
Goal I have a system which forces the user to change their password after x time. After the length of time is satisfied, I need to redirect the user to the change password page, and ensure they do not have access to other parts of the website until their password is changed. Current implimentation Currently, I am using a recviever like so, located in profile/models.py def does_password_need_changing(request, **kwargs): date_string = Profile.objects.get(user=request.user).last_password_change if date.today() - date_string > timedelta(days=90): print 'test' return redirect('https://google.co.uk') else: print 'in date' print(date_string) user_logged_in.connect(does_password_need_changing) The problem Currently, I can get the user to log in, and the logic behind the date checking works. I cannot redirect the user, I've also attempted to use HttpResponseRedirect, but have not had success thus far. -
How do I refactor this django rest framework endpoint?
I have a POST endpoint that accepts instead of array of keys an object that has key ids, like this { car: { id: 'a' }, passengers: [ { id: '123' }, { id: '34' }, ] ... } this feels silly, as I'd expect api to accept shape like this: { car: 'a', passengers: [ '123', '34'] ... } I am trying to change the endpoint but I don't know python or django and I can't figure it out. Help would be much appreciated The change feels trivial if you know how to use django rest framework here is the code def create(self, validated_data): passengers_data = validated_data.pop('passengers') car_data = validated_data.pop('car') car = Car.objects.get(pk=car_data['id']) passengers = Passenger.objects.filter( id__in=[p['id'] for p in passengers_data], ).all() with transaction.atomic(): drive = Drive.objects.create( **validated_data, driver=self.context['driver'], car=car, ) drive.passengers.set(passengers) drive.save() drive_created.send( self.__class__, drive_id=drive.id, driver_id=self.context['driver'].id, passengers_ids=[p.id for p in passengers], ) return drive -
Django Heroku Robots.txt Exclude from Production Pipeline
I am testing out Pipelines on Heroku. I have a staging app and a Production app in a pipeline and I had two issues which arose at the same time, and so may or nor may not be interrelated.... The first was how to run commands from my CLI on both my staging and production app. [This partially][1] answered my question but not entirely. I found the solution was to set my [staging app as the default][2]: git config heroku.remote staging Then to run my production apps commands I can run a command like so: heroku run python manage.py createsuperuser -a, --app your-app-name The other issue which seems to have a [solution for Ruby][3] is how to control my robots.txt from staging to production. I want my staging app to be hidden from Google etc. but I don't want this to be transferred over to my production app (of course). Perhaps I shouldn't be using robots at all? Any help would be appreciated... -
Is a django project only meant to be for a single website or can the different apps be different sites. What is perferable and advisable?
I have been using django for a while, but there is something im not quite clear on. How big should a django app be. If for example a django app should only be user authentication or if it should be an entire website in one app. If I have a project with several apps and each app is a whole website with a lot of code, is that the way it suppose to be or should all apps related to a single site within a project ? Im thinking of creating one django project for each site, but im now wondering if I should be creating one project where each app is one site. Can anyone please comment on this, what it the preferred way to do it ? In the django documentation one app is only used for a poll, so it seems to be that, according to the documentation, that each app should be some part of functionality on the site. -
"Need a valid file name!" xhtml2pdf with Django
My problem is: I am creating a pdf file from an html, using the xhtml2pdf library. Having created the pdf file, I send the file to the user via email using the sendgrid API. However, I am not able to leave an image embedded in the pdf file, since the application returns me a "Need a valid file name!" Message. I've researched in several places but I can not find a solution. The code used is below. HTML code: <img src="/static/media/logo.jpg" alt="Image"> python code (convert html to pdf): def link_callback(uri, rel): """ Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources """ # use short variable names sUrl = settings.STATIC_URL mUrl = settings.MEDIA_URL mRoot = settings.MEDIA_ROOT # convert URIs to absolute system paths if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) else: return uri # handle absolute uri (ie: http://some.tld/foo.png) # make sure that file exists if not os.path.isfile(path): raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl) ) return path def render_to_pdf(template_source, context_dict={}): from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa template = get_template(template_source) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, … -
Partitions size for install Ubuntu or Mint on SSD+HDD
I will try to install Ubuntu or Mint on my notebook (i5, 8 Gb RAM). I have 120 Gb on SSD and 500 Gb on HDD. Please help me for partitions size on SSD and HDD. I will learn FullStack development via Python (Django and Flask). Thank for help! -
TypeError: initialize() got an unexpected keyword argument 'bytes_mode'
I have recently configured django on apache using modwsgi. It works fine when I disable authentication on my application. But, it gives below error when authentication is enabled. I am using django_auth_ldap module for authentication purpose. I am using Python 2.7, Django 1.11.15 and apache 2.4.6 version. Error logs:- [Wed Dec 19 14:23:30.351155 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] python version [Wed Dec 19 14:23:30.351187 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] 2.7.5 (default, Oct 30 2018, 23:45:53) [Wed Dec 19 14:23:30.351260 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] [Wed Dec 19 14:23:30.351290 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] django version [Wed Dec 19 14:23:30.351390 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] 1.11.15 [Wed Dec 19 14:23:30.359768 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] Internal Server Error: /login/ [Wed Dec 19 14:23:30.359839 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] Traceback (most recent call last): [Wed Dec 19 14:23:30.359855 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner [Wed Dec 19 14:23:30.359864 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] response = get_response(request) [Wed Dec 19 14:23:30.359874 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response [Wed Dec 19 14:23:30.359883 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] … -
Where to keep long hardcoded data for initial migration in Django?
I want to create two models something like this: class LogActions(models.Model): name = models.CharField(default='-') text = models.TextField() class Logs(models.Model): user = models.ForeignKey(User) log_message = models.ForeignKey(LogActions) date = models.DateField(auto_now_add=True) price = models.CharField(default='-', max_length=20) In LogActions there will be stored user actions. Example: Action one: name = 'USER_POINT_ADDED' text = 'User {user} added point to bla bla bla (long text...)' There will be like 20 actions, names of this actions will be short, but texts are very long. I don't know where to store all the initial data for migration... This data should be available through all project life. I want to create dict like: log_actions = { 'USER_POINT_ADDED': 'User {user} added... <verylongtexthere>', 'USER_POINT_EDITED': '<verylongtexthere>', 'USER_POINT_DELETED': '<verylongtexthere>', 'USER_GROUP_ADDED': '<verylongtexthere>', } All dicts like this above I hold in django settings.py file, but there are small and adding such a unclear hardcoded code to settings.py seems to be bad... but i need it for initial migration. I'm Junior Dev are there any good habits in Django to store big hardcoded data that is needed to initial migration on new pc/server? Did you met this kind of problem? How did you solve it? -
How To Capture All Templates And Static Files Before They're Sent To Client
In Django >= 1.11, how would I go about capturing the rendered HTML templates and statically served files to make programmatic changes to them before they are sent to the client? I had made a custom "render" function, but soon realized that this only works on rendered templates and not static files. I would like to capture all files served over the server, not just rendered ones. How would I go about doing this?