Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get image and show image simultaneously on django
I'm using Django to upload an image and show it simultaneously on the webpage. How can I do this? Most of the tutorials available describe how to fetch it after the image has been uploaded on a separate url, but that's not what I want. (For example, https://www.geeksforgeeks.org/python-uploading-images-in-django/ ) {% load static %} <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="{% static 'styles.css'%}" rel="stylesheet"> </head> <body> <div class="container"> <div class="row justify-content-center"> <div class="col-xs-12 col-sm-12 col-md-6 text-center"> <h1>Sudoku Spoiler</h1> </div> </div> </div> <div class="container"> <div class="row justify-content-center"> <div class="col-12 text-center"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-primary">Upload</button> </form> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script src="{% static 'main.js' %}"></script> </body> </html> from django.shortcuts import render,redirect from .forms import * from django.http import HttpResponse # Create your views here. def image_view(request): if request.method=='POST': form = hotelForm(request.POST,request.FILES) for element in request.FILES: print(element) if form.is_valid(): form.save() print("form is valid") return redirect('success') if request.method=='GET': #this line is referred later imgs = Hotel.objects.all() return render(request,'djangoform.html',{"images":imgs}) else: form = hotelForm() return render(request,'djangoform.html',{"form":form}) def success(request): return HttpResponse('successfully uploaded') What I tried to do is insert a line of code that checks if the request … -
How do I compare the current time with time saved in database using django?
I'm making a simple Timetable web app to display current lecture ad subject after fetching the device time and match it with django database time. My database is having columns for Day, Time and Subject. General Sql query be like SELECT * FROM tablename WHERE timecolumn >= '12:00' AND Daycolumn = 'Monday' I am very new to django I only figure out to display the data like that but unable to understand about comparing it and then only display. {% for subject in subjects %} {{ subject }} {% endfor %} -
the command "python manage.py tenant_command shell" is not working
I am using django-tenant-schemas and the following command is not working. Does anybody know how I can run shell command on a tenant? python manage.py tenant_command shell Error: TypeError: Unknown option(s) for shell command: skip_checks. Valid options are: command, force_color, help, interface, no_color, no_startup, pythonpath, settings, stderr, stdout, traceback, verbosity, version. -
Convert Django Views to rest services
I have an application created long back, now client want to expose its some of views as APIs without breaking existing functionality, so that they can directly consume APIs using REST Tools to see the reports. Is there any easier way, I can convert my function to a REST View. P.S - I kept code shorter here to keep question simple, but in fact, its much complex in the actual app. eg. URL : - `path('/users', views.show_user_details, name='users'),` VIEW def show_user_details(request, user_id): users = User.objects.all() return render(request, "Users.html", {"users":users}) In REST Views, I want it to convert its input and output so that it can be accessible with same urls(or with little modifications), without much updating the existing views. `path('rest/users', views.show_user_details, name='users'),` #-- I am ok to add new url like this, but without much change in existing view . def show_user_details(request, user_id): users = User.objects.all() return JsonResponse({"users":users}) -
too many values to unpack (expected 2) - Django SQL exception
I am writing basic sign up view code with the Django framework. I have the following code: def register(request): if request.method == 'POST': username = request.POST.get("username") password = request.POST.get("password") email = request.POST.get("email") firstname = request.POST.get("firstname") lastname = request.POST.get("lastname") userObj = User.objects.filter(username) if userObj.exists(): return HttpResponse("username already exists") emailObj = User.objects.filter(email) if emailObj.exists(): return HttpResponse("email already exists") newUser = User.objects.create_user(username, email, password, first_name=firstname, last_name=lastname) if newUser is not Null: newUser.save() # render main menu page return HttpResponse("user successfully registered") else: return HttpResponse("error creating newUser") the failure is because of the lines userObj = User.objects.filter(username) and emailObj = User.objects.filter(email) here is part of the trace: Traceback (most recent call last): File "G:\Program Files\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "G:\Program Files\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "G:\Program Files\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\Programming\project3\orders\views.py", line 21, in register userObj = User.objects.filter(username) File "G:\Program Files\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "G:\Program Files\lib\site-packages\django\db\models\query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "G:\Program Files\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "G:\Program Files\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "G:\Program Files\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q … -
Django - Images won't upload and change in my profile page
I'm working on my website's profile page. Changing the username or the email works but not the profile picture and I don't understand why :( I added my profile app in "INSTALLED_APPS", set MEDIA_ROOT and MEDIA_URL and set urlspatterns : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'inscription.apps.InscriptionConfig', 'profil.apps.ProfilConfig', ] [...] MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' urls.py : urlpatterns = [ path('profil/', p.profil, name='profil'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I linked the user to its profile and I set the default image in models.py from django.db import models from django.contrib.auth.models import User class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='defaut.png', upload_to='image_profil') def __str__(self): return f'{self.user.username} Profil' admin.py : from django.contrib import admin from .models import Profil admin.site.register(Profil) Then I created the profile modification form in forms.py : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profil class FormulaireModifUtilisateur(forms.ModelForm): username = forms.CharField( label = 'Nom de compte', min_length = 4, max_length = 150, initial=User.username, ) email = forms.EmailField( label = 'Email', min_length = 4, max_length = 150, ) class Meta: model = User fields = ['username', 'email'] class FormulaireModifProfil(forms.ModelForm): image = forms.FileField( label = 'Image de profil' ) class Meta: … -
Django update selectize on new foreign key in admin template
Some back story: I have overridden Django admin templates completely. Everything works fine. In the change_form.html, I have initialized the selectize.js through the following script: <script> $('select').selectize({ create: false, sortField: 'text', }); </script> Now, everything looks and works fine but I'm having a little problem when I click the add button on in the related_field_wrapper for that foreign key. I press it, the pop-up opens and the object gets created for that model but it doesn't update selectize for that field. Like it doesn't show it in the selectize options list but if I don't change anything else on that select field, it actually doesn't show that the object is selected but upon saving, it saves the newly created object in that field. This means that the field is being set in the select field but selectize just doesn't update. I understand that this might be a very specific request and that it's less Django related and more JS/Selectize related but I'd really appreciate some help. A starting point, I think would be to know what functions are performed upon creating a new object or updating Selectize when a new object is created. I'm lost guys. Thank you for reading … -
a raw sql query is not working in django framework. I am getting "TypeError at / not all arguments converted during string formatting"
select *from table_name where name = %s",params={"name1","name2"} full_code: from django.shortcuts import render from . models import destination def index(request,params = None): dests1 = destination.objects.raw("select *from travello_destination where name = %s",params={'Bangalore','Mumbai'}) return render(request,'index.html', {"dests":dests1}) -
debugging selenium LiveServerTestCase in vscode
I run functional tests in django using the LiveServerTestCase class. When I want to write a new test, I put a breakpoint in vscode, then inspect the page to work out the selenium command which will activate the next step. I run it in the DEBUG CONSOLE, wait for the next page to load and repeat the process: inspect, write command in DEBUG CONSOLE, wait for next page to load. That's worked great for me in the past, but now it no longer works. I'm not sure if I inadvertently changed a setting, or if django or vscode updates have broken the process, but when I run the next selenium command in the debug window, the browser window just sits there with a status message "waiting for localhost..." ; sometimes 5 or 10 minutes later it will advance. Anyone else had experience with writing Selenium scripts this way who has an idea why the server thread in vscode seems no longer to respond when it is stopped at a breakpoint? My vscode's launch.json entry: { "name": "test particular functional test", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "args": [ "test", "functional_tests.tests.test_selenium.test_coach_with_no_students", ], "django": true }, I'm not supposed to … -
No Reverse Match - django.urls.exceptions.NoReverseMatch
django.urls.exceptions.NoReverseMatch: Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/(?P[^/]+)$'] [18/Apr/2020 14:05:02] "GET /checkout/ HTTP/1.1" 500 157543 <--- this is the error message I am getting in terminal when I try to go onto the checkout page. view.html {% for item in cart.products.all %} <tr><td> {{ item }} </td><td>{{item.price}}</td> <td><a href='{% url "update_cart" item.slug %}'> Remove</a></td></tr> {% endfor %} </table> <br/> <a href='{% url "checkout" %}'>Checkout</a> {% endif %} </div> </div> {% endblock content %} views.py for orders from django.urls import reverse from django.shortcuts import render, HttpResponseRedirect # Create your views here. from carts.models import Cart def checkout(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse("fuisce-home")) context = {} template = "fuisce/home.html" return render(request, template, context) urls.py from django.urls import path from . import views from carts import views as cart_views from orders import views as order_views urlpatterns = [ path('', views.home, name='fuisce-home'), path('subscription/', views.subscription, name='fuisce-subscription'), path('oneoff/', views.oneoff, name='fuisce-oneoff'), path('about/', views.about, name='fuisce-about'), path('contact/', views.contact, name='fuisce-contact'), path('cart/', cart_views.view, name='cart'), path('cart/<slug>', cart_views.update_cart, name='update_cart'), path('checkout/', order_views.checkout, name='checkout'), ] the problem seems to arise when i move the HttpResponse from just below def checkout, to below cart = Cart.objects.get(id=the_id). (change in code attached below). anyone know … -
Does Full-Stack Web Development Violate DRY?
I'm planning on using Django with ReactJS to build a GUI for a complicated database. In order to have features such as auto-completing searching for particular fields, etc, I suppose that using JavaScript is necessary. Is there a way to reuse the models that I made in Python so I don't have to repeat a bunch of code in writing the Django serializers for a REST API and in the models in ReactJS? -
Watching for file changes with StatReloader
I try to use docker in order to make the process of launching my django app automatically. I built the image, then executed the command docker run <image>. But everything I see is the line Watching for file changes with StatReloader and nothing happens. What am I doing wrong? -
How to add chatting application to django website
I want a very basic simplest way for users on website to chat. How can I do it? can I integrate any chat platform with it, like hangouts or etc. I was thinking I can use emails in any way but that would so brute. suggest easy to implement and basic methods because it is a large website and chatting is not its core part. -
Google Maps API Error: This API key is not authorized to use this service or API. Places API error: ApiTargetBlockedMapError
I've started getting this error from a Google Maps widget within a CMS I use: This API key is not authorized to use this service or API. Places API error: ApiTargetBlockedMapError The error message provides a helpful link to this page, which includes the following text: ApiTargetBlockedMapError Error The Maps JavaScript API has not been authorized for the used API key. Please check the API restrictions settings of your API key in the Google Cloud Platform Console. See API keys in the Google Cloud Platform Console. For more information, see Using API Keys. I know Google has tweaked this API in the past, so I went to the console and checked the permissions given for the key I am using. It includes these four permissions, include the Maps JavaScript API permission: Geocoding API Maps Embed API Maps JavaScript API Maps Static API The only part not working is the address auto-complete. When I change to Don't Restrict Key mode so the key works with all services, it works fine. Any idea which service checkbox I might be missing? I'm wondering if Google is just displaying the wrong error. Any ideas? -
Accessing a Subclass Model Data while Searching for it's parent class in Django
I don't really know how to explain my problem well enough but i'll give it a shot. We have the default User model, an extention to an Employee model and then an extension to that, Timesheet. Each employee can have many timesheets and each Employee only has one User. I want to create code which searches for the username, stored in User and then returns all the timesheet objects for that user. This is my current view Given the code Views.py: class EmployeeSearchView(PermissionRequiredMixin, ListView): permission_required = ('zapp.can_approve') model = User template_name = 'zapp/search_timesheet.html' def get_queryset(self): query = self.request.GET.get('q') object_list = User.objects.filter(username__iexact=query) return object_list and my current template {% extends 'zapp/base.html' %} {% block content %} <h2>Submit new timesheet</h2> <form method="POST" class="timesheet-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} If no solution can be provided with my little information where could I find in the docs something which talks about this? Thanks! -
Django.forms.fields.booleanfield Object at when iterating through a list of fields
I want to iterate through a list of checkboxes. When I use a single checkbox it works, but when I iterate through the checkboxes, I get <DJANGO.FORMS.FIELDS.BOOLEANFIELD OBJECT AT 0X7FA2DA62B470> <DJANGO.FORMS.FIELDS.BOOLEANFIELD OBJECT AT 0X7FA2DA5A5940> It shouldn't be a list or tuple issue like in this one or similar questions I found. my forms.py: class TestForm(forms.Form): toggles = [forms.BooleanField(label="A Checkbox", required=False), forms.BooleanField(label="A second Checkbox", required=False)] single_toggle = forms.BooleanField(label="A single Checkbox", required=False) my template: {% for toggle in form.toggles %} {{ toggle }} {% endfor %} {{ form.single_toggle }} Expected output: Three checkboxes Actual output: <DJANGO.FORMS.FIELDS.BOOLEANFIELD OBJECT AT 0X7FA2DA62B470> <DJANGO.FORMS.FIELDS.BOOLEANFIELD OBJECT AT 0X7FA2DA5A5940> and a single checkbox. -
django.contrib.auth login() returning None issue
I am new to django and I have been trying to implement login system for my django project. template_name = 'rest_framework/login.html' if request.method == 'POST': email = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=email, password=password) print (login(request,user)) login(request,user) return redirect('core:home') return render(request, template_name) For some reason, the login function which I have imported from django.contrib.auth is returning None even when user has the correct user object after authenticating and request has POST request object. This is resulting in the user not getting added to the session and hence when I redirect it to core:home, I am getting AnonymousUser in request.user. Help would be appreciated. PS: I have written a custom backend for authentication. -
Customizing Django GenericRelation content_type values in Admin add/change view
My models are using GenericForeignKey and GenericRelations. For simplification my models structure is following: class BaseModel(models.Model): name = models.CharField(max_length=100) model_labels = models.GenericRelation('ModelLabel', related_query_name='%(class)s') model_types = models.GenericRelation('ModelType'), related_query_name='%(class)s') class Meta: abstract = True class ModelA(BaseModel): fieldA = models.CharField(max_length = 50) class ModelB(BaseModel): fieldB = models.CharField(max_length = 50) class ModelLabel(models.Model); label = models.CharField(max_length = 50) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() model_object = GenericForeignKey('content_type', 'object_id') class ModelType(models.Model): type = models.CharField(max_length = 50) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() model_object = GenericForeignKey('content_type', 'object_id') class Unrelated(models.Model): name = models.CharField(max_lenght = 50) The problem I am facing is in admin view for ModelLabel and ModelType. Right now, out-of-the-box I am getting 3 fields: Label or Type, Content type and Object id. Yes, this is correct according to the model. But in Content type I am getting not only ModelA and ModelB as an options. I'm also getting Unrelated and most of the individual fields of different models. According to documentation: Instances of ContentType represent and store information about the models installed in your project, and new instances of ContentType are automatically created whenever new models are installed. According to this Unrelated can appear in the values, but models' fields shouldn't. So why they … -
Reverse for 'beriNilai' with arguments '('SI 43 01',)' not found. 1 pattern(s) tried: ['grader/beriNilai/(?P<pk>\\d+)$']
im trying to print a data from table called t_pengguna where the kelas field is equal to the data that is being clicked by the user, so im trying to make something like select nama from t_pengguna where kelas = ....., i tried to pass the clicked data using parameter, but i got this reverse error, here is my urls.py file: url(r'^beriNilai/(?P<pk>\d+)$', tambahNilai, name='beriNilai') and here is my views.py file: def tambahNilai(request, pk):return render(request, 'grader/beriNilai.html', {'siswa' : t_pengguna.objects.filter(kelas=pk)}) and here is my html file, where i make the button to pass the parameter: <td> <a class="btn btn-sm btn-outline-primary" href="{% url 'beriNilai' matkuls.kelas %}"> <i class="fa fa-pencil-square-o" aria-hidden="true"></i> beri nilai </a> </td> anyhelp will be appriciated, thanks before, stay healty! -
Graphene mutation with many to many relationship arguments
I'm not sure it will be understandable... I have a model Reservation with a service which actually is a ManyToManyField. Actually I'm creating a CreateReservation mutation and one of the required field is service but I don't know how to enter more than one (service arguments). class CreateReservation(graphene.Mutation): reservation = graphene.Field(ReservationType) class Arguments: dog = graphene.String() date = graphene.types.datetime.DateTime() service = graphene.String() def mutate(self, info, dog, date, service): reservation = Reservation(dog=dog, date=date, service=service) reservation.save() return CreateReservation(reservation=reservation) -
2 step authentication with django rest framework
i am looking to implement a 2 step authentication into my django application. Previously , i have used the packaged django-two-step-auth , however im not fully sure if it is react and drf compatible. Has anyone successfully implemented a 2 step authentication process in their django x react application? I would love to know what packages there are out there. -
Best type of SQL to use with Django?
Is MySQL a good option to use with Django? I'm a beginner to Django -
How would you handle creating a response for a method that checks if an object is valid?
Lets say I have a Model in my models.py that stores financial transactions. The model has a method called is_valid() which basically checks that the object adheres to a bunch of business logics. This method has now got quite long, it does about 20 checks on the object and looks something like this: def is_valid(self): if self.something is something: return false if self.something_else is something: return false ... return true So far this has worked great, but I've now got to the stage where I no longer need to just know if an object is valid, but if it's not valid I need to know which check it failed. So something like: def is_valid(self): if self.something is something: return error1 if self.something_else is something: return error2 ... return true But, if the object has failed multiple checks then I'd want to know all the checks it has failed. What would be the most clean way of handling this? My code also has lots of lines that check is_valid() returns true, so ideally it would still return true if the object is valid, but if not valid then it would let me know which conditions it failed. -
Django Tutorial or Online Class
I am searching for a good Django tutorial and an online class. All recommendations will be very much appreciated. I've looked at tutorialspoint and a few others, but would like something more complete with more examples. -
Does Celery cache tasks? How can I reload changes in a dev environment?
When using Celery, Docker, RabbitMQ and Django (with django-celery-results and django-celery-beat) I am able to load a simple task following the tutorial. However, when I make changes to the task and reload the server (docker-compose down, docker-compose up) the changes are not reflected. Does Celery cache tasks somewhere / how to I reload them when in a dev environment? The tutorial sets CELERY_CACHE_BACKEND = 'django-cache' but I would assume this is destroyed by docker-compose down? celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() proj/__ init __ .py: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) tasks.py: from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def hello_world(): return print('hello world!') settings.py: CELERY_BROKER_URL = 'pyamqp://rabbitmq:5672' CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_BEAT_SCHEDULE = { 'hello': { 'task': 'proj.tasks.hello', 'schedule': crontab() # execute every minute } }