Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
set_password() method is saving plain text
When I'm saving the user from the view and writing the codes it is saving the password as plain text but when I'm using the same set_password() method in the shell, it's saving the hashed password perfectly. Kindly point out where I'm making the mistake. Actually I'm saving the data directly from an excel sheet. username="username" password="password" firstName="first" lastName="lastname" user=User.objects.create( firstName = firstName, lastName = lastName, username = username, ) user.set_password(password)) user.is_student = True user.save() user.school = request.user.school user_inst.save() user_ins = User.objects.get(username=username) -
AttributeError: module 'django.contrib.auth.admin' has no attribute 'site'
I encountered the error AttributeError: module 'django.contrib.auth.admin' has no attribute 'site' .I cant figure out where i went wrong.Can anyone help? here is the code in urls.py. from django.contrib.auth import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('adoption.urls')), path('accounts/', include('accounts.urls')), path('admin/', admin.site.urls) ] urlpatterns= urlpatterns+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to use specifice blocks from another html file in Django template?
Suppose I have 2 files base.html and home.html. home.html: {% block block1 %} b1 {% endblock %} {% block block2 %} b2 {% endblock %} {% block block3 %} b3 {% endblock %} ... and many more base.html: <!-- need extending other files so it is not an option. --> {% extends 'othertemplate.html' %} {% include 'home.html' %} <-- I only want block2 from this file here. How do I do this when displaying 'base.html'? -
Django ModelForm's DateTime value being localized/translated with localization turned off
So I'm working on this Activity management platform, we are using Django 3.0.4. Before I expose my problem, I must say that I'm somewhat new to Django and python itself. My current objetive is to allow the administrator to set specific dates for specific events. Initially the page must show the current dates and details. That I can already the do with the code shown below This is an example of the model used to store the dates class Dates(models.Model): id = models.AutoField(db_column='ID', primary_key=True) datestart = models.DateTimeField(db_column='DateStart') dateend = models.DateTimeField(db_column='DateEnd') class Meta: db_table = 'Dates' This is my form class dateForm(forms.ModelForm): class Meta: model = Dates exclude = ['id'] And this is my current view function def editdates(request): dates_current = Dates.objects.get(id=1) dates_form = dateForm(instance=dates_current) if request.method == 'POST': submitted_data = request.POST.copy() #Might need to change incoming data before saving to db dates_form = diaAbertoSettingsForm(submitted_data, instance=dates_current) #Generate form with existing data if dates_form.is_valid(): dates_form.save() return render(request=request, template_name = 'dates/edit.html', context = {'form': dates_form}) The same page that shows the data (dates) must also allow you to submit a change, this would be relatively easy to do. The real problem starts when I want to submit the form. Currently, I do the … -
How to make notifications from one app to another app in django?
I am making one e-commerce website and i am just trying to make notifications from admin side to user side both are diffrent app in django... My problems is how to make notifications in admin side (one app)when i click the button send the messages and display the notifications or message in userside(other app) -
Django range filter datetimeshortcuts
Using Django-admin-rangefilter 0.5.4 with djanog 3.0.4 and Grappelli 2.14. Getting error: can't find variable: DateTimeShortsCuts in production when using rangefilter. which results in no date picker. While in development it's working fine. The date time picker working in Django Admin. Can someone suggest how to debug/correct this. -
how to display model questions and options and get the choice choosen by user in django
i'm creating quiz website in django...i'm confused in how can i get the quetions and options of model and display it into the page.and how i campare the choosen options with the result model answer and increament the score. here is my MODELS.PY class question(models.Model): question=models.CharField(max_length=100) def __str__(self): return self.question class options(models.Model): question=models.ForeignKey(question,default=1,on_delete=models.SET_DEFAULT) op1=models.CharField(max_length=20) op2=models.CharField(max_length=20) op3=models.CharField(max_length=20) op4=models.CharField(max_length=20) # def __str__(self): # return self.question class answer(models.Model): question=models.ForeignKey(question,default=1,on_delete=models.SET_DEFAULT) result=models.CharField(max_length=50) template(quizpage.html) <body> <h2>Hello, {{username}}</h2> <div id="nav"> <a href="/logout">Logout</a> </div> <br> {% for i in ques %} <h2>{{i.optionsid}}{{i.question}}</h2> <br> <form action="/next" method="POST"> <input type="radio" name="answer" value="a"><span>{{i.op1}}</span> <input type="radio" name="answer" value="a"><span>{{i.op2}}</span> <input type="radio" name="answer" value="a"><span>{{i.op3}}</span> <input type="radio" name="answer" value="a"><span>{{i.op4}}</span> <input type="submit" value="next"> </form> {% endfor %} </body> Views.py def addscore(request): score=0 if request.method=='POST': ans=request.POST.get('answer') ?????? return render(request,'nextpage') else: return render(request,'quizapp/quizpage.html') def nextquestion(request): pass def showtest(request): ops=models.options.objects.filter(id='id') return render(request,'quizapp/quizpage.html',{'ops':ops}) -
I made django application but can't orchestration in GKE
I made django appilcation in reference to official manual. https://cloud.google.com/python/django/kubernetes-engine?hl=ja After pushing the Docker image, I got bellow message in EXTERNAL-IP page. Django Version: 2.2.5 Exception Type: OperationalError Exception Value: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0") When I develop in local, I can connect to Cloud SQL instance. But, it seems that GKE resource can't connect to Cloud SQL instance. I think I made secret for instance-level access and database access correctly according to manual. When I create secret for instance-level access, I type bellow command. kubectl create secret generic cloudsql-oauth-credentials --from-file=credentials.json=appname-0000-*******.json When I create secret for database access, I type bellow command. kubectl create secret generic cloudsql --from-literal=username=user --from-literal=password=*** I edited in polls.yaml. In polls.yaml, I edited like bellow. # [START proxy_container] - image: gcr.io/cloudsql-docker/gce-proxy:1.05 name: cloudsql-proxy command: ["/cloud_sql_proxy", "--dir=/cloudsql", "-instances=appname-0000:asia-northeast1:mysqlinstance=tcp:5432", "-credential_file=/secrets/cloudsql/credentials.json"] In settings.py, I coded about DATABASES like bellow. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'polls', 'USER': os.getenv('DATABASE_USER'), 'PASSWORD': os.getenv('DATABASE_PASSWORD'), 'HOST': '127.0.0.1', 'PORT': '5432', } } What can cause this error? Please let me know the solution! -
How to send static file link as variable in `include` tag in Django?
Suppose I have a base.html and home.html. The base.html file has: {% include 'home.html' with thelink='hard/coded/link' %} And home.html contains: The link of static file is : {{ thelink }} This works well so far. But now, I want to do this: base.html: {% load static %} {% include 'home.html' with thelink={% static 'link' %} %} I know this will not work. So how do I send a variable with static files references in the include tag? -
UnicodeDecodeError: 'gbk' codec can't decode byte 0x82 in position 402: illegal multibyte sequence
when I use pipenv install django-mdeditor,then happend this question as follows: pipenv install -e git+https://github.com/pylixm/django-mdeditor.git@master#egg=django-mdeditor Installing -e git+https://github.com/pylixm/django-mdeditor.git@master#egg=django-mdeditor… Adding django-mdeditor to Pipfile's [packages]… Installation Succeeded Pipfile.lock (0c05dd) out of date, updating to (5c4038)… Locking [dev-packages] dependencies… Locking [packages] dependencies… Locking Failed! ... Traceback (most recent call last): UnicodeDecodeError: 'gbk' codec can't decode byte 0x82 in position 402: illegal multibyte sequence how can I solve it? -
Overwrite create method for a Django restframework nested serializer
I am trying to use nested writable serializer in django-rest-framework. When I send a POST request with following data: { "acc_name": "Salary Card", "acc_type_id": { "id": 2, "acc_type_name": "Debit Card" }, "credit_amt": null, "bill_dt": null, "due_dt": null, "balance": "0.00", "comments": null } I got an error: Cannot assign "OrderedDict([('acc_type_name', 'Debit Card')])": "Accounts.acc_type_id" must be a "AccountTypes" instance. I actually passed id for AccountTypes, but why restframework remove it automatically? How can I resolve this problem? How can I create a new account with existing account type? Views: class AccountTypesViewSet(ListAPIView): name = __name__ pagination_class = None queryset = AccountTypes.objects.filter(active='Y') serializer_class = AccountTypesSerializer class AccountsViewSet(viewsets.ModelViewSet): pagination_class = None queryset = Accounts.objects.all() serializer_class = AccountsSerializer Models: class AccountTypes(models.Model): id = models.AutoField(primary_key=True, editable=False) acc_type_name = models.CharField(max_length=50) active = models.CharField(max_length=1, default='Y') class Meta: db_table = f'"{schema}"."taccount_types"' managed = False class Accounts(models.Model): id = models.AutoField(primary_key=True, editable=False) acc_name = models.CharField(max_length=1024) acc_type_id = models.ForeignKey( to=AccountTypes, db_column='acc_type_id', related_name='accounts', on_delete=models.DO_NOTHING ) credit_amt = models.DecimalField(max_digits=11, decimal_places=2, null=True) bill_dt = models.DateField(null=True) due_dt = models.DateField(null=True) balance = models.DecimalField(max_digits=11, decimal_places=2, default=0) comments = models.CharField(max_length=1024, null=True) class Meta: db_table = f'"{schema}"."taccounts"' managed = False Serializers: class AccountTypesSerializer(serializers.ModelSerializer): class Meta: model = AccountTypes fields = ('id', 'acc_type_name') class AccountsSerializer(serializers.ModelSerializer): # acc_type = serializers.SlugRelatedField(slug_field='acc_type_name', source='acc_type_id', read_only=True) acc_type_id … -
Django Allauth Encrypt Email in account_emailaddress Table
I have successfully encrypted the user email via a custom user model with https://github.com/incuna/django-pgcrypto-fields. However, for some reason allauth does not encrypt the same email under the account_emailaddress table. This table is used to identify if a user has verified their email and if their email is their primary email. How would I be able to encrypt the email in that table? Code: Settings.py: PGCRYPTO_KEY = 'hello' INSTALLED_APPS = [ 'pgcrypto', ] Custom User Model models.py: from pgcrypto import fields class CustomUserManager(BaseUserManager): def _create_user(self, email, password,is_staff, is_superuser, **extra_fields): now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email,is_staff=is_staff, is_active=True,is_superuser=is_superuser, last_login=now,**extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): return self._create_user(email, password, False, False,**extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password, True, True,**extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): objects = CustomUserManager() email = fields.EmailPGPSymmetricKeyField() identifier = models.CharField(unique=True, max_length=50, default=uuid.uuid1) username = models.CharField(_('username'), max_length=30, blank=True, default='', unique=True) USERNAME_FIELD = 'username' first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_mod = models.BooleanField(_('moderator status'), default=False, help_text=_('Designates whether the user can … -
how do i properly include a template inside another template in django
i am trying to include a template(header.html) from another view into another template(index.html) that has another view but nothing seems to display from the header section when i load the page heres the views.py from django.contrib.auth import get_user_model from django.views.generic import TemplateView, ListView from baykay.models import Projects, Profile User = get_user_model() class HomeView(TemplateView): template_name = 'portfolio/index.html' class Header(ListView): template_name = 'portfolio/header.html' model = Profile context_object_name = 'header' here is the header.html <div class="container clearfix"> {% for profile in object_list %} {% if profile.image %} <img class="profile-image img-fluid float-left avatar-img" src="{{ profile.image.url }}" alt="young-baykay"/> {% endif %} <div class="profile-content float-left"> <h1 class="name">{{ profile.user.get_full_name|title }}</h1> <h2 class="desc">{{ profile.profession|title }}</h2> </div><!--//profile--> {% endfor %} <a class="btn btn-cta-primary float-right" href="#" target="_blank"><i class="fas fa-paper-plane"></i> Contact</a> </div> here is the index.html <!DOCTYPE html> <html lang="en"> <head> {% include 'portfolio/styles.html' %} </head> <body> <header class="header"> {% include 'portfolio/header.html' with profile=object_list only %} </header><!--//header--> {% include 'portfolio/footer.html' %} {% include 'portfolio/javascript.html' %} </body> </html> here is the model.py from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='profile_pic', blank=True, null=True) profession = models.CharField(max_length=50, blank=True, null=True) bio = models.TextField(blank=True, null=True) city = models.CharField(max_length=10, blank=True) country = models.CharField(max_length=10, blank=True) website … -
How do I upload files from Django admin directly to Google Cloud Storage, and how do I render them in the templates?
I am trying to store images in Google Cloud Storage for a production website. I have google cloud storage currently and I am wondering how to have the images uploaded in the Django admin store in GCS and how to render these in the templates. I have tried assigning the MEDIA_URL to the GCS bucket but they are not storing. Basically I just need some guidance from the start on how to achieve this. -
Many To Many Django, create instance
En estos momentos estoy desarrollando un proyecto, en el cual una de las secciones permite realizar una serie de anuncios, la idea del mismo es que estos tengan varias imágenes relacionadas,en la forma en la que tengo desarrollada esa sección, solo me permite almacenar una imagen por anuncio, y me gustaría saber como puedo hacer para agregar varias al mismo tiempo, a continuación presento el modelo, los formularios, y la vista para crearlo. Modelo class Ad(models.Model): id_user = models.ForeignKey(Account, on_delete=models.CASCADE) id_store = models.ForeignKey(Store, on_delete= models.CASCADE,default=None, blank=True, null=True) id_location= models.ForeignKey(Location, on_delete= models.CASCADE) id_ad_kind= models.ForeignKey(AdKind, on_delete= models.CASCADE) id_category= models.ForeignKey(Category, on_delete= models.CASCADE) id_unit= models.ForeignKey(Unit, on_delete= models.CASCADE, default = None, blank=True, null=True) ad_name= models.CharField(max_length=100) ad_description= models.TextField() price= models.FloatField() date_created = models.DateTimeField(auto_now_add=True) ad_images= models.ManyToManyField(Image, related_name="get_images_ad") def __str__(self): return self.ad_name class Meta(): verbose_name= "Anuncio" verbose_name_plural= "Anuncios" class Image(models.Model): img_route= models.ImageField(upload_to="Images", verbose_name="Ruta de la Imagen") class Meta(): verbose_name= "Imagen" verbose_name_plural= "Imagenes" Formulario class AdCreateForm(forms.ModelForm): class Meta(): model= Ad fields=('ad_name', 'ad_description','price','id_location', 'id_ad_kind','id_category','id_unit',) class AdImageForm(forms.ModelForm): class Meta(): model= Image fields=('img_route',) Vista def AdCreate(request): model = Ad if request.method == "POST" : ad_form= AdCreateForm(request.POST) img_form= AdImageForm(request.POST,request.FILES ) print("img es "+ str(img_form.is_valid())) print(img_form) if ad_form.is_valid() and img_form.is_valid(): img= img_form.save() ad= ad_form.save(False) ad.id_user = request.user ad= ad_form.save() ad.ad_images.add(img) ad.save() print("Almacenado") return render(request,'ad/ad_list.html') … -
Django Postgresql Cannot Decrypt From Query
Error: ERROR: function pg_sym_decrypt(bytea, unknown) does not exist LINE 1: select pg_sym_decrypt(users_customuser.email, 'hello') from ... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Query: select pg_sym_decrypt(users_customuser.email, 'hello') from users_customuser I installed pgcrypto in pgadmin but it seems like the function is missing? Does the Django package not allow decryption from sql, and instead only allows decryption from the Django code? My objective is to decrypt the encrypted emails from the database using queries. How would I do that? Django Package: https://github.com/incuna/django-pgcrypto-fields Django settings.py: PGCRYPTO_KEY = 'hello' Django models.py: from pgcrypto import fields email = fields.EmailPGPSymmetricKeyField() -
Validation Error when filtering by UUID Django
I am attempting to return all the friends of friends of a certain user who is the author of the relationship. However, I keep getting this error: ValidationError at /author/posts ["“[UUID('8c02a503-7784-42f0-a367-1876bbfad6ff')]” is not a valid UUID."] class Author(AbstractUser): ... uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False, unique=True) ... class Post(models.Model): ... author = models.ForeignKey(Author, on_delete=models.CASCADE) ... class Friend(models.Model): class Meta: unique_together = (('author','friend'),) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') friend = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='friend') This foaf line in particular is where the error is coming from. How else could I do this? friends = Friend.objects.filter(author=userUUID) foafs = Friend.objects.filter(friend=[friend.friend.uuid for friend in friends]) -
BookingConfirmation() missing 1 required keyword-only argument: 'amount'
I pretty new in Python and Django,and I am trying to build a hostel reservation using stripe. I am trying to pass data(The price of the room) from my room detail view to the Charge view but I get the following error. TypeError at /booking/confirm/ BookingConfirmation() missing 1 required keyword-only argument: 'amount' Request Method: POST Request URL: http://localhost:8000/booking/confirm/ Django Version: 3.0.2 Exception Type: TypeError Exception Value: BookingConfirmation() missing 1 required keyword-only argument: 'amount' Exception Location: C:\Users\Administrator\Desktop\hostel\env\lib\site-packages\django\core\handlers\base.py in _get_response, line 113 Python Executable: C:\Users\Administrator\Desktop\hostel\env\Scripts\python.exe Python Version: 3.7.3 Here is my Room Detail View def RoomBookingView(request,pk): publishkey = settings.STRIPE_PUBLISHABLE_KEY if request.method == 'POST': if pk: room_id = Room.objects.get(pk = pk) amount = room_id.price student_id = request.user room_id.is_reserved = True, reservation = Reservation( room_id = room_id.id, student_id = student_id.id, ) reservation.save() try: room = Room.objects.get(id=pk) room.is_reserved = True amount = room_id.price room.save() except BaseException: pass return redirect(reverse('confirm', args=[amount])) context = { 'STRIPE_PUBLISHABLE_KEY' : publishkey, } return render(request,'room-detail.html',context) And my Charge View def BookingConfirmation(request,*args,amount): amount = args if request.method == 'POST': charge = stripe.Charge.create( currency='usd', amount = amount, description='A Django charge', source=request.POST['stripeToken'] ) return render(request,'booking-confirm.html',{}) -
How to setup a flexible django models
I'm new to django. What I'm trying to achieve is when the ProductType combobox is changed, the fields changes to its specific fields then the users inputs using those field and entered to the database. My problem is how to create a flexible model that would accept extra fields Sample: Input from django.db import models class Product(models.Model): """SKU""" stock = models.IntegerField(default=None) class ProductType(models.Model): product_field = models.ForeignKey(ProductFields, on_delete=models.CASCADE) name = models.CharField(max_length=255) class ProductFields(models.Model): """Fields of ProductType""" Here's an DB example I'm trying to achieve See Image -
Function performance: backend vs frontend
I would like to know if it's better for the user's experience to execute a high resources demand function in the backend (django) or in the frontend(JS), for example, a function that performs a query and then a sorting. -
Annotate based on calculation in ManyToManyField
I am trying to annotate a Django model by calculating a non-trivial expression using a property of a ManyToManyField in the model. The situation can be translated into the following simple example structure of "payments" that should be split between a number of "companies" according to their relative sizes. Which companies participate in a given payment is stored as a ManyToManyField: class Company: relative_size = models.DecimalField() ## can be assumed to add up to 1 among all companies class Payment(models.Model): companies = models.ManyToManyField(Company, related_name='payments', blank=True) amount = models.DecimalField() I'm now trying to query for the total amount that each company participated in. If the share was the same in each of the payments, this would be as simple as companies = Company.objects.annotate(total_payments=Sum(F('payments__amount')*F('relative_size'))) for company in companies: print("Company %s: %s" (str(company), total_payments)) But how to do this in the case where I have to calculate the correct fraction for every payment based on which companies participated? I tried something with SubQuery similar to the following, but couldn't really make sense of it or get it to work: ## this is clearly wrong, but just to illustrate what I'm after payments_per_company = Payment.objects.filter(company=OuterRef('pk')).values('company') payment_total_size = payments_per_company.annotate(totalfraction=Sum(F('companies__relative_size'))) companies = Company.objects.annotate(total_payments=Sum(F('payments__amount')*F('relative_size')/Subquery(payment_total_size))) Can anyone help … -
Cannot display all the results in a M2M relationship
Currently, I have the following entity relationship model : Table relationship ------------ ----------------- ------ | Objective | ------- | Objective_Task | ---------| Task | ------------ ----------------- ------ and I am trying to display the results as in the following table | id | Task | Task status | Objective | ---------------------------------------------------------------- | 1 | Set up drivers | In progress | Set up my machine | | 2 | Configure network | In progress | Set up the network | | 3 | Test the network | In progress | Set up the network | But the result I get is: | id | Task | Task status | Objective | ----------------------------------------------------------------------- | 1 | Set up drivers | In progress | objective.Objective.None | | 2 | Configure network | In progress | objective.Objective.None | | 3 | Test the network | In progress | objective.Objective.None | Below is the setup of my class models for this entity relationship: Objective model class Objective(models.Model): id = models.AutoField(primary_key=True) objective = models.CharField(null=False, max_length=60) initial_date = models.DateField(default=timezone.now(), null=False) expiration_date = models.DateField() class Meta: ordering = ['initial_date'] db_table = 'goal_objective' Task model class Task(models.Model): ACTIVE = 'Active' FINALIZED = 'Finalized' STATUS = [(ACTIVE, ACTIVE), (FINALIZED, … -
Cannot set value to instance
I am building a vote system for my app. I have 2 models, topic where votes are registers and VoteUser that takes topic as a foreign key and set the vote user to true Models : class Topic(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) votes = models.IntegerField(default=1) class VoteUser(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE, null=True, blank=True, related_name='TopicVote') vote_status = models.BooleanField(default=False) author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) Now when an user vote I want the model "VoteUser" to set the topic to a certain value and set vote_status to true So I tried this : View : def upvote(request, qa_id): vote = VoteUser.objects.create(author=request.user) qa = get_object_or_404(Topic, pk=qa_id) vote = get_object_or_404(Topic, pk=qa_id) qa.votes += 1 qa.save() But I am not able to set the topic even when I used the pk from a topic I know exist. Could you help ? -
Django Statement Scoped View Query
I have three models, Result, Environment and Test. Environment and Test are FKs in Result. I was trying to find the latest Result in a given Environment for each Test - essentially to produce a page for an Environment that shows the latest Result for each Test. In the process of trying to optimize a PostreSQL query, I came up with the following: WITH CR AS (SELECT "cases_result"."test_id", max("cases_result"."created_at") "created_at" FROM "cases_result" WHERE "cases_result"."environment_id" = 1001 GROUP BY "cases_result"."test_id" ) SELECT CR.* , "cases_test"."id", "cases_test"."created_at", "cases_test"."updated_at", "cases_test"."name", "cases_test"."usage", "cases_test"."result_id", "cases_test"."health", "cases_test"."variance", "cases_test"."duration", "cases_test"."required", "cases_test"."ticket", "cases_test"."removed_at" FROM CR JOIN "cases_test" ON CR."test_id" = "cases_test"."id" ORDER BY CR."test_id" ASC, CR."created_at" DESC I'm now trying to see if I can implement this in my models.Manager. I currently have: tests = Test.objects.order_by('name') if environment.domain != 'example.com': tests = tests.exclude(name__startswith='sample') results = ( self.filter(test__in=tests, environment=environment) .select_related('test') .prefetch_related('test__teams') .order_by('test_id', '-created_at') .distinct('test_id') ) for test in tests: for result in results: if result.test == test: yield result break Can I use Django ORM to create this query, or will I need to use raw SQL and fetch the associated result objects? -
Django Ajax form not showing up
I trying to use Ajax and Django to submit forms. However, when I click on the button nothing happens and there is no response and the modal does not open. I am trying to prompt users to create a post and then post it to the page without refreshing. So far my code is this: my home/home.html where the button that should open the post is: <button class="btn btn-sm btn-primary show-form ml-auto" data-url="{% url 'home:post-create' %}"><i class="fas fa-plus-square"></i></button> my modal and script in same file: <div class="modal fade" id="modal-post"> <div class="modal-dialog"> <div class="modal-content"></div> </div> </div> <script> $(document).ready(function(){ $('.show-form').click(function(){ $.ajax({ url: '/home/post/create', type: 'get', dataType:'json', beforeSend: function(){ $('#modal-post').modal('show'); }, success: function(data){ $('#modal-post .modal-content').html(data.html_form); } }); }); $('#modal-post').on("submit",".create-form", function(){ var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr('method'), dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#post-list div').html(data.posts); $('#modal-post').modal('hide'); } else { $('#modal-post .modal-content').html(data.html_form) } } }) return false; }) }); </script> my views for creating a post: @login_required def save_all(request,form,template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/home_post.html',{'posts':posts}) else: data['form_is_valid'] = False context = { 'form':form } data['html_form'] = render_to_string(template_name,context,request=request) return JsonResponse(data) @login_required def post_create(request): if request.method == 'POST': form = …