Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using arrays in django views.py code - is it a good habit?
I have couple of functions which captures ajax requests. I get the data from the request and put into the array. Then I loopthru this array in another function for instance to pass the data to context. This solution basically works, but is it a good way of doing things ? Appreciate for any feedback. piece of code: user_choices = [] @login_required @csrf_exempt def make_order(request): if request.method == "POST" and request.is_ajax(): data = json.loads(request.body) for order in data["array"]: user_choices.append(order) return HttpResponse(200) else: return redirect(request, 'home') movie = 0 seats = [] @login_required def confirmation(request): if len(user_choices) > 0: movie = Movies.objects.get(pk=int(user_choices[0]["id"])) for seat in user_choices: seats.append(seat["row"]+":"+seat["seat"]) context = { "movie":movie.title, "seats":seats } return render(request, "main_templates/confirmation.html", context) else: return redirect("home") -
Django - Legacy database tables - Querying 2 one to many tables
I am new to Django and would like some advice on how to query from 3 tables. I have 3 tables from legacy database mapped in to models (Patient, PrescribedMeds, PrescribedMedsSchedule). We can't change this structure since this will have to remain active while we create the Django application. 1 patient can have many prescribed medication. 1 prescribed medication can have several times in the schedule Below is the model in django. models.py class Patient(models.Model): patient_name = models.CharField(db_column='patient_name', max_length=50) dob = models.DateTimeField(db_column='DOB', blank=True, null=True) # Field name made lowercase. gender = models.CharField(db_column='Gender', max_length=7) # Field name made lowercase. dateofentry = models.DateTimeField(db_column='DateOfEntry', blank=True, null=True) # Field name made lowercase. .... .... class Meta: managed = False db_table = 'patient' def __str__(self): return self.patient_name class PrescribedMeds(models.Model): #id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. patient_id= models.ForeignKey(Patient, models.DO_NOTHING, db_column='patient_id') med_type = models.SmallIntegerField(db_column='Type') # Field name made lowercase. name_of_medication = models.CharField(db_column='Name_Of_Medication', max_length=50, blank=True, null=True) # Field name made lowercase. rxno = models.CharField(db_column='RxNo', max_length=50, blank=True, null=True) # Field name made lowercase. date_filled = models.DateTimeField(db_column='DateFilled', blank=True, null=True) # Field name made lowercase. .... .... class Meta: managed = False db_table = 'prescribed_meds' def __str__(self): return str(self.id) + ", " + self.name_of_medication + ", " + … -
Next JS getInitialProps Axios.Get Dynamic API Endpoint
I have a next.js app that makes API calls to a django server. The issue I'm having now is calling dynamic content with getInitialProps. Please see the url examples below. Basically, how would I pull a primary key dynamically in getinitialprops. Example: .herokuapp.com/api/v2/pages/1/?type=projects.ProjectsPage&fields=* vs .herokuapp.com/api/v2/pages/2/?type=projects.ProjectsPage&fields=* static async getInitialProps(ctx) { const resProjects = await axios.get(`...herokuapp.com/api/v2/pages/PK/?type=projects.ProjectsPage&fields=*`); return { data: data } } -
Dropzone.js doesn't saving files with Django
I tried using form for saving and looping through request.FILES and then AdsBanners.objects.create() but any of these methods work for me. Here are the 2 views I implemented to do the same thing: View 1 @login_required def index(request): images = AdsBanners.objects.filter(user=request.user) if request.method == 'POST': form = PictureForm(request.POST, request.FILES) print(form) if form.is_valid(): picture = form.save() else: form = PictureForm() return render(request, 'index.html', {'images': images, 'form': form}) View 2 @login_required def index(request): # Handle file upload current_client = request.user if request.method == 'POST': form = PictureForm(request.POST, request.FILES) if form.is_valid(): form.save() uploaded_files = [request.FILES.get('file[%d]' % i) for i in range(0, len(request.FILES))] for f in uploaded_files: client_upload = AdsBanners.objects.create(user=current_client, image=f) # Redirect to the document list after POST return HttpResponseRedirect(reverse('ads_module.views.index')) else: form = PictureForm() # A empty, unbound form # Load documents for the list page images = AdsBanners.objects.filter(user=current_client) # Render list page with the documents and the form return render(request, 'index.html', {'images': images, 'form': form}) Here are the model and the js code too: Model class AdsBanners(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.FileField(upload_to=user_directory_path) def save(self, *args, **kwargs): if AdsBanners.objects.filter(image=self.image).count() >= 5: return False else: super(AdsBanners, self).save(*args, **kwargs) def __str__(self): return self.user.username Template <script type="text/javascript"> Dropzone.options.myDropzone = { paramName: "image", // … -
Django advanced crispy form is not saving
Im using django crispy forms and I'd like to make the design it a little fancier. first my "old" code, that works models.py class Register(models.Model): CREATED = "C" PRINTED = "P" STATUS = ( (CREATED, _("Created")), (PRINTED, _("Printed")), ) user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name="author", on_delete=models.SET_NULL, default=1) timestamp = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(default=datetime.now) status = models.CharField(max_length=1, choices=STATUS, default=CREATED) comment = models.CharField(max_length=255, null=True, unique=False, blank=True) edited = models.BooleanField(default=False) objects = ArticleQuerySet.as_manager() name = models.CharField(max_length=255, null=True, unique=False) street = models.ForeignKey(Street, verbose_name=_('street'), on_delete=models.CASCADE, null=True, blank=True) number = models.IntegerField(blank=True, null=True) phone = models.IntegerField(blank=True, null=True) forms.py class RegisterForm(forms.ModelForm): status = forms.CharField(widget=forms.HiddenInput()) edited = forms.BooleanField( widget=forms.HiddenInput(), required=False, initial=False) class Meta: model = Register autocomplete_fields = ('street',) fields = ["name", "street", "number", "comment", "phone", "status", "edited",] widgets = {'street': autocomplete.ModelSelect2(url='street-autocomplete',attrs={'data-html': True})} views.py class CreateRegisterView(CreateView): model = Register message = _("saved") form_class = RegisterForm template_name = 'register/register_create.html' def form_valid(self, form): if self.request.user.is_authenticated: form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): messages.success(self.request, self.message) return reverse('register:write_new') html template {% extends 'base.html' %} {% load static i18n %} {% load crispy_forms_tags %} {% load widget_tweaks %} {% block head %} {% endblock head %} {% block content %} <form action="{% url 'register:write_new' %}" enctype="multipart/form-data" id="register-form" method="post" role="form"> {% csrf_token %} {% crispy … -
Django deployment website is showing the source code instead of the page content
I finish developing my web site in Django and now I want to deploy it using cpanel. I uploaded the files via FileZila but when I run the home page, I am getting the Django source code of the base.html file such {% extends 'base.html'%} Please assist me -
Nested Multiple choice field serialize in Django and VueJS app
I have multiple choice nested serializer, I am able to get the value but fails subjects with patch call Here User and Subject are two models, **Model.py** class Subject(models.Model): uid = models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True) ENG = "ENGLISH" HND = "HINDI" SUBJECT = ( (ENG, "English"), (HND, "Hindi"), ) subject = models.CharField( max_length=50, choices=SUBJECT, default=ENG) def __str__(self): return self.subject class User(AbstractUser): uid = models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True) TEACHER = "Teacher" STUDENT = "Student" user_type = models.CharField(max_length=30, default=STUDENT) approved = models.BooleanField(default=True) def save(self, *args, **kwargs): if self.user_type == User.TEACHER and self._state.adding: self.approved = False super().save(*args, **kwargs) @property def syllabus(self): ret = self.teacher.syllabus_set.all() if ret: return ret else: return '' Here is my serializer call **serializers.py** class TeacherProfileDetails(serializers.ModelSerializer): logger = logging.getLogger(__name__) teacher_date = AvailabilityDetails(many=True, read_only=True) first_name = serializers.CharField(source='user.first_name', read_only=True) last_name = serializers.CharField(source='user.last_name', read_only=True) cities = CitySerializer(many=True, read_only=True) subject = serializers.SerializerMethodField() user = UserDetailsSerializer(read_only=True) class Meta: model = Teacher fields = ('user', 'first_name', 'last_name', 'bio', 'teacher_cost', 'subject', 'teacher_date', 'cities') def get_subject(self, obj): subject_list = [] for i in obj.subject.all(): subject_list.append(i.subject) return subject_list Here is my views.py call **views.py** class TeacherListCreateAPIView(APIView): logger = logging.getLogger(__name__) #def create(self, request, *args, **kwargs): def get(self, request, *args, **kwargs): self.logger.info("Geeting TeacherListCreateAPIView information") teacherList = Teacher.objects.filter(user__username=kwargs["username"]) self.logger.info(teacherList) serializers = TeacherProfileDetails(teacherList, … -
Error when I try to rename fieldname in my models.py
Annoying problem. I want to rename a field in my model from reconciled_type to import_type. As soon as I change the fieldname I get the error below and can't proceed to MakeMigrations. raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'reconciled_type' into field. Choices are: account, amount, category, category_id, created, currency, data, description, id, import_journal_entry, import_journal_entry_id, import_type, is_load, merchant, merchant_id, monzo_id, settled, transaction_datetime, updated The field in Models.py: IMPORT_TYPE_CHOICES = ( ('r', 'Reconciled'), ('i', 'Ignore'), ) reconciled_type = models.CharField( max_length=1, choices=IMPORT_TYPE_CHOICES, blank=True, null=True, ) The full traceback is: Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Philip\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Philip\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\urls\resolvers.py", line 406, in check for pattern in self.url_patterns: File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\urls\resolvers.py", line … -
Django psycopg2 cursor does not exist
Using the Postgres specific ArrayField, i am trying to sum the lengths of ArrayFields. The queries work fine in shell but not on local dev server. I have narrowed the error down to the last annotate on line 19: "annotate(total=Sum("length"))", seeing as it runs fine without this last .annotate(...).values(...) part. I have also run "makemigrations" and "migrate" so the database is updated. Error: cursor "_django_curs_19180_1" does not exist Debug output: ('SELECT "product_design_assembledfromcomponent"."id", ' '"product_design_assembledfromcomponent"."assembled_id_id", ' '"product_design_assembledfromcomponent"."quantity", ' '"product_design_assembledfromcomponent"."designed_with_id_id", ' '"product_design_assembledfromcomponent"."position", ' '"product_design_assembledfromcomponent"."description", ' '"product_design_assembledfromcomponent"."assembled_inhouse", (SELECT ' 'SUM(ARRAY_LENGTH(U0."position")) AS "total" FROM "product_design_multistep" ' 'U0 WHERE U0."assembly_id" = ("product_design_assembledfromcomponent"."id") ' 'GROUP BY U0."assembly_id" LIMIT 1) AS "taken" FROM ' '"product_design_assembledfromcomponent" WHERE ' '"product_design_assembledfromcomponent"."assembled_id_id" = %s') The above exception (function array_length(character varying[]) does not exist LINE 1: ...edfromcomponent"."assembled_inhouse", (SELECT SUM(ARRAY_LENG... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. ) was the direct cause of the following exception: Code: 1 from django.db.models import Q, Sum, Count, Subquery, OuterRef 2 from django_postgres_extensions.models.functions import ArrayLength 3 4 class ProductionStepForm(forms.ModelForm): 5 helper = FormHelper() 6 helper.layout = Layout( 7 Div("assemblies", "description", 8 css_class="col-md-7", 9 ), 10 ) 11 12 helper.add_input(Submit('submit', 'Submit', css_class='btn-primary')) 13 14 15 def … -
Django S3 Bucket File Upload
Trying to upload a file to S3 Bucket, but I am receiving the following error: InvalidRequestThe authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.18B2904E53096953+pm4kJtsnkRDaopEeQ0JxAVcyhh9stYsTR4tnTkKMOm/HQv3N0ZAdrbZ42H1ggbB8CIOBRISwEs= I believe my problem is that the code is using the old v2 S3 signature process and I need to update the signature code to the v4 S3 format. s3_config.py AWS_UPLOAD_BUCKET = 'upload-bucket-s4-frankfurt' AWS_UPLOAD_USERNAME = 'upload-user' AWS_UPLOAD_GROUP = 'CFE_group' AWS_UPLOAD_REGION = 'eu-central-1' AWS_UPLOAD_ACCESS_KEY_ID = 'removed' AWS_UPLOAD_SECRET_KEY = 'removed' AWS_S3_SIGNATURE_VERSION = 's3v4 ' Views.py import base64 import hashlib import hmac import os import time import datetime from django.utils import timezone from rest_framework import permissions, status, authentication from rest_framework.response import Response from rest_framework.views import APIView from .config_s3_aws import ( AWS_UPLOAD_BUCKET, AWS_UPLOAD_REGION, AWS_UPLOAD_ACCESS_KEY_ID, AWS_UPLOAD_SECRET_KEY, ) from .models import FileItem import boto3 from botocore.client import Config # Get the service client with sigv4 configured s3 = boto3.client('s3', config=Config(signature_version='s3v4')) class FilePolicyAPI(APIView): permission_classes = [permissions.IsAuthenticated] authentication_classes = [authentication.SessionAuthentication] def post(self, request, *args, **kwargs): filename_req = request.data.get('filename') if not filename_req: return Response({"message": "A filename is required"}, status=status.HTTP_400_BAD_REQUEST) policy_expires = int(time.time()+1000) user = request.user username_str = str(request.user.username) file_obj = FileItem.objects.create(user=user, name=filename_req) file_obj_id = file_obj.id upload_start_path = "{username}/{file_obj_id}/".format( username = username_str, file_obj_id=file_obj_id ) _, file_extension = os.path.splitext(filename_req) filename_final = "{file_obj_id}{file_extension}".format( file_obj_id= file_obj_id, … -
How to store Google Auth Credentials object in Django?
I'm trying integrate Google Tag Manager into my project. In official document, Google suggests oauth2client library. Unfortunately, this library deprecated. I used google_auth_oauthlib. I can get token and send request to Google Tag Manager API with this token. But I don't decide how can I store credentials object in Django. In oauth2client lib, there is CredentialsField for model. We can store Credentials object in this field with using DjangoORMStorage. But I can't use this deprecated library. Are there any alternative ways? Google Tag Manager document is here My codes here: from google_auth_oauthlib.flow import Flow from googleapiclient.discovery import build FLOW = Flow.from_client_secrets_file( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scopes=[settings.GOOGLE_OAUTH2_SCOPE]) class GTMAuthenticateView(APIView): def get(self,request,**kwargs): FLOW.redirect_uri = settings.GOOGLE_OAUTH2_REDIRECT_URI authorization_url, state = FLOW.authorization_url(access_type='offline', include_granted_scopes='true') return Response({'authorization_url':authorization_url,'state':state}) def post(self, request, **kwargs): FLOW.fetch_token(code=request.data['code']) credentials = FLOW.credentials return Response({'token':credentials.token}) class GTMContainerView(APIView): def get(self,request,**kwargs): service = get_service() containers = self.get_containers(service) return Response({'containers':str(containers),'credentials':str(FLOW.credentials)}) @staticmethod def get_containers(service): account_list = service.accounts().list().execute() container_list = [] for account in account_list['account']: containers = service.accounts().containers().list(parent=account["path"]).execute() for container in containers["container"]: container["usageContext"] = container["usageContext"][0].replace("['", "").replace("']", "") container_list.append(container) return container_list def get_service(): try: credentials = FLOW.credentials service = build('tagmanager', 'v2', credentials=credentials) return service except Exception as ex: print(ex) -
TemplateSyntaxError in django when passing variable to ajax
I receive template error "Could not parse the remainder: '{{movie_id}}' from '{{movie_id}}'" when passing the varriable to ajax. This variable works in template, but ajax cannot get it thru. Variable contains id which is required to pass to my views function. ajax call: $.ajax({ url: "{% url 'make-order' {{movie_id}} %}", type: 'POST', data: new_array, processData: false, contentType: "application/json", dataType: "json", headers: {"X-CSRFToken":'{{ csrf_token }}'}, success: function (result) { console.log(result.d) window.location.href = "{% url 'confirmation' %}" }, error: function (result) { console.log(result); } }); urls: path("make-order/<int:pk>", views.make_order, name="make-order"), views: def make_order(request, movie_id): if request.method == "POST" and request.is_ajax(): data = json.loads(request.body) print(movie_id) return HttpResponse(200) else: return redirect(request, 'home') -
Why is my ModelForm not showing the right settings?
I have two Model Forms, one for notification types and one for privacy settings. Both show the defaults and not what is saved in the database. How can I make the form show the choice that's stored in the database instead of the defaults? Example: Say the user chose a Direct Message privacy of "Friends and Followers". When they visit the privacy options page again after having saved the changes, it shows "Open" instead of reflecting what is in the database. I tried assigning the values saved in the database directly to the form when rendering the page when the request is GET but that didn't do anything, even though the debug print shows that the value of form.dm_privacy is indeed what's in the database, it still shows "Open". Both forms work fine, the changes get saved and everything. I don't understand why it's not reflecting the changes though, is this just something that Model Forms do and not something I can change? privacy_options.html {% extends "accbase.html" %} {% block content %} <h1>Privacy Options</h1> <form method="post"> {% csrf_token %} {{form.as_p}} <button type="submit">Save</button> </form> {% endblock %} views.py @login_required def privacy_options(request): """ Holds all privacy options such as.. open/closed DMs, who … -
OperationalError table X has no column named Y
I have a problem with my from. When I try to save(add review) it in view then I see this error: table bookstore_review has no column named author_id. I already tried to do makemigrations and migrate but my code cause the above problems. models.py class Review(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='reviews') text = models.TextField() grade = models.IntegerField(default=1) created_date = models.DateTimeField(default = timezone.now) def __str__(self): return self.text forms.py class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ['text', 'grade'] views.py book = get_object_or_404(Book, pk = first_book['pk']) if request.method == "POST": form = ReviewForm(request.POST) if form.is_valid(): review = form.save(commit=False) review.author = request.user review.book = book review.save() return redirect('network') else: form = ReviewForm() return render(request, 'bookstore/computer/network.html', { 'form' : form, }) templates <form method="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Send</button> </form> -
Django- aggregating conditional child fields
Let say I have the following models. A given Job can run for multiple days, has multiple users on it, and those users can have various flags set (the booleans in the model): class Job(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=128) class JobEmployee(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date = models.DateField() job = models.ForeignKey(Job, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) is_sup = models.BooleanField() is_mgr = models.BooleanField() timecard_complete = models.BooelanField() What I would like to do is pull a list of Job IDs, dates, and the count of all children, children with is_mgr==True, is_sup==True, and timecard_complete==False on each job's date. So the result would look something like: Job ID | Date | all_users | mgr | sup | missing_tc -------------------------------------------------------------------------------------- 978294d8-3ae8-11ea-b77f-2e728ce88125 | 2020-01-05 | 8 | 2 | 0 | 4 978294d8-3ae8-11ea-b77f-2e728ce88125 | 2020-01-06 | 6 | 0 | 1 | 3 f5e87902-3ae8-11ea-b77f-2e728ce88125 | 2020-01-05 | 10 | 1 | 3 | 7 f5e87902-3ae8-11ea-b77f-2e728ce88125 | 2020-01-06 | 5 | 0 | 1 | 0 How can this be done with a django query? -
I am unable to create a virtualenv in command window to run django projects
Could anyone please help me with how to fix the virtuaenv issue on windows 10 - 64-bit pc. I repeatedly keep getting this error while I try to create a virtual env using windows Powershell/Command windows to install Django projects Error message "mkvirtualenv : The term 'mkvirtualenv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." Appreciate your advice -
Sending Images as inline Attachment within HTML template using Django
I am trying to send an HTML email that would render an inline image. My code in views.py is as follows: import ... def signup_mail_function(form): # here, form is just my context subject = "Signup Successful" html_message = render_to_string('emailTemplate.html', {'form': form}) plain_message = strip_tags(html_message) from_email = 'uconnect786@gmail.com' to_email = [form.email] # Sending email here msg = EmailMultiAlternatives(subject=subject, body=plain_message, from_email=from_email,to=to_email) msg.attach_alternative(html_message, "text/html") msg.content_subtype = 'html' msg.mixed_subtype = 'related' img_path = settings.STATIC_DIR + '/images/blogsImage.svg' # path of my image image_name = Path(img_path).name # Testing image name,which returns out to be same as image name i.e blogsImage.svg print(img_path, image_name) # testing image paths here with open(img_path, 'rb') as f: image = MIMEImage(f.read(), _subtype="svg+xml") msg.attach(image) image.add_header('Content-ID', "<{}>".format(image_name)) # Setting content ID print("<{}>".format(image_name)) # Testing content ID msg.send() So the above is my handling code of email message. In the template, I am doing the following: <img alt="Blog Image" src="cid:blogsImage.svg" /> Email is sent successfully with the image as the attachment but actually I was expecting to get the image as an inline image within the Html page. The email I received, You see no images are displayed within Html template so 'alt' tags of those images pop up I could snapshot the whole Html … -
The QuerySet value for an exact lookup must be limited to one result using slicing Error in Django
I'm trying to input from user the vendor choices(2 choices) and timeframe(3 choices) from which they want the query from. I am facing the above mentioned error in the same. Attached below are the relevant files. The HTML: <form method="POST" action="/profiles/adminKaLogin/"> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="defaultInline1" name="inlineDefaultRadiosExample" value="1"> <label class="custom-control-label" for="defaultInline1">Vendor 1</label> </div> <!-- Default inline 2--> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="defaultInline2" name="inlineDefaultRadiosExample" value="2"> <label class="custom-control-label" for="defaultInline2">Vendor 2</label> </div> <br> <h3> Select time period</h3> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="defaultInlines1" name="inlineDefaultRadiosExample1" value="1"> <label class="custom-control-label" for="defaultInlines1">1 Month</label> </div> <!-- Default inline 2--> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="defaultInlines2" name="inlineDefaultRadiosExample1" value="2"> <label class="custom-control-label" for="defaultInlines2">2 Months</label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="defaultInlines3" name="inlineDefaultRadiosExample1" value="6"> <label class="custom-control-label" for="defaultInlines3">6 Months</label> </div> <br> <button type="submit" class="btn btn-primary" name="form1">Submit</button> </form> The models.py class vendor(models.Model): id = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=30) class employee(models.Model): name = models.OneToOneField(User, on_delete=models.CASCADE) id = models.CharField(max_length=20, primary_key=True) balance = models.IntegerField(default=0) class transaction(models.Model): vendor_id = models.ForeignKey(vendor, on_delete=models.CASCADE) emp_id = models.ForeignKey(employee, on_delete=models.CASCADE) debit = models.IntegerField() credit = models.IntegerField() timestamp = models.DateField(("Date"), default=datetime.date.today) The views.py if 'form1' in request.POST: d={} vendor_choice = request.POST["inlineDefaultRadiosExample"] date_choice = request.POST["inlineDefaultRadiosExample1"] x = employee.objects.all() y = vendor.objects.all() if … -
Can use app specific static files fine, cannot get static files under project root to load
So I have two apps (account and job). Each app has its own respective app_name/templates/app_name and app_name/static/app_name directories. With the following static related settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') I can use app-specific templates and static files with no problem. I.e. in my job/templates/index.html I have the line <link rel="stylesheet" href="{% static 'job/index.css' %}">` and it grabbed the job/static/index.css file. However, under the main project directory(website/) I have a website/templates/base.html( in other answers on here I have seen this where you should store base.html) and a website/static/css/base.css fle . I cannot get this base.css file to load. Within base.html I have tried the following three links: <link rel="stylesheet" href="{% static 'base.css' %}"> `<link rel="stylesheet" href="{% static 'css/base.css' %}"> <link rel="stylesheet" href="{% static 'static/css/base.css' %}"> and none of them have worked. Does anyone know how to get this base.css working? Thanks in advance and yes I included {% load static %}! -
Django-Static files, how to close yourdoman/static file index
How to close Index of /Static/ from viewing them by the visitor of your website in djangoenter image description here -
how to implement multiple file upload with multiple "choose file" clicks in Django
I am working on the image upload functionality for my project website. I would like to implement the file upload button to allow multiple image uploads with multiple "choose file" button clicks I understand how to implement a file input that allows multiple files with the 'multiple' attribute, but I would like to implement the "choose file" upload button so that users can click and upload multiple times to add files to be uploaded. Currently for a file input with multiple attribute, users will update the files if they click "choose file" button the second time, I want it so that the second time won't update the files but to add to the files to be uploaded. How would I accomplish this in Django. Any help is appreciated. -
how to display questions to user and compare them using "if" "else" statements expert system django?
I have stored the rules in database in form of questions and want to ask questions by user and then conclude to a result. I want questions to be displayed on user's screen with yes or no option and ask further questions according to the choices. i am unable to find a solution that how should i compare user input from front end with backend (django) so far i have tried views.py def fetch_rules(request): if request.method=='POST': issueid=request.POST['issueid'] rules=Rules.objects.all().filter(parentissue=issueid) return render(request,"questions.html",{"rules":rules}) else: return HttpResponse("Not found") template {% extends 'base.html' %} {% block content%} <div class="questionwrapper"> {% for rul in rules %} <div class="question"> <h1>{{rul.question}}</h1> </div> <div class="solution"> <p>{{rul.solution}}</p> </div> <p style="text-align: center;font-weight: bold;">Your issue solved?</p> <div class="question_btns"> <a id="yes_q" >Yes</a> <a id="no_q" >No</a> </div> {%endfor%} </div> {% endblock %}[![My template][1]][1] currently template shows all the questions but i want to display once at a time and then display one after another according to the user's choice. -
Django Populating New Project With Directories From Old
New to Django and I created a project with Django 3.0 based on a tutorial, then created Project 2 based on a second tutorial, following the steps. But when I use the command django-admin startproject project2_project it populates project2's folder with all of the directories/files from project 1, and everything else on my Desktop. When I run the server, I get Project 1's website. Have looked in the Django docs and on here but can't find any answers to this. Also, when I enter the virtual environment pipenv shell it says I am on my desktop: (Desktop) bash-3.2$ This might have something to do with it? -
How to set an attribute in a model property
I want to add a label attribute to a model property, so I can access a verbose name for it: class MyModel(models.Model): @property def is_closed(self): setattr(self.is_closed, 'label', 'is the object closed?') if self.list_closure_datetime: return True else: return False However, obj.is_closed.label returns maximum recursion depth exceeded Where am I going wrong? -
Schema design for multi-location education class room booking system
Within the broader context of an organizational HR suite I am designing a scheduling system. The teachers table will be connected at a later time to the main schema and doesn't need to hold anything other than a name and any data required for scheduling. The primary entities I am dealing with are: Teachers Rooms Learning Centers Classes Schedules I am planning on connecting these via a junction table, called DailySchedule, which will have foreign keys to each of the above entities, as well as Time information associated with it. The time information will be stored in the form of discrete blocks(1-6) as all classes are the same length. The Daily Schedule will be used to build the weekly schedule and so on. The areas I am unsure about are: - where to store the LearningCenter location data and stay normalized (in the teacher, the room, ? ) (The center key will likely become a foreign key at a later date) - Expanding to at least 50 centers and ensuring that each center does not get flooded with unneeded data regarding users. I am planning on implementing the first version in the django admin and then building out a prettier …