Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Find bots in SMS registration and verification
I am implementing an SMS registration system for my Django project. like Whatsapp or telegram messenger, users can register and login just with mobile number. and OTP code. But i found a problem in my application. when user enter his number, my app send an OTP to user with SMS. he can't request new OTP with SMS in less than 3 minutes. and a user can request totally 10 OTP with SMS in a day. but if a hacker write a bot to enter different mobile number, my app can't detect that. for example a bot that has a dictionary of 10000 mobile numbers, enter this numbers one by one. my app just send OTP with sms to 10000 different mobile number. and I will have to pay a lot of many to my SMS service provider. how can i prevent from this problem? how messengers like Whatsapp solve this problem? -
.env not working with Django with supervisor
I have a Django 2.2 project and all secrets are in .env file. I'm using a library dotenv to load .env to the Django application in the manage.py file import dotenv def main(): # Read from .env file env_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), '.env') dotenv.read_dotenv(env_file) .... The environment file is working and is loaded well when running locally. On the server, I'm using the supervisor to run the application with the following configuration. [supervisord] [program:myapp] command=/var/www/html/app/start_gunicorn.sh directory=/var/www/html/app/ autostart=true autorestart=true stopasgroup=true stopsignal=QUIT logfile=/home/ubuntu/log/supervisor/supervisor.log logfile_maxbytes=5MB logfile_backups=10 loglevel = info stderr_logfile=/home/ubuntu/log/supervisor/qcg-backend.err.log stdout_logfile_maxbytes=5MB stdout_logfile_backups=10 stdout_logfile=/home/ubuntu/log/supervisor/qcg-backend.out.log stderr_logfile_maxbytes=5MB stderr_logfile_backups=10 But the environment variables are not loaded and not working in Django. Running following command from SSH console is working. python manage.py shell import os os.environ.get('DEBUG') > True But running the application, environment variables are not accessible and not applied in the application. -
Python 3 (Django). Request.GET and Unicode
How can I decode value from request.GET if it in unicode? def find_streets(request, qs=None): city_name = request.GET.get('city_name') print(request.GET.get('city_name')) # %u041C%u043E%u0441%u043A%u0432%u0430 # (Москва) qs = models.Streets.objects.values_list('street_name', flat=True).filter(city__city_name=city_name) If I filtering english word - I successfully get results, but if I filter russian word - result is empty. For example, russian word Москва returns from request.GET in unicode as: %u041C%u043E%u0441%u043A%u0432%u0430 Encoding this to utf-8 returns the same value. How to convert %u041C%u043E%u0441%u043A%u0432%u0430 into Москва or how to filter DB data using this unicode value? -
How to show child of parent in template?
I have the following models: class Category(models.Model): cat_image = models.ImageField(upload_to='Category',null=True, blank=True) cat_title = models.CharField(max_length=250) cat_overview = models.CharField(max_length=500) cat_slug = models.SlugField(unique=True) class SubCategory(models.Model): sub_cat_image = models.ImageField(upload_to='SubCategory',null=True, blank=True) sub_cat_title = models.CharField(max_length=255) sub_cat_overview = models.CharField(max_length=500) sub_cat_parent = models.ForeignKey(Category, on_delete=models.CASCADE) sub_cat_slug = models.SlugField(unique=True) class SubSubCategory(models.Model): subsub_cat_title = models.CharField(max_length=150) subsub_cat_parent = models.ForeignKey(SubCategory, on_delete = models.CASCADE) subsub_cat_slug = models.SlugField(unique=True) I already filled these models with some data and I have no problem showing Category model in templates but there is a problem when I want to show SubCategory and SubSubCategory simultaneously in one template. these are the categories, but when I click on "Python" for instance. This pages shows up: the problem as you can see in above code is that only python syntax, Python Variables and Python loops belongs to Python Basic not Python Files and Python Logs. How do I avoid this and show only related instances of SubSubCategory associated to SubCategory model? Codes associated to above image: views.py def home(request): return render(request, 'tutorials/home.html', {'categories':Category.objects.all()}) def sub_cat(request, category): sub_cats = SubCategory.objects.filter(sub_cat_parent__cat_slug=category) subsub_cats = SubSubCategory.objects.filter(subsub_cat_parent__sub_cat_parent__cat_slug = category) context = { 'sub_cats': sub_cats, 'subsub_cats': subsub_cats, } return render(request, 'tutorials/sub_cat.html', context) and sub_cat.html <div class="row"> <div class="col-md-3"> <div class="sidenav"> {% for sub_cat in sub_cats %} <button class="dropdown-btn"> … -
How do you set up pycharm community edition to support django unit tests where the IDE runs the unit test?
I can run my unit tests using django manage.py test. However, I want to be able to debug my tests using the pycharm community IDE. Is this supported? Every time I run the unit test in the IDE I get the following error: TypeError: argument of type 'ConnectionHandler' is not iterable How should I configure the IDE?