Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I increase the max length of captured Python parameters in Sentry?
I'm using sentry-python==0.5.3 in a Django project, and when I inspect a stacktrace's parameter list, I see some of the values are long enough to be cut off by a ... elipsis. I want to see the entire value. How do I configure sentry-python to show the entire parameter value in the stacktrace? Here's how I'm calling the init function in my Django config: sentry_sdk.init( dsn="sentry dsn", integrations=[DjangoIntegration()], send_default_pii=True ) -
Django; Signup form with only email and password
I want to create a Sign Up form with just email and password (and confirmation). I don't need username. But when I try to create a CustomSignUp form based on UserCreationForm, this error occurred. Unknown field(s) (password2, password1) specified for CustomUser Do I have to set password fields? Or is there a smart way to inherit these (including validation) from UserCreationForm? forms.py class CustomUserCreationForm(UserCreationForm): class Meta: fields = ('email', 'password1', 'password2') and views.py is going to be like this def sign_up(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') user = authenticate(email=email, password=password) login(request, user) ... What is the easiest way to create like sign up form or login form with only email and password? -
Django Admin use JWT
Using: Django 1.11 Python 3.6 DRF with JWT in FE I understand that the Django admin uses a session, and basic authentication. What I did so far: Replaced the Django Admin authentication signin page with AWS-Cognito: The user goes to domain/admin/*, redirected to signin in AWS On successful signin the user is redirected to the redirect_uri, leads to a Django View In the view I replace the code with tokens I can't navigate to any Admin page - I am trying to redirect, but that doesn't work since I didn't login() the User Stuck - I would like to associate the User with the fetched tokens and authenticate with every Admin page request, and when the user logs out delete the tokens What to do next? When I use JWT with the Front End application, every request.META has HTTP_AUTHORIZATION, and uses a suitable backend. I know how to add backends, and potentially leverage the user.backend (I also use Cognito-JWT for other FE portions, so already wrote BE for that) I need to find a way to replace the Django Admin sessions authentication with the fetched token Thank you! -
How to Redirect Form Submissions to Another View
I have the following django form, which will be used by users to input a query and select a model to search that particular query: from django import forms class search_forms(forms.Form): search_query = forms.CharField(label='search_query') path_choices = [('urlpath1/','model name 1'), ('urlpath2/','model name 2')...] model_paths = forms.ChoiceField(label='model_paths',choices=path_choices) This form is used to populate a template which consists of a input field of text for for users to submit queries, and a drop down field which identifies which model the query should be directed to (the path_choices variable in forms.py). Thew views.py is as follows, which needs to change to the following somehow: def search(request): if request.method == 'GET': form = search_forms(request.GET) if form.is_valid(): return render(request, 'template_for_model_paths.html', {'form': form, 's_results': s_results}) else: form = search_forms() return render(request, 'search.html', {'form': form,}) Currently, the form template yields a GET result as follows: /search?search_query=QUERY&model_paths=model_path%2F What I would like to accomplish is: model_path/Query as the result, which I can feed back to the view for the search form and use it to redirect the view relevant for model_path. How should I accomplish this? Does this approach make sense? Or am I misapplying the intent of the form functionality? -
Automatic Thermal Receipt Printout with Python/Djano?
A restaurant currently has an online ordering system built with django, they get online orders via email but would like them to be automatically printed out as they come in. Is there a way to do this using python/django? Would I need to write code specific to the make/model of the printer? -
Django REST - Writing a view function that returns attributes changed on PATCH request
I'm trying to add a function to a view class of viewset.ModelViewSet such that when the user makes a patch request it returns the value and the attribute changed. So for example if I make a patch with the body like so {key : food, value : "coffee"} if the change was successful in the database the response should be 200 body: {food : "coffee"} How do I do this? Thanks in advanced. -
Creating a docker image to scaffold django projects
I'm build a docker image that can scaffold out a docker project using this Dockerfile: FROM python:3 WORKDIR /usr/src/app CMD ["pip","install Django"] CMD ["django-admin", "startproject hello_world_django"] I build the image using: docker build django-scaffold . and run it using docker run django-scaffold Error message: docker: Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"django-admin\": executable file not found in $PATH": unknown. When I run this docker image, I am informed that the command django-admin is not available. How can I add django-admin to the path within the container? -
Django ModelForm error 'this is a required field'
When trying to upload an Image in my Django App, I get the error "This is a required field". Even though I am actually uploading an Image. It works fine in the Admin, but not in the App itself. Here is the models.py, forms.py and the View, respectively. models.py class Blog(models.Model): BLOG_CATEGORIES = ( ( 'T', 'Technology'), ( 'B', 'Business' ), ( 'C', 'Culture' ), ( 'N', 'None' ) blogger = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.Cascade) date_added = models.DateField(auto_now_add=True) blog_post = models.TextField(max_length=2000) blog_category = models.CharField(max_length=20, choices=BLOG_CATEGORIES blog_name = models.CharField(max_length=20, primary_key=True) blog_picture_context = models.ImageField(upload_to='/static/homepage/', max_length=250) def __unicode__(self): return '{} created this entry on {}'.format(self.blogger, self.date_added) def __str__(self): return '{} created this entry on {}'.format(self.blogger, self.date_added) forms.py class BLogForm(models.ModelForm): class Meta: model = Blog fields = ['blogger', 'date_added', 'blog_post', 'blog_category', 'blog_name', 'blog_picture_context'] views.py class BlogView(LoginRequiredMixin, FormView): template_name = 'blog_form.html' form_class = BlogForm success_url = '/' login_url = 'users/login/' Again, just for context, I am trying to do this in the app with the development server running. It gives me the error just above the ImageField. !https://i.imgur.com/M7ylwzB.png -
Issue with deploying geodjango on heroku
I made a simple GIS application with GeoDjango and I am struggling to deploy it on Heroku. I tried with Heroku-18 stack with heroku config:set BUILD_WITH_GEO_LIBRARIES=1 but it got [Errno 2] No such file or directory: 'gdal-config': 'gdal-config' error. I also tried heroku-16 with https://github.com/cyberdelia/heroku-geo-buildpack.git buildpack but ended up with getting this error ImportError: libjasper.so.1: cannot open shared object file: No such file or directory. My requirements.txt is as below: beautifulsoup4==4.6.3 certifi==2018.11.29 chardet==3.0.4 dj-database-url==0.5.0 django-crispy-forms==1.7.2 django-heroku==0.3.1 django==2.1.4 gdal==2.1.3 gunicorn==19.9.0 idna==2.7 psycopg2==2.7.6.1 pytz==2018.7 requests==2.20.1 urllib3==1.24.1 whitenoise==4.1.2 wikipedia==1.4.0 I am also using python 3.7.0. Can you please help me? -
How can I fix Python/Django migrate error
I had migrated error. Please give me any advance thanks. And here is my related cod and error. migration/0001_initial_.py operations = [ migrations.CreateModel( name='Member', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=120)), ('content', models.TextField()), ], ), ] member models.py `class Member(models.Model): name = models.CharField(max_length=120) content = models.TextField() def __str__(self): return self.name` member serialize class class MembersSerializer(serializers.ModelSerializer): class Meta: model = Member fields = ('id', 'name', 'content') migrate result error AttributeError: 'AutoField' object has no attribute 'api' -
Django Rest Framework url dispatcher
I am trying to interact with the SWAPI API. I want a view that fetches all the movies(films/) and one that fetches one (film/id). When I hit http://127.0.0.1:8000/api/films/?id=4 it enters the get_films function. I am using Django==1.11 and Django Rest Framework==3.9.0 . my urs.py: urlpatterns = [ url(r'films/',views.get_films,name="get-films"), url(r'films/(?P<id>[0-9])/',views.get_film,name="get-film"), ] my views.py: MAX_RETRIES = 5 API_URL= "https://swapi.co/api/" @api_view(['GET', 'POST']) def get_films(request): request_url = API_URL + "films" print(request_url) if request.method == "GET": attempt_num = 0 # keep track of how many times we've retried while attempt_num < MAX_RETRIES: r = requests.get(request_url, timeout=10) if r.status_code == 200: data = r.json() return Response(data, status=status.HTTP_200_OK) else: attempt_num += 1 # You can probably use a logger to log the error here time.sleep(5) # Wait for 5 seconds before re-trying return Response({"error": "Request failed"}, status=r.status_code) else: return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'POST']) def get_film(self, request): print('entered') request_url = API_URL + "films/" + request.query_params.get('id') if request.method == "GET": attempt_num = 0 # keep track of how many times we've retried while attempt_num < MAX_RETRIES: r = requests.get(request_url, params=film_id,timeout=10) if r.status_code == 200: data = r.json() return Response(data, status=status.HTTP_200_OK) else: attempt_num += 1 # You can probably use a logger to log the error here … -
Assign ids to entries
There are following models: class Parameter (models.Model): id_parameter = models.IntegerField(primary_key=True) par_rollennr = models.IntegerField(default=0) par_definition_id = models.IntegerField(default=0) #not FK par_name = models.CharField(max_length=200) class Measurements (models.Model): id_measurement = models.AutoField(primary_key=True) par_value = models.IntegerField(default=0) line = models.ForeignKey(Line, on_delete=models.CASCADE, null=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True) parameter = models.ForeignKey(Parameter, on_delete=models.CASCADE, null=True) I write down as follows: def handle_parameters_upload(request, file): wb = openpyxl.load_workbook(file, read_only=True) first_sheet = wb.get_sheet_names()[0] ws = wb.get_sheet_by_name(first_sheet) recipe, _ = Recipe.objects.get_or_create(par_recipe=ws["B2"].value) line, _ = Line.objects.get_or_create(par_machine=ws["C2"].value) order, _ = Order.objects.get_or_create(par_fa=ws["D2"].value) parameter_data = set() measurement_data = [] for row in ws.iter_rows(row_offset=1): parameter_data.add(( row[5].value, row[6].value, row[7].value, )) # par_rollennr, par_definition_id, par_name, measurement: par_value measurement_data.append(row[8].value) # Bulk create data Measurements.objects.all().delete() Parameter.objects.all().delete() parameters = Parameter.objects.bulk_create([ Parameter( id_parameter=index, par_rollennr=p_data[0], par_definition_id=p_data[1], par_name=p_data[2], ) for index, p_data in enumerate(parameter_data) ]) Measurements.objects.bulk_create([ Measurements( line=line, order=order, recipe=recipe, par_value=m_data, parameter=parameter, ) for parameter, m_data in zip_longest(parameters, measurement_data) ]) return True Thus, I only establish connections by the first lines, by the number of parameters. How can I set the parameter_id for all records if I have them duplicated in the whole file that I process. -
Trying to save multiple files in Django 2 Admin
I have read the various posts on saving multiple files using the django 2 admin, but I still can't get it to work. My model: class Document(Model): document_id = models.AutoField(primary_key=True) document_state = models.IntegerField(choices=DOCUMENT_STATE, default=PRIVATE, verbose_name="state") documentType_id = models.ForeignKey(DocumentType, on_delete=models.CASCADE, verbose_name="document type", ) created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name="date created") updated = models.DateTimeField(auto_now=True, editable=False, verbose_name="last update") storage_file_name = models.FileField('File name', upload_to=unique_file_path) thumb_storage = models.FileField(editable=False,) original_file_name = models.CharField(editable=False, max_length=200) computed_sha256 = models.CharField(editable=False, max_length=64) I create my own field in the Document admin, so I added the 'multiple' keyword to the field. The field for storage_file_name looks like this in the admin create document page: <label class="required" for="id_storage_file_name">File name:</label> <input type="file" name="storage_file_name" multiple required id="id_storage_file_name" /> I have this in save_model in the DocumentAdmin class: def save_model(self, request, obj, form, change): logger.debug("save_model START") logger.debug("obj=%s, change=%s" % (obj, change)) if (form.is_valid()): logger.debug("\tvalid form") logger.debug("form.cleaned_data=%s",form.cleaned_data) obj.metadata = form.cleaned_data['metadata'] logger.debug("files=%s" % request.FILES.getlist('storage_file_name')) files = request.FILES.getlist('storage_file_name') for f in files: logger.debug("storing file=%s" % f) obj.storage_file_name = f super().save_model(request, obj, form, change) logger.debug("save_model END") files has the right list of files I want to upload. But I can't seem to save more than the last item in the list of files. I don't get any error messages; just the … -
django - username already taken
I'm new to python and django and following tutorials online here and there I was trying to develop an app. But when doing the register function I encountered an error. Django says that the user name already exist when I'm trying to create an user, but the user doesn't exist and I'm stuck. Can you help? models.py from django.contrib.auth.models import User from django.db import models class Hobby(models.Model): hobby = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.hobby class Member(User): gender = models.CharField(max_length=6) date_of_birth = models.DateField() picture = models.ImageField(upload_to='profile_images') hobby = models.ManyToManyField(to=Hobby, blank=True, symmetrical=False) urls.py urlpatterns = [ # /matchings/ path('', views.home, name='home'), # /matchings/login path('login/', views.login, name='login'), # /matchings/login path('signup/', views.signup, name='signup'), # /matchings/login path('register/', views.register, name='register'), ] singup.html {% extends 'base.html' %} {% block head %} <title>Sing Up</title> {% endblock %} {% block body %} <div class='main'> <h3>Please enter your details to sign up</h3> <form method='POST' action="{% url 'register' %}"> {% csrf_token %} <span class='fieldname'>Username</span> <input type='text' maxlength='16' id='regusername' name='username'> <span id='info'></span> <br> <span class='fieldname'>Password</span> <input type='password' maxlength='16' name='password'><br> <span class='fieldname'>&nbsp;</span> <input type='submit' value='Sign up'> </form> </div> {% endblock %} views.py from django.shortcuts import render from django.utils import timezone from django.http import HttpResponse, Http404 from django.template import RequestContext, loader from matchings.models … -
Updating audio.currentTime resets to 0 - unintended behavior (Django?)
I'm attempting to update the currentTime of an html audio element, however, it keeps resetting to 0 no matter what value I give it. I've confirmed that the values I'm passing are less than the audio file's duration, and greater that 0. The following code works as-intended locally in an html file, but exhibits this strange behavior in my Django app. HTML: <audio id="my-audio" preload="true" src="path/to/file.mp3" type="audio/mp3"></audio> JavaScript: var audio = document.getElementById('my-audio') audio.play() console.log(audio.currentTime) // result: 0.997171 or similar console.log(audio.duration) // result 3596.06855 audio.currentTime = 500 console.log(audio.currentTime) // result: 0 All my other audio-related functions are working. This strange behavior occurs with multiple different audio files. I've searched SO for a solution, but nothing seems relevant to my particular case. I'm thinking that is has something to do with Django's server per the following comment from another thread. But I can't find any more information about this. I am facing the same issue. It's working on a piece of code, but when i integrate it in a Django application, it fails. It works on Firefox but not on Google Chrome. Video / Audio file doesn't matter, it happens with any file i try on the code. The time i am … -
how to set foreign key in function based view in django?
This is the error - Cannot assign "'question2'": "Answers.question" must be a "Question" instance. model.py def main(request, pk): ques = get_object_or_404(Question, pk=pk) if request.method == "POST": answerForm = AnswerForm(request.POST) if answerForm.is_valid(): ans = answerForm.save(commit=False) ans.user = request.user ans.question = Answers(question=ques.question) # here assigning foreign key ans.answer = answerForm.cleaned_data.get['question_sel'] print(answerForm.cleaned_data.get['question_sel']) ans.save() return redirect('main', pk=ques.pk) else: answerForm = AnswerForm(request.POST) return render(request, 'quiz/main.html', {'ques': ques,'answerForm':answerForm}) -
AngularJS Error Controller with this name is not registered
im having a headache with this one, im not very skilled in Angular but was the only way to check 'today dolar value'. This is my dolar.js var app = angular.module("app", []); app.controller("DolarCtrl", function($scope, $http) { $scope.dailyIndicators = ''; $http.get('https://mindicador.cl/api/dolar').then(function(res) { //.success was changed for .then // $scope.dailyIndicators = res.data.serie[0].valor; }) }); base.html <body ng-app> <p ng-controller="DolarCtrl"> Dolar acutal: $ {{DolarCtrl.dailyIndicators}}</p> </body> but at soon as i refresh the page, i got this error: error: [$controller:ctrlreg] http://errors.angularjs.org/1.7.5/$controller/ctrlreg?p0=DolarCtrl at angular.js:99 at angular.js:11646 at ga (angular.js:10677) at q (angular.js:10462) at g (angular.js:9801) at g (angular.js:9804) at angular.js:9666 at angular.js:1947 at m.$eval (angular.js:19356) at m.$apply (angular.js:19455) any ideas? i dont know if you guys needs more info. thanks! -
Deploying django site to elasticbeanstalk: NotAuthorizedError: Operation Denied. The security token included in the request is invalid
I am getting this error when trying to deploy to elastic beanstalk using CLI. The deploy was working before I added the code to a remote git repository (theplay.team) vagrant@debian-7:/vagrant/Devel/theplay.team/theplayteam$ eb deploy --verbose INFO: Deploying code to playground-env in region us-east-1 INFO: Getting version label from git with git-describe /vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/urllib3/util/ssl_.py:339: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings SNIMissingWarning INFO: Traceback (most recent call last): File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/core/ebrun.py", line 41, in run_app app.run() File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/cement/core/foundation.py", line 797, in run return_val = self.controller._dispatch() File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/cement/core/controller.py", line 472, in _dispatch return func() File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/cement/core/controller.py", line 478, in _dispatch return func() File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/core/abstractcontroller.py", line 85, in default self.do_command() File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/controllers/deploy.py", line 83, in do_command staged=self.staged, timeout=self.timeout, source=self.source) File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/operations/deployops.py", line 50, in deploy app_name, process=process_app_versions, label=label, message=message, staged=staged, build_config=build_config) File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/operations/commonops.py", line 507, in create_app_version s3_bucket, s3_key = get_app_version_s3_location(app_name, version_label) File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/operations/commonops.py", line 347, in get_app_version_s3_location app_version = elasticbeanstalk.application_version_exists(app_name, version_label) File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/lib/elasticbeanstalk.py", line 408, in application_version_exists app_versions … -
Reverse for 'random_obj' with keyword arguments '{'ran': ''}' not found. 1 pattern(s) tried: ['detail\\/(?P<ran>[0-9]+)\\/$']
I want to create a view that generates a random number for me between 1 and the amount of objects inside the model. I then want to pass it as context to the template. However i keep getting the following error: Reverse for 'random_obj' with keyword arguments '{'ran': ''}' not found. 1 pattern(s) tried: ['detail\/(?P[0-9]+)\/$'] def random_page(request): object_count = MODEL.objects.count() ran = random.randint(1, object_count) return render(request, 'app/detail.html', {'ran': ran}) urlpatterns = [ path('', views.home, name='home_page'), path('detail/<int:pk>/', views.detail_page, name='detail_page'), path('detail/<int:ran>/', views.random_page, name='random_page'), ] This results in above error: <a class="anchor_boot" href="{% url 'app:random_page' ran=ran %}">random obj</a> </div> This works: <a class="anchor_boot" href="{% url 'app:random_page' 8 %}">random obj</a> </div> What am I doing wrong? -
How to accomplish full record update on Django REST serializer update() method
I have a model based serializer called RecipeSerializer(). In it I have a create method that looks like so: class RecipeSerializer(serializers.ModelSerializer): hops = HopAdditionSerializer(many=True) fermentables = FermentableAdditionSerializer(many=True) style = StyleSerializer() yeast = YeastSerializer() class Meta: model = Recipe exclude = () def create(self, validated_data): recipe = Recipe.objects.create(**validated_data) recipe.save(); return recipe What I'm trying to do is something similar with my update() method. In the documentation they show going through each field one by one and setting the values: def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.save() My model has many fields though. What I'd like to do is pass the validated data to the update method similar to the create method: instance.update(**validated_data) However, I get an error: 'Recipe' object has no attribute 'update' Is it possible to update all properties of the instance using the validated dataset without setting each property individually? -
Python MySQLdb works from Python on Command Line but not Django Views.py
I have a Django views.py function named getpos that gets served by apache2 and wsgi.py. If I run the exact same code from my views.py in a normal Python session from the Ubuntu command line, the MySQLdb connection works fine: >>> import MySQLdb >>> db = MySQLdb.connect(host="localhost",port=22,user="root",passwd="mypassword",db="gps") >>> >>> cursor = db.cursor() If I run it from the django debug server, it fails with: ERROR: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") The code that runs is this: def getpos(request): query = "SELECT * FROM..." # connect to the DB and return nearby deals db = MySQLdb.connect(host="localhost",port=22,user="root",passwd="mypassword",db="gps") cursor = db.cursor() # Query the gps Data database results = cursor.execute(query) db.commit() Howcome I can connect from Python on the command line but not in the views.py file with Django? Thanks. I've tried using "127.0.0.1" instead of "localhost", but nothing seems to work. I appreciate any help thanks! -
Dynamic url pattern in django
I don't fully understand how to make the dynamic menu in Django. I have this in models.py class Menu(models.Model): menu_title = models.CharField(verbose_name=_('Menu title'), max_length=70) is_active = models.BooleanField(verbose_name=_('Is active'), default=False) slug = models.SlugField(max_length=70, null=True) class Meta: verbose_name = _('Menu') verbose_name_plural = _('Menus') def get_absolute_url(self): return reverse("main:menu", kwargs={'slug':self.slug}) in template: {% for item in menu %} {% if item.is_active %} <li class="navigation-panel__item"><a href="{{ item.get_absolute_url }}" class="navigation-panel__link">{{ item.menu_title }}</a></li> {% endif %} {% endfor %} in admin.py class MenuAdmin(TabbedTranslationAdmin): list_display = ('menu_title', 'is_active') prepopulated_fields = {"slug": ("menu_title_en",)} in urls.py urlpatterns = [ path('<slug>', ArticleListView.as_view(), name='menu'), ] Now all buttons in menu refer to article list view page. But I should render various views for various slugs. Is it possible to select a view based on the slug field? Thanks. -
Heroku/Django deploy: why am I getting an error 500 with successful deploy and static collection?
Here is my repo in full. I've been struggling to deploy my first Django site on Heroku for months. I'm getting successful builds with git push heroku master and successfully collecting the static files using heroku run python manage.py collectstatic --noinput, but I can't get the site to serve without an error 500 when DEBUG = config('DEBUG', default=False, cast=bool). The site does work when DEBUG is set to True (though I'm going to have to figure out making the database work). I think my allowed hosts are set correctly. All of the answers I can find on SO don't quite solve my issue. I added the logging from this answer which gives me a little more information in the logs, but I'm not understanding why the staticfiles aren't available when I've been able to successfully collect them? 2018-12-09T16:24:38.181428+00:00 heroku[web.1]: State changed from starting to up 2018-12-09T16:24:39.173376+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/whitenoise/base.py:104: UserWarning: No directory at: /app/staticfiles/ 2018-12-09T16:24:39.173419+00:00 app[web.1]: warnings.warn(u'No directory at: {}'.format(root)) 2018-12-09T16:24:39.173421+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/whitenoise/base.py:104: UserWarning: No directory at: /app/staticfiles/ 2018-12-09T16:24:39.173423+00:00 app[web.1]: warnings.warn(u'No directory at: {}'.format(root)) I'm obviously missing a lot, any guidance would be most appreciated. -
iterate trough a forms in dictionaly passed from view to html in python with jinja
I would appreciate your help in the below problem: I need to use 3 different models in a python app which I want the user to populate from a HTML form. I want to use model forms and I pass all the three different form in one dictionary (see my views.py): def new_sales_trip(request): if request.method == "POST": Restaurant_Form = RestaurantForm(request.POST) SalesEvent_Form = SalesEventForm(request.POST) NextAction_Form = NextActionForm(request.POST) if Restaurant_Form.is_valid() and SalesEvent_Form.is_valid() and NextAction_Form.is_valid(): Restaurants = Restaurant_Form.save() SalesEvents = SalesEvent_Form.save(False) NextActions = NextAction_Form.save(False) SalesEvents.restaurants = Restaurants SalesEvents.save() NextActions.restaurants = Restaurants NextActions.save() return redirect('/') else: allforms = { 'Restaurant_Form': Restaurant_Form, 'SalesEvent_Form': SalesEvent_Form, 'NextAction_Form': NextAction_Form, } return render(request, 'sales/SalesTrip_form.html', allforms) else: Restaurant_Form = RestaurantForm() SalesEvent_Form = SalesEventForm() NextAction_Form = NextActionForm() c = {} c.update(csrf(request)) allforms = { 'Restaurant_Form': Restaurant_Form, 'SalesEvent_Form': SalesEvent_Form, 'NextAction_Form': NextAction_Form, } return render(request, 'sales/SalesTrip_form.html', allforms) So far it works - however I don't know how to use this dictionary to iterate trough in my template so I shouldn't reference all the form by name separatelly. I try to to do something like this: {% for key, value in allforms.items %} {% for field in value %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <!--this gonna be only displayed if there is an error … -
Django QuerySet last added from a specific category
Probably an extremely easy solution, but cant really come up with one. The end-goal is to create a gallery showing at first the categories. Each category should display the last added image with the respective category name. My models.py class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() objects = models.Manager() class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=200) description = models.TextField(blank=False, null=True) date = models.DateTimeField(blank=False, null=True) image = models.ImageField(blank=True, null=True) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) objects = models.Manager() class Meta: app_label = 'home' get_latest_by = 'date' My views.py def index(request): cat = Category.objects.all() latest = Item.objects.latest('date') context = { 'categories': cat, 'last_added': latest, } return render(request, 'gallery/index.html', context) My index.html {% block content %} <h4 class="gallery">Gallery</h4> {% for category in categories %} <p class="category">{{ category.name }}</p> <p> <img class="images" src="{{ last_added.image.url }}"> </p> {% endfor %} {% endblock %} I cannot figure out how to display the latest image for their respective category. I know i have to somehow create a dynamic query that would use the 'category.name' as variable, but i cannot figure out how to do this. Any input would be very valuable, at least indicating the direction in which i …