Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix 'NoReverseMatch at /' error on Django app?
I'm new to Django and I'm trying to just build a basic application to work off in the future. I keep getting an error saying "NoReverseMatch at/ Reverse for 'about' not found. 'about' is not a valid view function or pattern name." I've searched for other people with the same issue and it seems their issues used an older version of Django and they used different functions from what I'm using. I'm using a book called Hello Web App by Tracy Osborn, which simplifies everything, and all the code I've found dealing with a similar problem seems far more complicated than what I've done so far. I've tried changing my views.py file to request the base.html file instead of the index.html file which didn't work. I've double checked my syntax on all files, including the html file. And, I've made sure the urls.py file matched up exactly. I still keep getting the same error. here is my urls.py file from django.contrib import admin from django.urls import path from django.views.generic import TemplateView from condata import views urlpatterns = [ path('', views.index, name='home'), path('about/', TemplateView.as_view(template_name='about.html'), name='about'), path('contact/', TemplateView.as_view(template_name='contact.html'), name='contact'), path('admin/', admin.site.urls), ] views.py from django.shortcuts import render # Create your views here. … -
App crashed , deployment Heroku error in Django
I'm deploying my first Django app on Heroku and i get this error: 2019-06-17T22:02:04.615398+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=carlosdelgado1.herokuapp.com request_id=210a779e-59ba-46c3-af78-e60215244798 fwd="24.55.161.197" dyno= connect= service= status=503 bytes= protocol=https 2019-06-17T22:34:14.393752+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=carlosdelgado1.herokuapp.com request_id=cc7678e9-c3ec-4b97-9a34-383b6f6f0a4e fwd="24.55.161.197" dyno= connect= service= status=503 bytes= protocol=https this is whats in my Procfile: web: gunicorn porfolio.wsgi i did these import in the wsgi.py file: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kloudless.settings") from django.core.wsgi import get_wsgi_application from dj_static import Cling application = Cling(get_wsgi_application()) here is the github link to the blog project: https://github.com/Poucarlos/portfolio I'm trying to display my blog in Heroku to see it when I access it -
Error in production No module named 'django.db.migrations.migration'
recently I pulled from my git the new version of the project, unfortunately I made a mistake and my settings.py file was completly overwrite. I fix it but when I run my apache server and tried to make a request in the logs I found this: [Mon Jun 17 17:31:02.934215 2019] [wsgi:error] [pid 29830] [remote 200.116.66.129:52114] from .migration import Migration, swappable_dependency # NOQA<br/> [Mon Jun 17 17:31:02.934240 2019] [wsgi:error] [pid 29830] [remote 200.116.66.129:52114] ModuleNotFoundError: No module named 'django.db.migrations.migration' I looked in this other question: Updating Django - error: 'No module named migration' and tried every posibility unsuccessfully. What else should I do to fix this? -
How to create checkboxes with the values of model instances created by users
I want to create forms with checkboxes in them which values of these checkboxes is a model instance created by users. Here is my SessionModel: class SessionModel(models.Model): starting_time = models.TimeField() . . Imagine that I have several instances of this model with various starting_times. and I have another model which is: class TimeModel(models.Model): time = models.TimeField() now i want to select the required instances of SessionModel and update them. But the problem is that I want to have a form with checkboxes with the values of TimeModel.time to grab the instances in SessionModel with the starting_time same as selected TimeModel.time but I don't know how to create these checkboxes should I use dynamic forms or is there any other way I can do this? -
How do I add information from javascript variables to Django ModelForm input?
I am building a web application using Django. The page shows a large leaflet map, in which users can select one out of several layers. I want users to be able to select a layer, click on the map and add a note to that location and that layer. I've created a model form, which holds the note itself. This works fine, and saves to my database. However, I need to also include the currently selected layer and mouse-click-location, which is readily available as a JS variable. How do I pass this on in Django? My views.py holds the following: if request.method == 'POST': form = MapNoteForm(request.POST) if form.is_valid(): form.save() else: form = MapNoteForm() And forms.py: class MapNoteForm(forms.ModelForm): note = forms.CharField() class Meta: model = MapNote fields = ('note',) Finally, the relevant section of the template: map.on('click', function (e) { var MapNote = L.popup(); var content = '<form method="post"> {% csrf_token %} {{form}} <br> <button type="submit"> Save</button>' MapNote.setContent(content); MapNote.setLatLng(e.latlng); //calculated based on the e.layertype MapNote.openOn(map); }) I'm kind of looking to reverse the workings of the Django-view, trying to pass something from the template to Django, instead of vice versa. What would be the best approach here? -
Django templatetag does not expand text properly if it contains double brackets
I'm using a templatetag to expand some TextFields at my Django application (see code below). I'm using the templatetag like this at my template.html: {% load readmore %} ... <h4>{{ user.about|readmore:300|safe|linebreaks }}</h4> this is the actual templatetag which contains the functionality to expand the textfield at my template.html: readmore.py from django import template from django.utils.html import escape from django.utils.safestring import mark_safe import re register = template.Library() readmore_showscript = ''.join([ "this.parentNode.style.display='none';", "this.parentNode.parentNode.getElementsByClassName('more')[0].style.display='inline';", "return false;", ]); @register.filter def readmore(txt, showwords=15): global readmore_showscript words = re.split(r' ', escape(txt)) if len(words) <= showwords: return txt # wrap the more part words.insert(showwords, '<span class="more" style="display:none;">') words.append('</span>') # insert the readmore part words.insert(showwords, '<span class="readmore">... <a href="#" onclick="') words.insert(showwords+1, readmore_showscript) words.insert(showwords+2, '">more</a>') words.insert(showwords+3, '</span>') # Wrap with <p> words.insert(0, '<p>') words.append('</p>') return mark_safe(' '.join(words)) readmore.is_safe = True The problem with this templatetag is the following: If the TextField I'm applying this templatetag onto contains double brackets the "button" to expand the Textfield (labled as 'more' - See: words.insert(showwords+2, '">more') at code above) get's placed somewhere inside the TextField I display on my side... Which again looks quite stupid because it should be at the bottom, to show the user that there is more to read-on. can … -
Swagger provide correct render of POST method API from serializer, but not for DELETE method
Our project is using Django, Django-Rest-Framework, and drf_yasg to document our API with swagger. I created a serializer, and I'm using it with my POST method. everything works well, all the fields are present on my swagger page. I created a delete method using the same serializer and the swagger documentation is showing as parameters to the API only the first group of fields. I tried to use @swagger_auto_schema( method='post', operation_description="POST /Rules/list/", responses={200: listResponseSerializer()}, ) @swagger_auto_schema( @swagger_auto_schema(responses={200: listResponseSerializer()}) method='delete', operation_description="DELETE /Rules/list/", responses={200: listResponseSerializer()}, ) @action(detail=False, methods=['post', 'delete']) and have a single method. both, the post and delete methods are immediately absent from the documentation page. and when using @swagger_auto_schema(responses={200: listResponseSerializer()}) Post method is working, but not the delete method. this capture shows the good results from POST method, where all the fields are presents in the API documentation. filters, parameters, and others. https://1drv.ms/u/s!AvljzERK5-K2akGS8l9zHs8yEtw?e=3QmMe9 With DELETE, it shows only the filters and ignores all the other fields present in the serializer. https://1drv.ms/u/s!AvljzERK5-K2a-x4dqsPCMELUr0?e=LY6jbj Hope someone can help me with this one. I'm struggling for a couple of days now with it. I don't catch what I'm missing or what piece of the integration between django and swagger I don't understand, and need … -
How to Display Div When Checkbox Is Checked
I want to display the hidden div when the checkbox is selected. Currently, when the checkbox is selected, the div remains hidden. Perhaps the nested structure of the divs is causing issues? page.html <div class="field"> <label class="label">Opportunity Information:</label> <div class="field"> <div class="control"> <label class="checkbox"> <input type="checkbox" name="ware_type" id="ware_type" onchange="showHiddenField()">Hardware/Software:</a> </label> </div> </div> <div class="field"> <div class="field"> <input class="input" name="estimate_id" id="estimate_id" type="text" placeholder="Estimate ID" style="display: none;"> </div> </div> </div> script.js function showHiddenField(currentObject) { var inputDiv = $(currentObject).parent().next(); if ($(currentObject).is(":checked")) { $(inputDiv).toggle('show'); } else { $(inputDiv).hide(); } } -
I want to see Google Map and its nearby places in my Django project [on hold]
I want to use Google map to show nearby hospital, pharmacy. How can i do? it It is better to have a resource or tutorial. -
In DRF, how can I serialize the data retrieved from an ad-hot route?
I have the 3 models below: #Appointment class Appointment(models.Model): doctor = models.ForeignKey( Doctor, on_delete=models.CASCADE, related_name='doctor_appointment') patient = models.ForeignKey( Patient, on_delete=models.CASCADE, related_name='patient_appointment') scheduled = models.DateTimeField(auto_now_add=True) # Doctor class Doctor(models.Model): user_id = models.TextField(unique=True) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) # Patients class Patient(models.Model): user_id = models.TextField(unique=True) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) and their 3 respective serializers: # Patient Serializer class PatientSerializer(serializers.ModelSerializer): # contract_number = serializers.PrimaryKeyRelatedField(queryset=Contract.objects.all()) class Meta: model = Patient fields = '__all__' # Doctor Serializer class DoctorSerializer(serializers.ModelSerializer): tariff = serializers.DecimalField( source='DoctorTariff.amount', max_digits=6, decimal_places=2) class Meta: model = Doctor fields = '__all__' # Appointment Serializer class AppointmentSerializer(serializers.ModelSerializer): doctor = serializers.CharField(source='Doctor.user_id') patient = serializers.CharField(source='Patient.user_id') service_provided = serializers.CharField(source='ServiceProvided.service') upcoming = serializers.SerializerMethodField() class Meta: model = Appointment fields = '__all__' For my Appointment model, I've specified an ad-hoc route that will show the upcoming appointment: class AppointmentViewSet(viewsets.ModelViewSet): queryset = Appointment.objects.all() serializer_class = AppointmentSerializer @action(detail=False, url_path='upcoming/(?P<user_id>[^/.]+)') def upcoming_appointment(self, request, user_id=None): try: queryset = Appointment.objects.filter(patient__user_id=user_id).\ select_related('patient', 'doctor').values('scheduled', doctor_first_name=F('doctor__first_name'), doctor_last_name=F('doctor__last_name'), specialty=F('doctor__specialty'), doctor_address=F('doctor__address')) #serializer = AppointmentSerializer(queryset, many=True) # if serializer.is_valid(): except Appointment.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) # If I use serializer.data instead of queryset I get an error return Response(queryset, status=status.HTTP_200_OK) This code works fine, meaning that If I hit the upcoming endpoint I can see … -
Best way to load static images in Django from root directory
I am working on a project in Django 2.2 and I am having a problem loading static images. I followed a tutorial that suggests a media directory in the root of the project. After that, I configured settings as suggest as shown below: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' The urls.py of the project as shown below: urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And this is the base.urls file that has the pages with the images I am trying to load: urlpatterns = [ path('', views.index, name='tedfield-home'), path('faqs/', views.faqs, name='tedfield-faqs'), path('contact/', views.contact, name='tedfield-contact'), path('about/', views.about, name='tedfield-about'), ] I am loading static images used by the website. These images are loading well for the home page, but when I navigate to a page like /about, the images fail to load. On checking, the link loaded is http://127.0.0.1:8000/about/media/images/brands/brand-2.png which has the about instead of the link: http://127.0.0.1:8000/media/images/brands/brand-2.png which is the actual link that loads the images. The code that I am using for the html template is: <img src="media/images/icons/area.png" alt=""> I have also tried using a static directory on the root folder … -
Why is user query triggering TypeError?
I have a CustomUser model in a Django app that I'm trying to query, but the query raises TypeError: all() missing 1 required positional argument: 'self' What I'm trying to accomplish is addressed in several posts here, including this one. >>> from django.contrib.auth import get_user_model >>> User = get_user_model() >>> userList = User.objects.all() Here's my user model: class CustomUser(AbstractUser): username = models.CharField(max_length=11, blank=True, default= 'newUser', verbose_name="User Group") email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager # add additional fields in here display_name = models.SlugField(max_length=50, unique=True) phone = models.CharField(max_length=14, blank=True, help_text="XXX-XXX-XXXX") def __str__(self): return self.display_name Instead of the expected queryset I get the error referencing the missing 'self' argument. The solutions I've found here for that error don't seem to work; clearly I'm missing something. -
Return the other model's field as a response to POST request
In my models.py there are two models: class Genre(models.Model): genre_id = models.CharField(max_length=10) name = models.CharField(max_length=40) information = models.CharField(max_length=120) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) def __str__(self): return self.title They are serialized: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('title', 'author', 'genre') class GenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ('name', 'information') and ViewSets are created for each: class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer class GenreViewSet(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer What I'd like to do is: Sending a POST request to books/ endpoint. Sent data has to contain existing genre ID, it won't be saved to the database otherwise (it's done by default already). Receiving information from the Genre model as a response. Let me give a short example: I'm sending this JSON: { "title": "Hercules Poirot", "author": "Agatha Christie", "genre": 1 } Instead of repeated request from above I receive something like this: { "genre": "crime story" } How to do this? -
Problems making migrations with mysqlclient whit Django virtual enviroment
I want to make a mysql database connection using django, and I have downloaded the mysqlclient packages to do this, but when I use python manage.py makemigrations it throws me the next error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/db/models/base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/db/models/base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/db/models/options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/db/__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/db/utils.py", line 201, … -
How fix to upload image from bootstrap modal form in django
I can not find the information how to load image through django modal form. How to upload a file through a django modal form? my file models.py class Meal(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) name = models.CharField(max_length=500) short_description = models.CharField(max_length=500) image = models.ImageField(upload_to='meal_images/', blank=False) price = models.IntegerField(default=0) def __str__(self): return self.name my file form.py class MealForm(forms.ModelForm): class Meta: model = Meal exclude = ("restaurant",) What needs to be added to views.py to process image loading views.py def restaurant_add_meal(request): data = dict() if request.method == "POST": form = MealForm(request.POST, request.FILES) if form.is_valid(): form.save() data['form_is_valid'] = True meals = Meal.objects.all() data['meal_list'] = render_to_string('meal_list.html',{'meals':meals}) else: data['form_is_valid'] = False else: form = MealForm() context = { 'form': form } data['html_form'] = render_to_string('restaurant/add_meal.html', context, request=request) return JsonResponse(data) Modal form add_meal.html {% load crispy_forms_tags %} <form method="POST" data-url="{% url 'restaurant-add-meal' %}" class="create-form" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header bg-blue"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true" class="text-white">&times;</span> </button> <h4 class="modal-title text-center text-white" >Add Meal</h4> </div> <div class="modal-body"> {{form|crispy}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-pink">Add Meal</button> </div> </form> ajax code that handles the form. I can not understand what is missing here. plugin.js $(document).ready(function(){ $('.show-form').click(function(){ $.ajax({ url: '/restaurant/meal/add', type: 'get', dataType:'json', beforeSend: … -
Unable to set auth_user model primary key as foreign key in my app models.py
I am trying to create a blog app with models.py I want to set auth_user model primary key as foreign key to my model in blog app.After adding the appropriate code i am getting the following error? from django.db import models from django.conf import settings # Create your models here. class Post(models.Model): title=models.CharField(max_length=100) desc=models.TextField() date=models.DateTimeField(auto_now=True) author=models.ForeignKey("settings.AUTH_USER_MODEL", on_delete=models.CASCADE) ERRORS: blog.Post.author: (fields.E300) Field defines a relation with model 'User', which is either not installed, or is abstract. blog.Post.author: (fields.E307) The field blog.Post.author was declared with a lazy reference to 'blog.user', but app 'blog' doesn't provide model 'user'. -
How to query by joining a Django Model with other, on a non unique column?
I have the following models in my models.py file in my django project from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings class CustomUser(AbstractUser): pass # add additional fields in here class PDFForm(models.Model): pdf_type=models.IntegerField(default=0) pdf_name=models.CharField(max_length=100,default='') file_path=models.FileField(default='') class FormField(models.Model): fk_pdf_id=models.ForeignKey('PDFForm', on_delete=models.CASCADE,default=0) field_type=models.IntegerField(default=0) field_page_number=models.IntegerField(default=0) field_x=models.DecimalField(max_digits=6,decimal_places=2,default=0) field_y=models.DecimalField(max_digits=6,decimal_places=2,default=0) field_x_increment=models.DecimalField(max_digits=6,decimal_places=2,default=0) class Meta: ordering= ("field_page_number", "field_type") class UserData(models.Model): fk_user_id=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,default=0) field_type=models.IntegerField(default=0) field_text=models.CharField(max_length=200,default='') field_date=models.DateField() Here is how the models are related 1) a pdfform contains a pdf form and path for it on the file system 2) A pdfform has multiple FormFields in it. Each field has attributes, and the specific one under discussion is field_type 3)The UserData model has user's data, so one User can have multiple rows in this table. This model also has the field_type column. What I am trying to query is to find out all rows present in the Userdata Model which are present in the FormField Model ( matched with field_type) and that are of a specific PDFForm. Given that the Many to Many relationship in django models cannot happen between no unique fields, how would one go about making a query like below select a.*, b.* from FormField a, UserData b where b.fk_user_id=1 and a.fk_pdf_id=3 and a.field_type=b.field_type … -
Django - Determine model fields and create model at runtime based on CSV file header
I need to determine the best approach to determine the structure of my Django app models at runtime based on the structure of an uploaded CSV file, which will then be held constant once the models are created in Django. I have come across several questions relating to dynamically creating/altering Django models at run-time. The consensus was that this is bad practice and one should know before hand what the fields are. I am creating a site where a user can upload a time-series based csv file with many columns representing sensor channels. The user must then be able to select a field to plot the corresponding data of that field. The data will be approximately 1 Billion rows. Essentially, I am seeking to code in the following steps, but information is scarce and I have never done a job like this before: User selects a CSV (or DAT) file. The app then loads only the header row in (these files are > 4GB). The header row is split by ",". I use the results from 3 to create a table for each channel (columns), with the name of the field the same as the individual header entry for that … -
What technology to use to create a real-time collaborative table
I run a very distributed help desk. One of the issues that we are running into is that most of the tools out there for technology documentation have a reasonably high barrier of entering data into them (anything more than 20 seconds to navigate and get into is an issue. What I'd love to try to innovate for fun is this - - Single web form that has a few simple columns. - As people add rows (take notes, think of it as a tech diary) these will update on the other tech's screens, our NOC screens, etc. - Some of the fields should be able to be pre-populated from the database. For example, we definitely have all of the data available to us from our network management systems, so if a tech starts typing in a server name we'd want for it to start popping up suggestions, like google does. Sorry for being so basic -- we are infrastructure guys and don't even know where to start speccing this out. We have 100% no problem paying someone to build this for us, but we'd love to have some understanding of who/what/how/why are. We wouldn't even know where to start … -
Deploy Django on Heroku with Docker heroku.yml
I'm using Docker locally for Django development and trying to use Heroku to deploy with Docker. But I'm getting complains about "no web processes running" aka no Dynos spun up. So missing this config somehow but find no mention of it on Heroku or the few tutorials out there. Dockerfile: FROM python:3.7-slim # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ heroku.yml setup: addons: - plan: heroku-postgresql build: docker: web: Dockerfile run: web: python /code/manage.py runserver 0.0.0.0:$PORT I suspect the issue is in the run section of heroku.yml but pretty stuck. -
Accessing the parent object primary key in CreateView without passing through the url
In django, I have a one to many relationship with two models (e.g. Parent and Child) and would like auto-create the foreign key when I create a new Child record, using CreateView. The only way I can accomplish this is to pass the parent.id through the url, followed by updating the parent_id with a form_valid function in CreateView. I would, however, prefer to keep IDs out of the url and only pass in a descriptive field (i.e. Parent's name field). Is it feasible to access the parent.id from the descriptive fields (or another way)? Or do I just need to accept that I need to have IDs in my url? Let me know if a code example is helpful, but this is more of a theoretical question about the functionality limits of django. -
Why can I not access forms' errors attributes in django template?
The code below shows my template, views, and forms code. I would like to display the errors generated by the .is_valid() functions called in views.py when the form html is re-rendered. The problem is that I cannot even access the errors within the incident_form and incident_formset, let alone display them. Neither incident_form.errors, incident_formset.errors, nor {% for field in incident_form %} {% for error in field.errors %} <p> {{ error }} </p> {% endfor %} {% endfor %} allow me to view the errors generated by the .is_valid method. Strangely enough, the crispy app returns to the invalid form with the first invalid field highlighted and ready to accept input from the user. Also, when the date field is filled out incorrectly, the form will sometimes display an error like "Invalid date field". However, no required fields which are submitted without data show "Required" errors. Help is much appreciated. Snippet of new_incident.html: <form method="post" class="form-horizontal"> {% crispy incident_form %} <input type="button" id="delete_field_data" class="btn btn-outline-danger" value="Delete Field Incident Data"> <div id="form_set_class"> {{ incident_formset.management_form }} {% for form in incident_formset %} {{form.non_field_errors}} {{form.errors}} {% crispy form %} {% endfor %} </div> [...] Snippet of forms.py: class IncidentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(IncidentForm, self).__init__(*args, … -
save image with models.ImageField , and it dosent save's with the CreateView
I am using CreateView CBV, when i am trying to use the CreateView it dosen't save the image to the DB, the rest of the fields works fine, only this one. well it do save it with the admin interfase models.py: class Movie(models.Model): name = models.CharField(max_length = 250,unique = True) director = models.CharField(max_length = 250) image = models.ImageField(upload_to='movies_pictures', blank =True, null=True) length = models.IntegerField() price = models.IntegerField() copies = models.IntegerField() trailer = models.URLField() def __str__(self): return self.name def get_absolute_url(self): ''' this will reverse you back to movie detail page ''' return reverse("movie_detail",kwargs={"pk":self.pk}) class Meta: ordering = ['name'] forms.py: class MovieForm(forms.ModelForm): class Meta: model = models.Movie fields = '__all__' views.py: class MovieCreateView(CreateView): model = models.Movie fields='__all__' -
Django Template Access a dictionary values with variable
I have a list with IP Addresses. I also have a nested dictionary which uses those addresses as keys. For example: my_list = ['1.2.3.4', '8.8.8.8'] my_dic = {'data': {'1.2.3.4': 'My First Data'}, {'8.8.8.8': 'My Second Data'}} In my template I am trying to this: for each in my_list: print(my_dic['data'][each]) Everything works well until I hit that each key. So if I just print my_dic or my_dic[data] it will all work correctly. But when I add the each index nothing shows up in the webpage I have printed each independently so I know that it works correctly. This also works as expected when I run the loop in my IDE so I know the logic is right. In django my code looks like this: {% if my_dic.data %} {% for each in my_list %} <p>{{ my_dic.data.each }}</p> {% endfor %} {% endif %} I'm new to Django so not sure if I'm overlooking something silly. Anyone know what I am missing here? -
How to add objects to a table in sqlite?
I'm not asking for some code but just for recommendations about tutorials or source material about this issue; In django I can add new objects to a table using the admin panel or the python shell but in both cases I have to manually add every single object to the table in my sqlite database. I have every object I want to add in a list, is there a way to add the objects in this list automatically to the table in the database? Where can I study how to add objects from a list to a database's table using django? I've obsessively searched a solution during all afternoon, couldn't find any. Any suggestion where to look to learn is very appreciated, thanks.