Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: Unable to configure handler 'file1' django with apache2 error
i am trying to run my django website with apache2 webserver on an ubuntu machine i configured everything almost as the django wsgi documentaion but when i try to open my website in the browser it dosen't work and it raises the following error ValueError: Unable to configure handler 'file1' i think the problem is related to the logging files i have in sittings.py itried to give the apache2 access to both of them but it didn't work sudo chown :www-data debug.log sudo chown :www-data info.log does any one know how i can fix this issue. here is my apache2 configuration file: <VirtualHost *:80> ServerAdmin admin@cryptobank.localhost ServerName cryptobank.localhost ServerAlias www.cryptobank.localhost DocumentRoot /home/hamzahfox/Desktop/CryptoBankApache ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/hamzahfox/Desktop/CryptoBankApache/static <Directory /home/user/django_project/static> Require all granted </Directory> Alias /static /home/hamzahfox/Desktop/CryptoBankApache/media <Directory /home/user/django_project/media> Require all granted </Directory> <Directory /home/hamzahfox/Desktop/CryptoBankApache/CryptoBank> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess cryptobank.localhost python-path=/home/hamzahfox/Desktop/CryptoBankApache python-home=/home/hamzahfox/Desktop/python/env/django-env WSGIProcessGroup cryptobank.localhost WSGIScriptAlias / /home/hamzahfox/Desktop/CryptoBankApache/CryptoBank/wsgi.py </VirtualHost> here is my wsgi.py file: """ WSGI config for CryptoBank project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CryptoBank.settings') application = get_wsgi_application() here is my sittings.py … -
Django get_serializer 'NoneType' object is not callable
I am testing an API of Django (DRF) application. I am calling http://127.0.0.1:8000/api/users/1/documents/ (1 - user id) And receive an error ... File "/app/backend/apps/users/views/users/views.py" in create 542. serializer = self.get_serializer(data=request.data) File "/usr/local/lib/python3.7/site-packages/rest_framework/generics.py" in get_serializer 110. return serializer_class(*args, **kwargs) Exception Type: TypeError at /api/users/1/documents/ Exception Value: 'NoneType' object is not callable How can i identify the problem? Request related view /app/backend/apps/users/views/users/views.py (problematic line is serializer = self.get_serializer(data=request.data)) class UserDocumentCreate(generics.CreateAPIView, generics.RetrieveAPIView): serializer_class = UserDocumentSerializer permission_classes = (UserIsOwner, IsAuthenticatedDriver) queryset = Document.objects.all() def get_serializer_class(self): if self.request.version == "1.0": return UserDocumentSerializer # return UserDocumentSerializer2 def create(self, request, *args, **kwargs): request.data._mutable = True request.data["owner"] = kwargs.get("pk") serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): owner = serializer.validated_data.get("owner") document_type = serializer.validated_data.get("document_type") message_status = request.data.get("message_status") documents = owner.document_owner.filter( document_type=document_type ) for document in documents: if document.status == DocumentStatus.DOCUMENT_REJECTED_STATUS: document.delete() # Mark user as new owner.is_new_user = True owner.save() self.perform_create(serializer) headers = self.get_success_headers(serializer.data) response = { "status": status.HTTP_201_CREATED, "result": serializer.data, } # accept corresponding registration message if message_status: driver_reg = DriverRegistration.objects.filter(user=kwargs.get("pk")).first() driver_reg.accept_by_status(message_status) next_id = driver_reg.get_next() # add information about next registration message to response if next_id != -1: response["next_message"] = REG_MESSAGES[next_id].to_json() return Response( response, status=status.HTTP_201_CREATED, headers=headers ) Related serializer (nothing special) class UserDocumentSerializer(serializers.ModelSerializer): is_new_document = serializers.BooleanField(read_only=True) class Meta: model = Document … -
super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'label'
Sir, my name is Karthik. I tried a multi-select-field project in Django. Based on my knowledge everything is correct. But, try to make migrations it shows TypeError. How to fix it. Please help me sir/madam. Error File "D:\My Django Projects\multiselectproject\multiselectapp\forms.py", line 4, in class EnquiryForm(forms.Form): File "D:\My Django Projects\multiselectproject\multiselectapp\forms.py", line 30, in EnquiryForm course = MultiSelectField(label='Select Required Courses:', choices='Courses_Choices') File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\multiselectfield\db\fields.py", line 70, in init super(MultiSelectField, self).init(*args, **kwargs) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields_init_.py", line 986, in init super().init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'label' settings.py """ Django settings for multiselectproject project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'n&*#@g^b-%-$-yd1^!iwzhfnttd4s^zf+&$*5!i0_ves1v8s4&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multiselectapp.apps.MultiselectappConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Django 3.1: Choice of static files directory
I have seen different ways in tutorials where the static files directory keep on changing. 1. Some put static files in the project root directory. Example myproject |__blog | |__migrations | |__static | |__templates mysite | static |__blog |__css |__js 2. Some put the static files in the root directory of the app it is serving. Example myproject ├── blog │ ├── migrations │ ├── static │ └── templates └── mysite Where should static files be located? -
authenticate a user in django
How to authenticate a user(model) in django? according to django docs we can use below method for authenticate users, user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return redirect('/profile') i had tried above, it success,but it works only for built-in user models that comes with admin panel. my problem is: i had created a model(Customer) in models.py with custom fields,ex.phone number from django.db import models class Customers(models.Model): first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) phone=models.CharField(max_length=15) email=models.EmailField() password=models.CharField(max_length=500) signin.html <form action="/login/" method="POST"> {% csrf_token %} <input type="email" name="email" placeholder="Enter email"> <input type="password" name="password" placeholder="Password"> <input type="submit" value="submit"> </form> In views.py def login(request): if request.method=='POST': email= request.POST.get('email') password= request.POST.get('password') user = Customers.authenticae(email=email, password=password) if user is not None: user.login(request, user) return redirect('/profile') return render(request,'login.html') when i tried this, it says: type object 'Customers' has no attribute 'authenticae' do i need to create authenticate() function in models.py, or there is a method for this? how to authenticate my customer,i just started learning django framework, anyone helps me to achieve this. -
I have a problem with urls in django, and I have "Page not found"
I started to learn Django myself, and there is a problem with understanding how URLs and path work. The error message is: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/question/1/ Using the URLconf defined in not_bad.urls, Django tried these URL patterns, in this order: [name='index'] [name='detail'] [name='results'] [name='vote'] microsanya/ The current path, question/1/, didn't match any of these. In project files I have this code: not_bad\urls.py: from django.contrib import admin from django.urls import include from django.urls import path urlpatterns = [ path('', include('polls.urls')), path('microsanya/', admin.site.urls), ] polls/urls.py: from django.urls import include, path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('', views.detail, name='detail'), path('', views.results, name='results'), path('', views.vote, name='vote' ), ] polls/views.py from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from django.shortcuts import redirect from django.shortcuts import render from django.http import Http404 from . models import Question, Choice def index(request): question = Question.objects.all() return render(request, "index.html", {"latest_questions": Question.objects.order_by('-pub_date')[:5]}) def detail(request, question_id): def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404 return render(request, 'polls/answer.html', {'question': question}) def answer(request, question_id): question = get_object_or_404(Question, pk=question_id) try: question = question.question_set.get(pk=request.POST['question']) except (KeyError, Question.DoesNotExist): return render(request, 'answer.html', {'question': question, 'error_message': 'Question does not exist'}) else: … -
fields added in Django View not displayed with django-crispy-forms
I have this view (modified to make it simple to understand): class MyCreateViewView(CreateView): model = SomeModel def get_form(self, form_class=None): form = super().get_form(form_class) form.helper = FormHelper(form) form.fields['additional_field'] = forms.BooleanField(label="Something", required=False) form.helper.add_input(Submit('submit', "Submit")) return form Before adding the FormHelper, the field additional_field appeared on the template. Now it doesn't. The form in my template is basically one line: {% crispy form %}. The django-crispy-forms docs don't show this approach because they are focused on using forms. I'm using the CreateView from Django that builds the form for me, so I don't need a form class. So far, I noticed that doing form.helper = FormHelper(form) after programmatically adding the new field solves the problem. But this is not a solution because the view I presented here is a simplified version, and I actually have two views that are doing something similar. So I'm inheriting this class and adding extra fields in the views themselves (meaning FormHelper is already there). -
Django Ckeditor: How to change background color/styling
I am having trouble changing the background color of the rich text editor. Most places say to edit the ckeditor css file but that isn't in my django project for the way i'm doing it i think. Is there a way to change it/add styles in the settings configs? or is there a better way to do this? template: <script type="text/javascript" src="ckeditor.js"> window.CKEDITOR_BASEPATH = '/static/ckeditor/ckeditor/'; CKEDITOR.replace( 'links' ); </script> settings file: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'toolbar_Custom': [ ['Link', 'Unlink'], ], 'height': 200, 'width': 750, 'stylesSet': [ { "name": 'Lead', "element": 'p', "attributes": {"margin-top": "10px"}, }, ], } } -
Django Rest Framework view doesn't work when called from DRF API tool
I have the following DRF ViewSet: class ServiceStatusForListViewSet(CustomModelViewSet): pagination_class = None permission_classes = (permissions.IsAuthenticated,) queryset = models.ServiceStatus.objects.all() serializer_class = serializers.ServiceStatusForListSerializer filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,) search_fields = ('service__item__product__name', 'service__client_name') filter_fields = ('id', 'service', 'service__item', 'service__item__product') This view works perfectly when a GET request is sent by a React frontend application, and it returns the expected response: The problem is when I send a GET request from the browser (Chrome): It just never returns, and the "loading" indicator keeps spinning forever. All other endpoints work well from DRF API tool, but this one. -
How can I loop the list into another loop in the Django template?
I need to loop a list into another loop without duplicating the results for example: {% for x in list1 %} {% for y in list2 %} {{ y }} {% endfor %} {% endfor %} I found half of the problem where I can call the elements of a list by a dot followed by the index number for instance: {{ iterator.0 }} {{ iterator.1 }} and that is succeded indeed however I took a little thinking where I thought that I could use: forloop.counter0 for looping but I couldn't use it I tried to use it like so: {{ iterator.forloop.counter0 }} but the trick didn't succeed. so, How can I loop easily into another loop? -
For loop in Django template causing error when I use the add filter
I am trying to add two variables together in my template that will combine two scores together and print the value. The problem is when the loop gets to a game that hasn't happened yet it kicks out an error because the variable doesn't exist yet. What am I supposed to add to skip games in the loop that have no score? {% for game in games %} <p class="light-blue text-center"> Total: {{ game.scoreboard.score.home|add:game.scoreboard.score.away }} </p> {% endfor %} -
Registration form refreshes after submitting instead of sending post request in django
I'm trying to register a user but the page refreshes instead of submitting the data. At the initial stage of my project, it was working properly but when I added some more models and form it's not working and tried to register it stopped working. and it also doesn't throw any errors views.py from django.shortcuts import render from django.contrib.auth import authenticate,login,logout from .models import * from django.http import HttpResponseRedirect from django.urls import reverse from .form import * from django.db import IntegrityError from django.contrib.auth.decorators import login_required from django.contrib import messages # Create your views here. def index(request): if not request.user.is_authenticated: message = f"please sign in" else : message = f"signed in as {request.user}" return render(request, "auctions/index.html",{ "listings": Listings.objects.all(), "message": message }) def login_view(request): if request.method == "POST": form = loginForm() email = request.POST["email"] password = request.POST["password"] user = authenticate(request,username=email,password=password) if user is not None: login(request,user) return HttpResponseRedirect(reverse('index')) else: return render(request, "auctions/login.html",{ "form": form , "message": "username/password not valid" }) return render(request, "auctions/login.html",{ "form": loginForm() }) def logout_view(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): if request.POST == "POST": form = registerForm() email = request.POST["email"] # check passwords are same password = request.POST["password"] confirmation = request.POST["id_confirmation"] if password != confirmation: return render (request, "auctions/register.html",{ … -
Accordion expands all cards when clicked at any one
{% for inv in invoices__ %} <div class="row"> <div class="col-md-12"> <div class="accordion" id="accordionExample"> <div class="card"> <div class="card-header" id="{{inv.headingId}}"> <div class="row headerContiner"> <div class="col-md-10"> <h5 data-toggle="collapse" data-target="{{inv.collapseTarget}}">{{inv.ttl}}</h5> </div> <div class="col-md-2"> <a href="{% url 'invoice_update' inv.id__ %}" class="btn text-secondary px-0"> <i class="fa fa-edit fa-lg"></i></a> <a href="{% url 'invoice_delete' inv.id__ %}" class="btn text-secondary px-0"> <i class="far fa-trash-alt fa-lg text-danger float-right"></i></a> <a href="{% url 'invoice_details' inv.id__ %}" class="btn text-secondary px-0"> <i class="fas fa-file-invoice"></i></a> <a href="{% url 'invoice_status' inv.id__ %}" class="btn text-secondary px-0"> <i class="fas fa-tasks"></i></a> </div> </div> </div> <div id="{{inv.collapseId}}" class="collapse" aria-labelledby="{{inv.headingId}}" data-parent="#accordionExample"> <div class="card-body"> <div class="row"> {% for stg in inv.stages %} <div class="col-md-3 stags"> <h6 class="stepHeading">Step {{stg.counter__}}: {{stg.title}}</h6> <p>HTML stands for HyperText Markup Language. HTML is the standard markup language for describing the structure of web pages. <a href="https://www.tutorialrepublic.com/html-tutorial/" target="_blank">Learn more.</a></p> {% if stg.isCreated %} <a href="{% url stg.editLink inv.id__ %}" class="btn text-secondary px-0"> <i class="fa fa-edit fa-lg"></i> </a> <a href="{% url stg.deleteLink inv.id__ %}" class="btn text-secondary px-0"> <i class="far fa-trash-alt fa-lg text-danger float-right"></i> </a> <a href="{% url stg.previewLink inv.id__ %}" class="btn text-secondary px-0"> <i class="fas fa-file-invoice"></i> </a> {% else %} <a href="{% url stg.addLink %}" class="btn text-secondary px-0"> <i class="fas fa-plus"></i></a> </a> {%endif%} </div> {% endfor %} </div> </div> </div> </div> … -
Running python IBM Cloud Apps Cloud Foundry with error in ModuleNotFoundError: No module named 'matplotlib'
After deployment in IBM Cloud - App Cloud Foundry using Python - Django I found the follow error running the container: APP/PROC/WEB 0 File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "<frozen importlib._bootstrap_external>", line 678, in exec_module 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "<frozen importlib._bootstrap>", line 665, in _load_unlocked 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 callback, param_dict = resolver.resolve_error_handler(500) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 141, in handle_uncaught_exception 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 103, in response_for_exception 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 response = response_for_exception(request, exc) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 49, in inner 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 response = self._middleware_chain(request) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in get_response 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 response = self.get_response(request) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 respiter = self.wsgi(environ, … -
create a model in django with conditions
I want to create an appointments model with Django, but with 2 conditions the first if the profile already exists than the appointments model use the information from the profile model, but if the profile dose doesn't exist than the user should fill the information in the appointments model this is my profile model class Profile(models.Model): GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'),) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) phone_number = PhoneNumberField(blank=True) photo = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) def __str__(self): return f'Profile for user {self.user.username}' and this is my appointments model class Appointments(models.Model): GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'),) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) profile = models.OneToOneField(Profile, on_delete=models.CASCADE)# if profile dose not exist this will be none date_of_birth = models.DateField(blank=True, null=True)# and the user should fill this information gender = models.CharField(max_length=1, choices=GENDER_CHOICES) # and the user should fill this information phone_number = PhoneNumberField(blank=True)# and the user should fill this information date_time = models.DateTimeField() so if the one who wanted to make the appointments have already a profile the information about the gender and date of birth come from his profile if there is no profile the user should be fill those information -
Allowing user to rename the django model field names visible to him
I have a model like below. I want the user to be able to change the "external" field names (i.e. what is visible to the user) using some form of Legend (the internal field names should be the same: Product.rating1 should not change). The user opens the Product form he sees the default name of the fields (e.g. 'Rating 1' is called 'Rating 1'). But the user should be able to change this in a different form (e.g. 'Rating 1' to 'Some random name'). This new rating name should now be changed for all Products. class Product(models.Model): name = models.CharField(max_length=200) rating1 = models.IntegerField(default=0) rating2 = models.IntegerField(default=0) rating3 = models.IntegerField(default=0) class Legend(models.Model): rating1_name = models.CharField(max_length=200, default='Rating 1') rating1_abbr = models.CharField(max_length=2, default='R1') rating2_name = models.CharField(max_length=200, default='Rating 2') rating2_abbr = models.CharField(max_length=2, default='R2') rating3_name = models.CharField(max_length=200, default='Rating 3') rating3_abbr = models.CharField(max_length=2, default='R3') Desired result: The Product's database table will contain several products. However, the database table of Legend will just contain one entry that is created from the start (automatically) and it will never be deleted, the fields will just be changed. What I want is basically to in one place of my app have a form that creates these Products and another form … -
why do developers still create separate dashboard for login to perform CRUD functions instead of using the inbuilt Admin that is shipped by Django
I am a novice in Django I am just wondering why most developers would create separate dashboards to login and logout to perform all the CRUD functions. Why go through all that trouble instead of using the shipped Admin panel and create your users and assign permissions/roles to them to perform basically all the CRUD functions. -
Extract only the last 7 days of data in Python
If I have such data and I want to extract only the last 7 days of data, how can I do that? I tried to use Pandas examples, but I got errors such as module 'pandas' has no attribute 'example' or 'list' object has no attribute 'example', so I could not get the data for seven days. Also, I'm using React for the frontend. When processing data like this, is it best to do it on the frontend side or the backend side? "daily_report": [ { "date": "2020/03/27", "count": 999 }, { "date": "2020/03/28", "count": 0 }, { "date": "2020/03/29", "count": 0 }, { "date": "2020/03/30", "count": 0 }, { "date": "2020/03/31", "count": 0 }, { "date": "2020/04/01", "count": 0 }, { "date": "2020/04/02", "count": 0 }, { "date": "2020/04/03", "count": 0 }, { "date": "2020/04/04", "count": 0 }, { "date": "2020/04/05", "count": 0 }, { "date": "2020/04/06", "count": 0 }, { "date": "2020/04/07", "count": 0 }, { "date": "2020/04/08", "count": 0 }, { "date": "2020/04/09", "count": 0 }, { "date": "2020/04/10", "count": 0 }, { "date": "2020/04/11", "count": 0 }, { "date": "2020/04/12", "count": 0 }, { "date": "2020/04/13", "count": 0 }, ] def get_daily_report(self, obj): data = Entry.objects.all().values( … -
how do I send a text field input from the frontend to the backend
I have made a website, it uses react as the frontend and Django as the backend. I am trying to get an input from the frontend and send it to the backend, it doesn't seem to be working. here's the code: searchSong(e) { this.setState({ search: e.target.value }); console.log(this.state.search) } this is what takes the text field input : <TextField id="outlined-basic" label="Song" variant="outlined" value={this.state.search} onChange={this.searchSong} /> <Button variant="contained" color="secondary" onClick={this.addButtonPressed}>Search Song</Button> these are the functions that send the text input from the frontend to the backend and the states : addButtonPressed() { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ search: this.state.search, }) }; fetch("/spotify/search-song/", requestOptions) } } searchSong(e) { this.setState({ search: e.target.value }); console.log(this.state.search) } the state : this.state = { search: "" } here's the function that I made which will test if I got the correct text field input : def search_song(session_id, song_name): search_letters = "playlist/?type=" + song_name print(search_letters) this is the view that uses the function : class SearchSong(APIView): lookup_url_kwarg = 'search' def post(self, request, format=None): if not request.session.exists(request.session.session_key): request.session.create() room_code = self.request.session.get(self.lookup_url_kwarg) music = str(request.data.get(self.lookup_url_kwarg)) room = Room.objects.filter(code=room_code)[0] search_song(room.host, music) this is the endpoint being called by the frontend : from … -
Django custom registration form html
New to Django and I am attempting to create a customer registration form and was successful. However the tutorial I followed showed me how to iterate through a loop, the contents of my registration_form which doesn't really give me much flexibility from a UI perspective, or so it seems. Can someone tell me how to customize this form based on the code I've got? HTML: <h1>This is the register.html</h1> <div class="col-md-4 offset-md-4"> <form method="post"> {% csrf_token %} {% for field in registration_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color: grey;">{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style="color: grey;">{{error}}</p> {% endfor %} </p> {% endfor %} <button type="submit">Register</button> </form> </div> views.py def registration_view(request): context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) return redirect('home') else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form print(context) return render(request, 'accounts/register.html', context) forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=100, help_text='Required. Add a valid email address') class Meta: model = Account fields = ('email', 'username', 'password1', 'password2', 'first_name', 'last_name') the form renders and works fine with registration, just looks kinda crappy. thanks! -
Changing language with React Native and django-modeltranslation
I would like to add option to mobile app to change language. Im using django on backend and RN as mobile. So I installed django-modeltranslation and added my model I want to translate. On mobile I display available languages. When user clicks on specific language I would like to get translated data. I have huge problem to create logic how to do it. I'm not asking about code just some hints and idea -
Make a dang form field read only after initialised
I have a ModelForm in forms.py as follows: class OrderDetailForm(forms.ModelForm): class Meta: model = OrderDetails fields = ( 'OrderID', 'ProductCode', 'Location', 'UnitPrice', 'Quantity', 'Discount', ) def __init__(self, *args, **kwargs): super(OrderDetailForm, self).__init__(*args, **kwargs) locations = self.initial['ProductCode'].productqtys_set.values_list('Sublocation', flat=True) locationslist = list(locations) locationsQueryset = SubLocations.objects.filter(id__in=locationslist) print("locations queryset in form") print(locationsQueryset) self.fields['Location'].queryset = locationsQueryset In my views.py I have the function that uses it: def AddOrderDetail(request, pk): Product = Products.objects.get(ProductID=pk) order = Orders.objects.last() locations = Product.productqtys_set.all() if request.method == "POST": form = OrderDetailForm(request.POST, initial={"ProductCode": Product, "OrderID": order}) if form.is_valid(): form.save() return redirect('orders:subslistCreate') else: form = OrderDetailForm(initial={"ProductCode": Product, "OrderID": order}) template_path = 'orders/orderdetail_form.html' context = { "form": form, } return render(request, template_path, context) now as you can read, I initialised the ProductCode and OrderID fields, of course when it's time to fill in data for the other fields, the user can edit the values in ProductCode and OrderId. I don't want the user to be able to do that. I tried setting disabled to True but that didn't allow me to initialise the fields anymore, and I also tried to set readonly to true by adding the following lines in the definition of the init function: self.fields['OrderID'].widget.attrs['readonly'] = True self.fields['ProductCode'].widget.attrs['readonly'] = True sadly that changed … -
Server Error (500) arised on django project
My Project is a website is 'learning_log' same as in the book Python Crash Course. Learning Log works fine in local machine but when I go out of local machine it shows Server Error (500). I used heroku to deploy it and renamed it 'trak-your-learnin' you can go to https://trak-your-learnin.herokuapp.com/ to view the error page. I've posted some important file so you can easily figure out the error; sorry i've posted too much code. This deploying process is really difficult for a beginner so hmp. settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '3kiqlq&v(^09b5ba3xp1krc#z0uu_2ji=eqe7t=cb)-n-^^%bz' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ '*', 'https://warm-taiga-24464.herokuapp.com/', '127.0.0.1', ] # Application definition INSTALLED_APPS = [ # My apps 'learning_logs', 'users', # Third party apps. 'bootstrap4', # Default django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'learning_log.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': … -
Django Two Databases: Default User Auth + Legacy Database
I want to put all of the default Django authentication backend on a separate database from my legacy database. I created a new database named 'AUTH_DB' and ran the migration. As expected, it put all of the tables (auth, admin, contenttypes, sessions, etc.) on AUTH_DB. However, now I am only able to render my login.html page. After I attempt to login, I receive a connection does not exist error. I'm having trouble understanding The connection 'auth' doesn't exist at / DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'AUTH_DB', 'USER': '', 'PASSWORD': '', 'HOST': 'lvn-gc.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server' }, }, 'data_db': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'CRM', 'USER': '', 'PASSWORD': '', 'HOST': 'lvn-gc.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server' }, }, } DATABASE_ROUTERS = ['CRM.routers.DataRouter'] In CRM/routers.py class DataRouter: db_apps = ( 'CRM' ) def db_for_read(self, model, **hints): if model._meta.app_label in self.db_apps: return 'data_db' return model._meta.app_label def db_for_write(self, model, **hints): if model._meta.app_label in self.db_apps: return 'data_db' return model._meta.app_label def allow_relation(self, obj1, obj2, **hints): return True def allow_syncdb(self, db, model): if model._meta.app_label in self.db_apps: return db == 'data_db' return False Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/ Django … -
Django Templates Formsets with Foreign Key Lookup
hoping for some guidance around my below problem with displaying reverse lookup field in a template inside formsets. Maintenance Item Model class Maintenance_Item(CommonInfo): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, unique=True) name_description = models.CharField(max_length=255) is_active = models.BooleanField(default=True) def __str__(self): return self.name Checklist Model class MaintenanceCheckList(CommonInfo): CHOICES = ( ('P','Compliant'), ('F','Non-Compliant'), ) id = models.AutoField(primary_key=True) item = models.ForeignKey(Maintenance_Item, on_delete=PROTECT, related_name='item_name') is_compliant = models.CharField(max_length=20, choices= CHOICES, default=CHOICES[0][0]) def __int__(self): return self.item The current template <form class="" method='post'> {% csrf_token %} {{ form.management_form }} <table class="table my-0" id="dataTable"> <thead> <tr> <th>Maintenance Items</th> </tr> </thead> <tbody> {% for sub_form in form %} <tr> {% for i in sub_form.item_name.all %} <td>Item: {{ i.name }}</p> {% endfor %} {{ sub_form.item|add_class:"form-select" }}<p> </p>{{ sub_form.is_compliant }}</td> </tr> {% endfor %} </table> <div class="divider"></div> <div class="col-md-12"> <p class='pt-sm-2'> <button type="submit" class="btn btn-primary">Submit</button> </form> Currently, I have generic formset view which creates an row for each item in the Maintenance_Item which works brilliant and generates the formset view as shown. The challenge, I have is I want to hide the ModelChoice fields (I can do that easily with a Widget), and just display the friendly name in the ModelChoice field as a simple Text Label in the template. Note setting disabled …