Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django - Get the absolute URL when using .values()
I have a user model with many fields class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(max_length=255, unique=True) username = models.SlugField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) avatar = models.ImageField(upload_to='users/avatar', default='users/avatar/avatar.png') last_login = models.DateTimeField(blank=True, null=True) member_since = models.DateTimeField(default=timezone.now, db_index=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) In a particular view, I am interested in retrieving just the username and the avatar of the user, so I can return a JSON response, so I do the following: users = User.objects.values('username', 'avatar') That will return me a list of dictionaries with the following data: <QuerySet [ {'username': 'A', 'avatar': 'users/avatar/avatar.png'}, {'username': 'B', 'avatar': 'users/avatar/avatar.png'}, {'username': 'C', 'avatar': 'users/avatar/avatar.png'} ]> Notice that the URL for the avatar is a relative one. How could I get the absolute URL without having to retrieve all the fields of the user? I'd like to get the following: <QuerySet [ {'username': 'A', 'avatar': 'http://example.com/media/users/avatar/avatar.png'}, {'username': 'B', 'avatar': 'http://example.com/media/users/avatar/avatar.png'}, {'username': 'C', 'avatar': 'http://example.com/media/users/avatar/avatar.png'} ]> -
Django formtools done function not executed
I am trying to implement the formwizard in django. The steps work as expected, but aftet the final form (second step) is submitted, the done function is not hit. I am not able to find the reason why. Kindly direct. Following is my code, Forms.py from django import forms class FormStepOne(forms.Form): name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) phone = forms.CharField(max_length=100) email = forms.EmailField() class FormStepTwo(forms.Form): otp = forms.CharField(max_length=100) views.py from django.shortcuts import render from .forms import FormStepOne, FormStepTwo from formtools.wizard.views import SessionWizardView from django.http import HttpResponseRedirect # Create your views here. class FormWizardView(SessionWizardView): template_name = 'done.html' form_list = [FormStepOne, FormStepTwo] def done(self, form_list, **kwargs): print('done') return render(self.request, 'home.html', {'form_data':[form.cleaned_data for form in form_list],}) # return HttpResponseRedirect('/home/') def process_step(self, form): # print(self.get_form_step_data(form)['0-email']) # print(self.steps.current) if self.steps.current == '0': print('send mail to ' + self.get_form_step_data(form)['0-email']) else: print('verify the entered otp') I want to send a mail with otp after 1st step is submitted, and then in the second step I ask for the otp that was sent in first step for verification. And by default, after submitting the last step the page is redirected to step 1. Why? -
SuspiciousFileOperation joined path located outside base path component
When opening and image with the PIL library like below img = Image.open(image.image) I get the following error... Error Message: base = 'C:\\code\\receipts\\media\\' paths = ('test_files\\no_meta_data_picture.png',) final_path = 'C:\\code\\receipts\\media\\test_files\\no_meta_data_picture.png' base_path = 'C:\\code\\receipts\\media\\' def safe_join(base, *paths): """ Join one or more path components to the base path component intelligently. Return a normalized, absolute version of the final path. Raise ValueError if the final path isn't located inside of the base path component. """ final_path = abspath(join(base, *paths)) base_path = abspath(base) # Ensure final_path starts with base_path (using normcase to ensure we # don't false-negative on case insensitive operating systems like Windows), # further, one of the following conditions must be true: # a) The next character is the path separator (to prevent conditions like # safe_join("/dir", "/../d")) # b) The final path must be the same as the base path. # c) The base path must be the most root path (meaning either "/" or "C:\\") if (not normcase(final_path).startswith(normcase(base_path + sep)) and normcase(final_path) != normcase(base_path) and dirname(normcase(base_path)) != normcase(base_path)): raise SuspiciousFileOperation( 'The joined path ({}) is located outside of the base path ' > 'component ({})'.format(final_path, base_path)) E django.core.exceptions.SuspiciousFileOperation: The joined path (C:\code\receipts\media\test_files\no_meta_data_picture.png) is located outside of the base path component … -
Serialize a list os questions and return as a JSON
I'm trying to serialize a list of objects, but I get an erro, How can I serialize this list of objects? Thanks ids = request.data.__getitem__("ids") questions_array = [] for id in ids: questions = Question.objects.filter(pk=id) questions_array.append(questions) serializer = QuestionSerializer(questions_array, many=True) return Response(serializer.data) I alway get this error: TypeError: init() got an unexpected keyword argument 'fields' -
Why I cannot save records into database?
I have a form that in past works good but after I change some data in the models and add image field it doesn't work. From admin I can add new records but I think is a problem with form id. When I inspect in google chrome the admin page, form id is porumbei_form and when I inspect my template, the form id is not showing. #My view @login_required(login_url='/login/') def porumbelnou(request): if request.method == "POST": form = AdaugaPorumbel(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('/porumbei/') else: form = AdaugaPorumbel() context = { 'form': form, } template = loader.get_template("adaugare_porumbel.html") return HttpResponse(template.render(context, request)) #My form class AdaugaPorumbel(forms.ModelForm): class Meta: model = Porumbei fields = ['data_adaugare', 'serie_inel', 'anul', 'culoare', 'crescator', 'culoare_ochi', 'sex', 'ecloziune', 'rasa', 'linie', 'nume', 'tata', 'mama', 'compartiment', 'status', 'data', 'vaccinat', 'info', 'imagine', 'imagine_ochi'] widgets = { 'ecloziune': forms.DateInput(format='%d/%m/%Y', attrs={'class': 'form-control', 'type': 'date'}), 'data': forms.DateInput(format='%d/%m/%Y', attrs={'class': 'form-control', 'type': 'date'}), 'vaccinat': forms.DateInput(format='%d/%m/%Y', attrs={'class': 'form-control', 'type': 'date'}), 'info': forms.Textarea(attrs={'class': 'form-control mt-15', 'rows': '3', 'placeholder': 'Vor apărea în pedigree'}), } #My model class Porumbei(models.Model): id_porumbel = models.AutoField(primary_key=True) data_adaugare = models.DateTimeField(default=datetime.now()) crescator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True) anul = models.CharField(max_length=4, null=False, blank=False) culoare = models.ForeignKey(CuloriPorumbei, on_delete=models.CASCADE, null=False, blank=False, ) culoare_ochi = models.ForeignKey(CuloriOchi, on_delete=models.CASCADE, … -
How to Logout in Django
I am using Django-Python3-LDAP as my user authentication back-end which works fine. However, I am unable to logout a user using the Django authentication system. Upon clicking my logout button which calls my logout view, I am redirected via LOGOUT_REDIRECT_URL = '/website/login' in my settings.py. So it seems it is working, yet if I navigate to a page within the site, the user credentials are still within the session. Any thoughts? views.py # Login Page def login(request): username = request.POST.get('username') password = request.POST.get('password') try: user = auth.authenticate(request, username=username, password=password) if user is not None: auth.login(request, user) else: context = {'': ''} return render(request, 'website/login.html', context) except: print() # Logout Page def logout(request): auth.logout(request) settings.py AUTHENTICATION_BACKENDS = ("django_python3_ldap.auth.LDAPBackend",) LOGIN_REDIRECT_URL = '/website/home' LOGOUT_REDIRECT_URL = '/website/login' home.html <a class="navbar-item " href="{% url 'logout' %}" style="color: #ff0000"> Logout </a> -
How do I retain expanded dropdown menu in a new fresh page?
It is a bit hard to explain what I am asking. So, I am explaining it using some snapshot step by step. Initially when I load page, page looks like this: If I click on Python Basics and Python Advanced links it will look like this: If I choose a link like Python Variables [see above pic] this will show up: as you can see, I am in Python Variables page and dropdown menus are collapsed, that is not what I want, I want it to look like this after clicking Python Variables link: I mean even after clicking new link I want it to retain its previous expaned dropdown menu in new page. Is this possible to achieve? How do I do it? This link shows exactly what I want my side bar to look like when I click a new link on side bar links? This is the code of side bar: <div class="sidenav"> {% for sub_cat in sub_cats %} <button class="dropdown-btn"> {{ sub_cat.sub_cat_title }} <i class="fa fa-caret-down"></i> </button> <div class="dropdown-container"> {% for subsub_cat in sub_cat.subsubcategory_set.all %} {% url 'tutorials:tutorials' subsub_cat.subsub_cat_parent.sub_cat_parent.cat_slug subsub_cat.subsub_cat_parent.sub_cat_slug subsub_cat.subsub_cat_slug as tutorial_link %} <a href="{{ tutorial_link }}" class="{% if request.path == tutorial_link %}working{% endif %}" … -
Does Django support named parameters when executing custom SQL?
I want to execute some custom SQL in Django using named parameters (aka pyformat), e.g. .. WHERE name=%(name)s. I've noticed that the docs only mention using %s placeholders, and not named parameters. Is the pyformat style supported by Django? -
HOw to rebuild Django tables?
I was having problems with my dB, so I dropped the tables for one of my Django apps. I then ran makemigrations for the app and tried to migrate. It said everything was up to date. It didn't re-create the dropped tables. How can I get Django to re-build the tables? -
Django Rest Framework: other URLs overwritten when including default router
I have a directory as follows manage.py base_app/ urls.py settings.py etc... app1/ urls.py models.py etc... My API routes seem to be overwritten, when I include app1/urls.py in my base_app. For instance, in base_app/urls.py, if I have the following: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), url(r'^schema/$', schema_view), ] Then my schema lists all of the rest-auth API endpoints. Yet when I include the API endpoints from app1 urlpatterns = [ url(r'^', include('app1.urls')), url(r'^admin/', admin.site.urls), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), url(r'^schema/$', schema_view), ] Then I lose the rest-auth endpoints and end up with only app1's endpoints. I think the issue is either in how I'm setting up app1's urls.py or with how I am screwing with the namespace improperly in base_app/urls.py. app1/urls.py appears as follows (imports not included): router = DefaultRouter() router.register(r'app1', views.App1ViewSet, base_name="app1") urlpatterns = router.urls How do I properly separate the namespace between rest-auth's and app1's APIs? -
How can I convert this SQL query to a Django ORM statement?
I have 3 models: #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 I want to execute the below query using Django ORM: SELECT d.first_name, d.last_name, d.specialty, d.address, a.scheduled FROM appointment as a LEFT JOIN patient as p ON p.id=a.patient_id LEFT JOIN doctor as d ON d.id = a.doctor_id WHERE p.user_id = '12345'; I've come up with this statement: ret = Appointment.objects.filter(patient__user_id='12345').values_list('doctor__first_name', 'doctor__last_name', 'scheduled') but upon examining its raw query (ret.query) I can see that this is translated to a set of INNER JOINS. Is there a way to get the query I want? -
Get unique together constraint name in db in Django
How can I get the name of a unique together constraint in Django? It seems to be generated quite randomly to e.g. book_membership_collection_id_order_c52e778f_uniq, and I need to programatically get this name to do something with RunSQL -
PyDev can autocomplete inherited method names but not field names
So i'm into django quickstart tutorial, and i'm currently using the latest pydev on the eclipse version of 2019-03 (4.11.0). Here's a code snippet: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.order_by('-pub_date')[:5] I tried navigating (F3) on generic.DetailView, and it works fine. I tried typing def [ctrl+space] and i can see what methods to override, including get_queryset. What i dont get is when i tried to ctrl+space on the field section in hope to see template_name or context_object_name but cannot find them, even after i tried narrowing them by typing the field name. Navigating to parent types work, and pydev can also see inherited methods, but why not the inherited fields ? -
How to pass a date object as a url parameter in a django template?
On the index page, I display a list of datetimes. I want every date to be clickable and lead me to another page. This other page will have information pertinent to the datetime the user clicked, and hence I would need to pass the datetime object as a URL parameter. I am not sure how to proceed. My view can have a parameter date, but I don't know (1) which regex to use in the URL and (2) if I have to convert it into a string (and how to do it). I am able to display it using {{ datetimeobject|date:'d-m-Y H:i' }} using a for loop. {% block content %} <p>List of <strong>{{ type }}</strong> measurements on <strong>{{ detector_id }}</strong>.</p> <ul> {% for dt in datetime_list %} <li>{{ dt|date:'d-m-Y H:i' }}</li> {% endfor %} </ul> {% endblock %} def other_page(request, datetime): -
I want to write a 75000x10000 matrix with float values effectively into a database
thanks for hearing me out. I have a dataset that is a matrix of shape 75000x10000 filled with float values. Think of it like heatmap/correlation matrix. I want to store this in a SQLite database (SQLite because I am modifying an existing Django project). The source data file is 8 GB in size and I am trying to use python to carry out my task. I have tried to use pandas chunking to read the file into python and transform it into unstacked pairwise indexed data and write it out onto a json file. But this method is eating up my computational cost. For a chunk of size 100x10000 it generates a 200 MB json file. This json file will be used as a fixture to form the SQLite database in Django backend. Is there a better way to do this? Faster/Smarter way. I don't think a 90 GB odd json file written out taking a full day is the way to go. Not even sure if Django databases can take this load. Any help is appreciated! -
upon submission of form no reverse found
no reverse match found ,i tried with the urls but in vain kindly take me through it .being new in django i tried to setup different urls and properly rendering of html but in vain THIS IS THE CODE: def homeview(request): form=Formm() if request.method=='POST': form=Formm(request.POST) if form.is_valid(): form.save() return redirect('helll:see') else: form=Formm() return render(request,'helll/myform.html',{"form":form}) def see(request): dataa=Person.objects.all() return render(request,'helll/index.html',{"dataa":dataa}) def edit(request,id): dataa=Person.objects.get(pk=id) dataa.save() return render(request, 'helll/myform.html', {'dataa':dataa}) this is the part of html file <a href="{% url "helll:edit" Person.pk %}"><button>edit</button></a> this is url: app_name='helll' urlpatterns = [ path('',views.homeview,name='home'), path('see/', views.see, name='see'), path('edit/<int:pk>', views.edit, name='edit'), ] -
How to identify specific client request in Django?
I am new to Django. I am developing Django web application which accepts the login credentials and saves it. How can to identify the specific client each time when client connects with the Django server? I have seen Token Authentication with Django REST Framework but I need to retrieve the password to send it to other application. Can anyone please help? -
Can I tell Django run some function after file is uploaded through admin panel?
I have models like this: class NameReplacements(models.Model): excel_file = models.FileField(upload_to='excel_files') class NameReplacement(models.Model): name_to_replace = models.CharField(max_length=255, default='') name_to_replace_with = models.CharField(max_length=255, default='') I am uploading the file for NameReplacements through admin panel. Elsewhere in my app I have some code that reads the file from the latest instance of this model and saves data from each row of this file as NameReplacement instance: def remove_old_name_replacements(): '''Removes all instances of NameReplacement from database''' replacements = NameReplacement.objects.all() replacements.delete() def import_name_replacements(): '''Imports name replacements to database from last uploaded Excel file''' remove_old_name_replacements() replacements = NameReplacements.objects.last() df = pd.read_excel(replacements.excel_file.path) for i in range(len(df)): name_to_replace=str(df.loc[i, 'managers']), name_to_replace_with=str(df.loc[i, 'best_matches']) name_replacement = NameReplacement(name_to_replace, name_to_replace_with) name_replacement.save() Currently I just run import_name_replacements manually from the shell whenever I upload a new file. My question is: is there a way to tell Django to run this code automatically whenever I upload the file through admin panel? -
Add a custom header on request Django middleware
I want to implement a middleware in django, that will append a header on the request's existing headers, before the get_response(request) function. Though, when trying like this: request.headers['CUSTOM_HEADER'] = 'CUSTOM_VALUE' I get an error: 'HttpHeaders' object does not support item assignment Also in django's request (WSGIRequest), there is no add_headers function like the python's request module. Any ideas on how this can be accomplished?