Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
404 error for static files in console with Django and Heroku
I am able to run collectstatic fine when I push to Heroku. The problem now is I that I'm not sure how to reference them when they're stored on the server. For example for my stylesheets I get a 404 error: <link rel="stylesheet" type="text/css" href="/static/bower_components/bootstrap-material-design/dist/css/material.css" /> This is the URL that is causing the 404:https://tixblast-membership.herokuapp.com/static/bower_components/bootstrap-material-design/dist/css/material.css What part of my settings to I alter to make sure I look in the right place? I ran heroku run python manage.py findstatic --verbosity 2 css/styles.css to show where it was looking for static files and it returned: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/admin/static /app/.heroku/python/lib/python3.7/site-packages/rest_framework/static So do I need to include one of the above directories in my settings? I assumed that after I got collectstatic working I'd be fine, here is my settings.py: """ Django settings for thinkster_django_angular_boilerplate project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import django_heroku PROJECT_DIR = os.path.dirname(__file__) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ***** # SECURITY WARNING: don't … -
Django Rest Framework view to return created files
I have a ViewSet in DRJ that creates several files with python-docx in the server, and I want that view to return such files. This is the code of my view: class RoomingWordView(viewsets.ViewSet): def list(self, request, *args, **kwargs): from ReportsManagerApp.controllers import RoomingReportController start_date = request.query_params['start_date'] end_date = request.query_params['end_date'] confirmed = request.query_params.get('confirmed', None) try: agencies = request.query_params['agencies'].split(",") except: agencies = None try: cities = request.query_params['cities'].split(",") except: cities = None try: hotels = request.query_params['hotels'].split(",") except: hotels = None rooming_report_controller = RoomingReportController(start_date, end_date, confirmed, agencies, hotels, cities) context = rooming_report_controller.get_context() documents_to_return =[] for hotel, bookings in context['hotels'].items(): documents_to_return.append(self.get_hotel_document(start_date, end_date, confirmed, hotel, bookings)) return Response(documents_to_return) def get_hotel_document(self, start_date, end_date, confirmed, hotel, bookings): from docx import Document from docx.shared import Inches, Pt document = Document() section = document.sections[-1] section.left_margin = Inches(0.5) section.right_margin = Inches(0.5) style = document.styles['Normal'] font = style.font font.name ='Arial' font.size = Pt(10) document.add_heading("EUROAMERICA TTOO INC") if confirmed: document.add_paragraph("ROOMING LIST DEL 01-12-2018 AL 31-01-2019 INCLUYE RESERVAS CONFIRMADAS") else: document.add_paragraph("ROOMING LIST DEL 01-12-2018 AL 31-01-2019") document.add_paragraph("Hotel: {}".format(hotel)) table = document.add_table(rows=len(bookings), cols=10) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Booking' hdr_cells[1].text = 'Reservado a' hdr_cells[2].text = '# Pax' hdr_cells[3].text = 'Agencia' hdr_cells[4].text = 'Habs' hdr_cells[5].text = 'Hab./Plan' hdr_cells[6].text = 'Entrada' hdr_cells[7].text = 'Salida' hdr_cells[8].text = 'Confirmación' hdr_cells[9].text … -
Django request.user returns 'NoneType'
I am setting up a djangos channel and I am receiving the following error when I visit Threadview at the url below. It seems that it can't query the user? The user is "dominic" and I am signed in, but the view doesn't seem to be able to request.user.. See error message referencing line 99 below. http://127.0.0.1:8000/portal/messages/dominic/ Error: Exception Type: TypeError Exception Value: 'NoneType' object is not iterable Exception Location: /home/dominic/Desktop/Projects/robobud/web/robobud/portal/views.py in get_object, line 99 Python Executable: /home/dominic/Desktop/Projects/robobud/web/env/bin/python3 Line 99 from views.py: def get_object(self): ... obj, created = Thread.objects.get_or_new(self.request.user, other_username) #Line99 Urls.py: #channels path("messages/", InboxView.as_view()), #url(r"^messages/(?P<username>[\w.@+-]+)", ThreadView.as_view(), name='thread'), path('messages/<username>/', ThreadView.as_view(), name='thread'), Views.py: class InboxView(LoginRequiredMixin, ListView): template_name = 'portal/inbox.html' def get_queryset(self): return Thread.objects.by_user(self.request.user) class ThreadView(LoginRequiredMixin, FormMixin, DetailView): template_name = 'portal/thread.html' form_class = ComposeForm success_url = './' def get_queryset(self): return Thread.objects.by_user(self.request.user) def get_object(self): other_username = self.kwargs.get("username") obj, created = Thread.objects.get_or_new(self.request.user, other_username) if obj == None: raise Http404 return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): thread = self.get_object() user = self.request.user message = form.cleaned_data.get("message") ChatMessage.objects.create(user=user, thread=thread, message=message) return super().form_valid(form) -
How to prevent the value of specific model field from being serialized?
I have a model like this: class Test(models.Model): textjson = models.TextField(default="Unassigned") The field textjson holds JSON as string: `'{"distance": 31702.1, "link": "www.strava.com/activities/2020494234", "athlete": 1, "average_speed": 6.499, "name": "Afternoon Ride", "start_date": "2018-12-16T12:13:42Z", "country": "Poland", "number": 2020494234, "date_added": "2018-12-16T20:14:01.362215Z"}`' I have build an API view for this model: class ListTestsView(generics.ListAPIView): serializer_class = TestSerializer def get_queryset(self): tests = Test.objects.all() return tests And I am serializing the model like this: class TestSerializer(serializers.ModelSerializer): class Meta: model = Test fields = '__all__' But this makes the jsontext field to be serialized again when the API view is called and backslashes appear: [ { "id": 1, "textjson": "{\"distance\": 31702.1, \"link\": \"www.strava.com/activities/2020494234\", \"athlete\": 1, \"average_speed\": 6.499, \"name\": \"Afternoon Ride\", \"start_date\": \"2018-12-16T12:13:42Z\", \"country\": \"Poland\", \"number\": 2020494234, \"date_added\": \"2018-12-16T20:14:01.362215Z\"}" } ] How do I rewrite the TestSerializer class to prevent only the value of textjson field from being serialized? -
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, …