Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django allauth isn't sending verification email after signup
I'm using django allauth for my user accounts. When I create an account, it successfully tells me it will send an email to the address for verification. However I don't receive this email. This is my settings.py: EMAIL_CONFIRMATION_SIGNUP = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" LOGIN_REDIRECT_URL = '/' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my@gmail.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' -
Inherit a class but only use required fields ,not all inherited fields
Suppose there are total 3 class. A,B and C. class A(models.Model): one = models.IntegerField() two = models.IntegerField() three = models.IntegerField() class Meta: abstract = True class B(A): pass class C(A): pass I am inheriting the class A in B and C,but i want to use only fields one and two in classB while all the three fields in classC. Is it possible to inherit some fields of classA in classB and some in classC? or is it a bad idea? -
Getting error : ForeignKey([]) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' in django
i am new in django python, i am working on rest api, for that i have used 2 tables user and userprofile, in userprofile table i have id,title,dob,address,country,city,zip,photo field is there, where id is foreign key of user table, when i run my api i am getting this error AssertionError: ForeignKey([]) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self', can anyone please help me why i am getting this error, here i have placed my whole code here, models.py from django.db import models # Create your models here. from django.db import models from django.contrib.auth.models import User class Songs(models.Model): # song title title = models.CharField(max_length=255, null=False) # name of artist or group/band artist = models.CharField(max_length=255, null=False) def __str__(self): return "{} - {}".format(self.title, self.artist) class Test(models.Model): def __str__(self): return class UserProfile(models.Model): # song title profile = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255, null=False) # name of artist or group/band dob = models.CharField(max_length=255, null=False) address = models.CharField(max_length=255, null=False) country = models.CharField(max_length=255, null=False) city = models.CharField(max_length=255, null=False) zip = models.CharField(max_length=255, null=False) photo = models.CharField(max_length=255, null=False) def __str__(self): return "{} - {}".format(self.title, self.dob, self.address, self.country, self.city, self.zip, self.photo) serializers.py from rest_framework import serializers from .models import … -
UnboundLocalError Exception Value: local variable 'first_name' referenced before assignment
//views.py from django.shortcuts import render,redirect from .models import insert_user def index(request): return render(request,'backpages/index.html') def register(request): if request.method=="POST": first_name=first_name.objects.get(first_name=request.POST['first_name']) email=email.objects.get(email=request.POST['email']) password=password.objects.get(password=request.POST['password']) user=insert_user(first_name=first_name,email=email,password=password) user.save() user=insert_user.objects.get(first_name=first_name,email=email,password=password) print ("user created.") return redirect('/') else: return render(request,'backpages/register.html') Create your views here. //models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, UserManager class insert_user(AbstractBaseUser): first_name=models.CharField(max_length=200) email=models.CharField(max_length=200) password=models.CharField(max_length=200) Create your models here. -
Checking for object if it already exists in manytomany field
I am trying to give a status of "Already Exists" if a customer already exists in the manytomany field of Customers View Class: class CustomerAddition(View): def get(self, request, business_id, user_id): current_business = Business.objects.get(pk=business_id) customer = User.objects.get(pk=user_id) new_customer, created = Customers.objects.get_or_create(business_id_id = business_id) new_customer.save() list_of_customers = Customers.objects.get(business_id_id = business_id).customers.all() for value in list_of_customers: print(value) if value == User.objects.get(pk=user_id).name: return JsonResponse({"Status":"Already Exists"}) new_customer.customers.add(customer) new_customer.save() return JsonResponse({"Status":"Success"}) Model: class Customers(models.Model): customers = models.ManyToManyField('User') business_id = models.ForeignKey(Business, on_delete = models.CASCADE, related_name='owner') def __str__(self): return 1 Whenever I call the API with the same customer, it's always giving a status of "Success" Print(value) result : Sagar Aggarwal Kartik Luthra -
Django - approach to code repetition in Unit tests
Short introduction. I'm just learning to write tests for my application. The application is an online gradebook. Below is the code from the homepage view test. Only the login form is there. If the user logs in for the first time, he is redirected to the view that forces to change the default password. If this is the next login, it is redirected to the right view, depending on the user rights. Problem. In this test of the view, I had to create 6 users and related models (Student, Parent, Teacher), so I wrote the methods to create these objects (create_user / create_person). In many future view tests, I will also have to log in users and use models (Student, Parent, Teacher). How should I repeat these steps? Two ways come to mind. 1. Convert methods to static and use them in the next test classes to create objects. Will the tests still be "unitary"? 2. Copy the method definitions to each next test class in which they will be needed. Will this not break the DRY principle? Which approach is good? class HomepageViewTestCase(TestCase): password = 'testerspass' def create_user(self): username = 'tester' numbering = 0 while True: try: User.objects.get(username=username) numbering … -
Securing Typeform Webhook Python
I'm trying to accept form responses from Typeform using Python/Django/DRF and am having trouble authenticating the webhook request due to not being able to get the hashes to match. Here are the instructions from Typeform: 1. Using the HMAC SHA-256 algorithm, create a hash (using created_token as a key) of the entire received payload as binary. 2. Encode the binary hash in base64 format. 3. Add prefix sha256= to the binary hash. 4. Compare the created value with the signature you received in the Typeform-Signature header from Typeform. authentication.py class TypeformAuthentication(authentication.BaseAuthentication): def authenticate(self, request): typeform_signature = request.META.get('HTTP_TYPEFORM_SIGNATURE') data = request.body secret_key = os.environ.get('TYPEFORM_SECRET_KEY') if not typeform_signature: return None if typeform_signature: hash = hmac.new(bytes(secret_key, encoding='utf-8'), data, hashlib.sha256) actual_signature = 'sha256={}'.format(base64.b64encode(hash.digest()).decode()) user = User.objects.get(username='typeform-user') if actual_signature == typeform_signature: return(user, None) else: raise exceptions.AuthenticationFailed('Typeform signature does not match.') else: return None Example Payload { "event_id": "01DTXE27VQSA3JP8ZMP0GF9HCP", "event_type": "form_response", "form_response": { "form_id": "OOMZur", "token": "01DTXE27VQSA3JP8ZMP0GF9HCP", "landed_at": "2019-11-30T05:55:46Z", "submitted_at": "2019-11-30T05:55:46Z", "definition": { "id": "OOMZur", "title": "Auto Liability (New Company)", "fields": [ { "id": "GnpcIrevGZQP", "title": "What is your business name?", "type": "short_text", "ref": "3e60e064-f14c-4787-9968-0358e8f34468", "properties": {} } ] }, "answers": [ { "type": "text", "text": "Lorem ipsum dolor", "field": { "id": "GnpcIrevGZQP", "type": "short_text", "ref": … -
Image not showing up in django admin view
admin.py @admin.register(TblJewelleryInventory) class JewelleryInventoryAdmin(admin.ModelAdmin): list_display = ('item_code','item_name', 'base_locker_location', 'created_at') ordering = ('item_name',) search_fields = ('item_name',) inlines = [ JewelleryRegisterRecordInline, ] readonly_fields = ["jewellery_image"] def jewellery_image(self, obj): return mark_safe('<img src="{url}" width="{width}" height={height} />'.format( url = obj.item_image.url, width=obj.item_image.width, height=obj.item_image.height, ) ) models.py class TblJewelleryInventory(models.Model): id = models.AutoField(primary_key=True) item_code = models.CharField(unique=True, max_length=5, blank=True, null=True) item_name = models.CharField(max_length=250, blank=True, null=True) item_image = models.FileField(upload_to='images/', blank=True,null=True, verbose_name="") base_locker_location = models.CharField(max_length=45, blank=True, null=True) current_checkin_status = models.IntegerField(blank=True, null=True) estimated_value = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return self.item_name class Meta: verbose_name = 'Jewellery Inventory' verbose_name_plural = 'Jewellery Inventory' managed = False db_table = 'tbl_jewellery_inventory' Does not show the image, I referred the Django admin Cookbook here link -
How to use html input value in multiple class? or How to store html input value and use it in multiple class?
HTML <div class="content-section"> <form method="GET" action="{% url 'doctor:search' %}"> <input name ="q" value="{{request.GET.q}}" placeholder="search.."> <button class="btn btn-success" type="submit"> Search </button> </form> </div> I like to use input value "{{request.GET.q}}" to be used in multiple class views. views class SearchResultsView(ListView): model = Search template_name = 'all_users/doctor/search.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = User.objects.filter(Q(username__icontains=query)) return object_list class PostCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/doctor/post_form.html' model = Post fields = ['title', 'content', 'comment'] def form_valid(self, form): query = self.request.GET.get('q') form.instance.author = self.request.user form.instance.patient = User.objects.get(username=query) return super().form_valid(form) [query = self.request.GET.get('q')] in 'SearchResultsView' and in 'PostCreateView' needs same value. How can is use input value from html and use it in both these classes -
'Registered_Courses' object has no attribute 'course_set' Django
I am really stuck on this error and it does not make sense why it does not follow the relationship backward on Registered_Courses on the foreign key for Courses when i use course_set views.py def registered_coursesView(request, username): '''Page to display the registered courses of a user.''' registeredCourses = Registered_Courses.objects.get(owner = request.user) courseInfo = registeredCourses.course_set.all() context = {'registeredCourses': registeredCourses, 'courseInfo':courseInfo} return render(request, 'safetyCourseApp/registered_courses.html', context) models.py class Course(models.Model): '''Offered Course information.''' subject = models.ForeignKey(Subject, on_delete=models.CASCADE) name = models.CharField(max_length=200, primary_key=True) description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) start_date = models.DateField() end_date = models.DateField() price = models.DecimalField(max_digits=10, decimal_places=2) capacity = models.IntegerField() registered_ppl = models.IntegerField() def __str__(self): """Return a string representation of the model.""" return self.name class Registered_Courses(models.Model): """Something specific learned about a Course.""" registered_course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): """Return a string representation of the model.""" return f'{self.owner}' Please let me know what you guys think. I cannot think of a reason why this is not working. Thanks! -
TypeError at /app/accounts/login/ 'AnonymousUser' object is not iterable (context_processors.py)
I have added the following in my context_processors.py if request.user.is_authenticated: recent_notifications = Notification.objects.filter(user=request.user,is_deleted=False) else: recent_notifications = [] profile = None if Profile.objects.filter(user=request.user).exists(): profile = Profile.objects.get(user=request.user) It returns TypeError at /app/accounts/login/ 'AnonymousUser' object is not iterable Environment: Request Method: GET Request URL: http://127.0.0.1:8000/app/accounts/login/?next=/ Django Version: 2.2.7 Python Version: 3.6.8 Installed Applications: ['registration', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'users', 'profiles'] Installed 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'] Traceback: File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 145. response = self.process_exception_by_middleware(e, request) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 143. response = response.render() File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/template/response.py" in render 106. self.content = self.rendered_content File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/template/response.py" in rendered_content 83. content = template.render(context, self._request) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/template/backends/django.py" in render 61. return self.template.render(context) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/template/base.py" in render 169. with context.bind_template(self): File "/usr/lib/python3.6/contextlib.py" in __enter__ 81. return next(self.gen) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/template/context.py" in bind_template 246. updates.update(processor(self.request)) File "/home/cirtic/dev/django/cyan/src/cyan/main/context_processors.py" in main_context 29. if Profile.objects.filter(user=request.user).exists(): File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/query.py" in filter 892. return self._filter_or_exclude(False, *args, **kwargs) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/query.py" in _filter_or_exclude 910. clone.query.add_q(Q(*args, **kwargs)) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in add_q 1290. clause, _ = self._add_q(q_object, self.used_aliases) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in _add_q 1318. split_subq=split_subq, simple_col=simple_col, File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in build_filter 1224. self.check_related_objects(join_info.final_field, value, join_info.opts) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in … -
How to restrict unauthorized user to have access to different pages in django
I have this model: class Student(Model): user = OneToOneField(CustomUser, on_delete=CASCADE, related_name='student', ) and this url: path('students/<int:student_pk>/', student, name='student') and this view: @login_required def student(request, student_pk): return HttpResponse('This is your personal panel') Well, by using login_required decoration I am restricting users that are not logged in to see student panel page. However, other students who are logged in can see other's panels. How can I restrict them from this? I can do this: @login_required def student(request, student_pk): student_ins = get_object_or_404(Student, pk=student_pk) if student_ins = request.user.student: return HttpResponse('This is your personal panel') else: return HttpResponse('Please do not try to see other students' panels! You are not authorized to do this') However, I prefer to do it in decorator. For example log out the logged in student with primary key pk=1 if he/she entered this in the url: www.example.com/students/2 -
i am getting no response when i am going to remove product from cart?
this is my view stuff. def remove_from_cart(request,id): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) print(cart) except: return HttpResponseRedirect(reverse('cart')) cartitem=CartItem.objects.get(id=id) cartitem.delete() cartitem.cart=None cartitem.save() this is my urlmapping url('^cart/(?P\d+)/$',views.remove_from_cart,name='remove_from_cart'), Remove i am getting this on my terminal "GET /cart/3/ HTTP/1.1" 302 0 -
Django admin site change_list customization
Homepage/templates/admin/Homepage mypath @admin.register(gradeScalesSetting) class gradeScalesSettingAdmin(admin.ModelAdmin): list_display = ('configuration_select', 'NumberOfGrades', 'Rounding','Precision', 'Status',) change_list_template = 'admin/Homepage/view.html' after i click Grade Scale Settings how to connect it to my views.py? thi is what i want to code in my views.py def gradescales(request): gradeScalesSettings = gradeScalesSetting.objects.all() configurations = configuration.objects.all() rounding = gradeScalesSetting.objects.all().values_list('Rounding', flat=True).distinct() print(rounding) return render(request, 'Homepage/gradescale.html', {"rounding": rounding,"gradeScalesSetting":gradeScalesSettings,"configurations":configurations}) UPDATE when i tried this @admin.register(gradeScalesSetting) class gradeScalesSettingAdmin(admin.ModelAdmin): def new_NumberOfGrades(self, obj): if obj.NumberOfGrades == 'Grade Scale Settings': return '<a href="view.html" </a>' # this url will redirect to your views function list_display = ('configuration_select', 'new_NumberOfGrades', 'Rounding','Precision', 'Status',) is there any way to connect it to my views.py? this is what i want to show in my view.html that is why i want to connect it to my views.py -
One div inside another, both clickable. When pressing the inner one, the outer is also triggered
what I would like to achieve is something like that: I have some div (a blog post to be precise, like reddit) and I want this this div to be whole clickable. It has a lot of data, like author, timeposted, content, img etc. But on the bottom is a save button which allows users to save it for later. But when I click the save button it also tiggers the post's onlick what causes that user is redirected to the detail page of the post. I do not want that. I only want to trigger save button. Image of the situation: What I do have is that: <div onclick="location.href='/post/{{ post.id }}/';" style="cursor: pointer; "> <article class="media post"> <div class="media-body"> <!-- Whole body, user, date, content, img etc. --> <div> <a id="save-post-{{post.id}}" href="javascript:void(0);" onclick="save_post('{{post.pk}}', '{{user.pk}}', this.id, '{{ csrf_token }}');"> Save </a> </div> </div> </article> </div> How do I do that, the save button is only triggered? -
CSS Grid/Flexbox for dynamic content in Django
I am using Django for a project, and I have a wireframe CSS grid layout, 4 across at the moment, and I want to know how I can replace these wireframe components with dynamic content using Django. I know that {% for post in posts %} would work for me in a straight down list way, but how can I make this work in a grid system, so it'll break to a new line whenever it reaches 4 across in the grid. I am stumped and haven't found anything online on how to do it. -
play song in django...please help me for solving that issue..i will pay small money for it..bt i need the answe quickly
help in audio play in django iam making a website using django..in my default.html page everything working good..iam collecting all details from database and fetch to default page..bt when clicking on each image i want to play the song that associated with..bt i dont know the code for that..please help me modesl page class Songs(models.Model): Title = models.CharField(max_length=100) Film = models.CharField(max_length=100) Composer = models.CharField(max_length=100) Artist = models.CharField(max_length=100) Duration = models.CharField(max_length=100) Language = models.CharField(max_length=100) Latest = models.BooleanField(default=False) Img = models.ImageField(upload_to='pics') Audio = models.FileField(upload_to='musics/')``` def default(request): son = Songs.objects.all() return render(request, 'default.html', {'son' : son}) //////default page//////// <div class="row"> {% for i in son %} {% if i.Latest %} <div class="col-lg-3 col-md-4 col-sm-6 col-xs-12"> <a style="text-decoration: none;" href="" class="fon acol profile-img-container"><img class=" imgsize" src="{{ i.Img.url }}"><i class="fa fa-play fa-5x profile-img-i-container iconcolor"></i><h6><br>Song : {{ i.Title }}</h6><h6>Movie : {{ i.Film }}</h6></a> <audio controls autoplay loop preload="metadata" style="width: 100%;background-color: #aa09f2"> <source src="{{ i.Audio.url }}" type="audio/mpeg"> Your browser does not support the audio element. </audio> {% endif %} </div> {% endfor %} </div></div> i want to play not like this..it is playing for every images..i need to play the media player when clickin on an image..can anyone help me -
Keep data in divs when comming back from other page
Firstly, I didn't know how to give a short description of the problem in the title, let me explain it here. I'm creating social site, with all common features like/comments etc. Imagine Twitter/Instagram. I do have main/home page where all posts are displayed. Every post has a like button, so when it is clicked it triggers a AJAX function to send request to Django server to update the database with new like. This JS function also changes the style of the button, so user can know that he liked it. So far so good. Now when he decides that he want to comment this post, he clicks it and is redirected to the new page - the detail page. Here when the page is loading with data from server his like he gave earlier is visible(the div is red). All right, he commented, but know when pressing back button, in order to go to the home page, his like under the post is not more visible without reloading the page. I will demonstrate it using images. Now I'm using JS function to reload whole page, to get from Django server all new data, but I don't think it is good … -
"TypeError: Input 'global_step' of 'ResourceApplyAdagradDA' Op has type int32 that does not match expected type of int64." What is this bug?
While I was trying to use the AdaGradDual Optimizer, I got an error for the batch size I had entered. The batch size I entered was 300 because I have 60000 samples to train. My code: import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt import numpy as np import time start_time = time.time() data = tf.keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = data.load_data() class_names = ['T-shirt', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot'] train_images = train_images/255.0 test_images = test_images/255.0 optimizer1 = tf.compat.v1.train.AdagradDAOptimizer(0.001,0) model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(100, activation="softsign"), keras.layers.Dense(10, activation="softmax") ]) model.compile(optimizer=optimizer1, loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_images, train_labels, epochs=5) test_loss, test_acc1 = model.evaluate(test_images, test_labels) print("Test acc is:", test_acc1) print("--- %s seconds ---" % (time.time() - start_time)) Error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/op_def_library.py in _apply_op_helper(self, op_type_name, name, **keywords) 527 as_ref=input_arg.is_ref, --> 528 preferred_dtype=default_dtype) 529 except TypeError as err: 13 frames /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, ctx, accepted_result_types) 1272 "Tensor conversion requested dtype %s for Tensor with dtype %s: %r" % -> 1273 (dtype.name, value.dtype.name, value)) 1274 return value ValueError: Tensor conversion requested dtype int64 for Tensor with dtype int32: <tf.Tensor 'training_16/AdagradDA/update_dense_22/kernel/Identity:0' shape=() dtype=int32> During handling of the above exception, another exception … -
how to convert RawQuerySet to int
i know this is a strange question but i need to reduce one from the RawQuerySet. i need to reduce a the value output by the .raw command but i do not know how to do this. i have tried to convenvert the RawQuerySet to the queryset dictionary tuple but i don`t know what to do from their. i am getting the data in the following query data = bio_eq.objects.raw('SELECT bio_eq_amount from bio_lab_bio_eq where bio_eq_id=bio_eq_id') i am not sure how to take this and extract the data and turn it into a integer -
django select_related() calls database each time object is referenced, instead of just once
using select_related, each time I reference the query set, another call to the database is made. instead of caching the result. models.py .... class Album(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) title = models.CharField(max_length=255) description = models.CharField(max_length=255, null=True) class Photo(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) name = models.TextField(unique=True) ... views.py .... photos = Photo.objects.select_related('album').filter(album_id = id).all() print(photos) print(photos) print(photos) .... will result in 4 different calls to the database for each reference to "photos", as verified by manage.py runserver_plus --print-sql is this normal? or am I not using select_related() properly? -
Are there flaws in my current understanding of classes and functions?
I have just started learning about Django and have finished classes and objects in Python. One common snippet that I see all the time is: from django.db import models class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) Is it ok to say that there is some file called django.db in the system and there is a class called models inside it and Model is an attribute of the class? Also, django.db is not a Python (.py) file, so how can it contain a class? Now, Is CharField is function inside the class models or is it something else? -
Django admin site change_list customization
Homepage/templates/admin/Homepage mypath @admin.register(gradeScalesSetting) class gradeScalesSettingAdmin(admin.ModelAdmin): list_display = ('configuration_select', 'NumberOfGrades', 'Rounding','Precision', 'Status',) change_list_template = 'admin/Homepage/view.html' after i click Grade Scale Settings how to connect it to my views.py? thi is what i want to code in my views.py def gradescales(request): gradeScalesSettings = gradeScalesSetting.objects.all() configurations = configuration.objects.all() rounding = gradeScalesSetting.objects.all().values_list('Rounding', flat=True).distinct() print(rounding) return render(request, 'Homepage/gradescale.html', {"rounding": rounding,"gradeScalesSetting":gradeScalesSettings,"configurations":configurations}) -
Conditional Relationships between Two Tables in Django?
The following image shows a rough draft of my proposed database structure that I will develop for Django. Briefly, I have a list of ocean Buoys which have children tables of their forecast conditions and observed conditions. I'd like Users to be able to make a log of their surf sessions (surfLogs table) in which they input their location, time of surf session, and their own rating. I'd like the program to then look in the buoysConditions table for the buoy nearest the user's logged location and time and append to the surfLog table the relevant buoyConditions. This will allow the user to keep track of what conditions work best for them (and also eventually create notifications for the user automatically). I don't know what the name for this process of joining the tables is, so I'm having some trouble finding documentation on it. I think in SQL it's termed a join or update. How is this accomplished with Django? Thanks! -
Trouble getting my HTML button linked to a Python function using Django
I am attempting to take data from an HTML page form hosted on Django's localhost development server and send it to a database in Models. I'm attempting to follow this solution, but I'm not sure how to link the function to the reference to the HTML in views.py. Here's my views.py currently: # djangotemplates/example/views.py from django.shortcuts import render from django.views.generic import TemplateView # Import TemplateView from django.http import HttpResponse from pathfinder.models import characterTable def addCharacter(sUserID, sPlayerName, sRace, sPlayerClass, sStr, sCon, sDex, sInt, sWis, sCha): c = characterTable() c.userID=sUserID c.playerName = sPlayerName #... rest of fields go here c.save() def request_page(request): if(request.GET.get('mybtn')): userID = 'testUser' addCharacter(userID, string(request.GET.get('characterName')), string(request.GET.get('race')), string(request.GET.get('class')), string(request.GET.get('characterName')), string(request.GET.get('strength')), string(request.GET.get('dexterity')), string(request.GET.get('constitution')), string(request.GET.get('intelligence')), string(request.GET.get('wisdom')), string(request.GET.get('charisma'))) # Add the two views we have been talking about all this time :) class HomePageView(TemplateView): template_name = "index.html" class AboutPageView(TemplateView): template_name = "about.html" And here is the HTML, in my templates folder: <!-- djangotemplates/example/templates/index.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Welcome Home</title> </head> <body> <a href="{% url 'home' %}">Go Home</a> <a href="{% url 'about' %}">About This Site</a> <form name = "characterForm" id = "characterForm" method = "get" action = "#"> Character Name:<br> <input type="text" name="characterName" id ="characterName"> <br> Race:<br> <select name = "race" …