Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Printing logs (of the running website) in VSCode console
hi all I have a web built with django framework and running with apache now. I am trying to print() but nothing is shown on the console, so I turned to logger and no luck still. This is one of my log I tried to print in the view.py, and I was expecting 'helloworld' could be shown on my console... import logging logger = logging.getLogger(__name__) logger.info('helloworld') is there anything i should be setting elsewhere? kindly help, thanks. -
Django conditional for rendering template
I am new to django and am trying to only render text which does not have the word 'After' or 'Before' in it. However this didnt break anything but it didnt actually remove those values? I looked at using a regex but this really isnt recommended for django templates. {% if "After" not in window.name or "Before" not in window.name %} {{window.event_id}}-{{window.name}} {% endif %} The codebase I am working on makes it almost impossible to remove these values in the models before you get to the template... I can only apologise for maintaining and putting up with this! -
Django modify table with jquery and ajax
I have a problem with my code. I'm trying to modify a data table utilizing the ajax code but does not work. I have create the json response in my view and add the script in my html code. When I try to edit my id.element in my shell recevice the following message: "GET /magazzino/?formId=1&formCodice=1&formCategoria=MATERIA+PRIMA&formSottocategoria=ciao HTTP/1.1" 200 16137". I don't know if it will help. This is my html code: {% extends "base/base.html" %} {% load crispy_forms_tags %} {% block content %} <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4"> .... <h1>Approvvigionamenti</h1> <div class="row"> <div class="col-md-12 "> <h3>Registra materiale acquistato</h3> <form id="addUser" method="post"> {% csrf_token %} <div class="form-row"> <div class="form-group col-2 0 mb-0"> {{form.codice|as_crispy_field}} </div> <div class="form-group col-5 0 mb-0"> {{form.tipologia|as_crispy_field}} </div> <div class="form-group col-5 0 mb-0"> {{form.sottocategoria|as_crispy_field}} </div> </div> <div class="form-row"> <div class="col-md-2 "> <button class="btn btn-primary form-control" type="submit">Registra nel magazzino</button> </div> </div> </form> </div> <div class="col-md-12"> <br> <h3>Materiale registrato</h3> <table id="userTable" class="table table-striped"> <tr> <th>Codice</th> <th>Tipologia</th> <th>Sottocategoria</th> </tr> {% if materiale %} {% for element in materiale %} <tr id="element-{{element.id}}"> <td class="codice userData" name="codice">{{element.codice}}</td> <td class="categoria userData" name="categoria">{{element.tipologia}}</td> <td class="sottocategoria userData" name="sottocategoria">{{element.sottocategoria}}</td> <td align="center"> <button class="btn btn-success form-control" onClick="editUser({{element.id}})" data-toggle="modal" data-target="#myModal"> Modifica</button> </td> <td align="center"> <button class="btn btn-danger form-control" onClick="deleteUser({{user.id}})">DELETE</button> … -
Django Rest Framework, Why does separate serialization class for Image fields is been required?
When serializing a model that contain image field, separate serialization class was been required. Why can't we serialize the model completely in single class ? Serializer.py class ProfileSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) avatar = serializers.ImageField(read_only=True) class Meta: model = Profile fields = '__all__' class AvatarSerializer(serializers.ModelSerializer): class Meta: model = Profile fields =('avatar',) models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) bio = models.CharField(max_length=100,blank=True) avatar = models.ImageField(null=True,blank=True) def __str__(self): return self.user.username I am following a tutorial in Udemy GitLink : https://github.com/pymike00/The-Complete-Guide-To-DRF-and-VueJS/tree/master/05-DRF-LEVEL-THREE/profilesapi/profiles/api -
CSS loaded but not takes effect on the display
I always get stuck at CSS. I have a table, which works perfectly fine on large screens, and for mobile devices I want the table to be in a card format. I got an idea of creating another div and made the UI for mobile devices as well. And Using CSS, I tried... resp.css .immobile{ display: none; } .immonitor{ display: block; } @media screen and (max-width: 764px){ .immonitor{ display: none; } .immobile{ display: block; } } List.html <tbody> {% for order in order_list %} <div class="immonitor"> <tr> <td>{{ order.id }}</td> <td>{{order.client_name}}</td> <td>{{order.event_name}}</td> <td>{{order.event_date}}</td> <td>{{order.location}}</td> <td><a href="{% url 'order_detail' order.id %}">View</a></td> </tr> </div> <div class="immobile"> <tr> <td> <div> {{order.client_name}} <br> <h3>{{ order.id }}</h3> </div> <div class="pull-right"> {{order.event_name}}<br> {{order.event_date}}<br> {{order.location}}<br> </div> </td> </tr> </div> {% endfor %} </tbody> Now, the CSS doesn't have any effect on the table, it displays both card and table. And the CSS is perfectly loaded. -
Django getting the option value from a drop down menu
I am creating a Django page and I have two drop down menus. The first drop down menu will select a test. Then based on whatever test they selected, it should populate the second drop down menu with some ManyToMany fields. Here is my drop down menus <form> <select name="test"> {% for test in test %} <option value={{ test.name }}>{{ test.name }}</option> {% endfor %} </select> </form> <form> <select name="event"> {% for applicable_events in test %} <option value={{ applicable_events.name }}>{{ applicable_events.name }}</option> {% endfor %} </select> <input type="submit" value="Submit"> </form> The first form is correctly populating all of my tests. Now when the user selects one of the options in the first drop down, I am trying to get whatever they selected so that I can then populate the second drop down. Here are my two models.. class Event(models.Model): name = models.CharField(max_length=255) #test = models.ManyToManyField(Test) applicable_devices = models.ManyToManyField(Device) applicable_platforms = models.ManyToManyField(Platform) class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return self.name class Test(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) applicable_device = models.ManyToManyField(Device) applicable_platform = models.ManyToManyField(Platform) applicable_events = models.ManyToManyField(Event) class Meta: verbose_name = 'Test' verbose_name_plural = 'Tests' def __str__(self): return self.name So you can see that for each … -
NoReverseMatch at /admin/r/1/APT2/ Reverse for 'apartment_create' not found. 'apartment_create' is not a valid view function or pattern name
I am trying to display a template on Django 3.0 and I get NoReverseMatch Error. Obviously, the url.py and views.py fail to show the template. I am on admin page adding a new record, but when I click show on site, I get this error. 1) What is the first part of admin/r/1/APT2 url mean especially the r/1? I believe this should redirect to apartment_create.html, but the view function does not exist or there is no url by that name. But according to me, there is. NoReverseMatch at /admin/r/1/APT2/ Reverse for 'apartment_create' not found. 'apartment_create' is not a valid view function or pattern name. views.py class ApartmentCreate(CreateView): # make a form based on this model form_class=ApartmentForm # if we only want to edit these two fields # fields = ('first_name', 'last_name') fields = '__all__' class Meta: widgets = {'geom': LeafletWidget()} # render this html file, pass a form object to that file template_name = 'rent_app:apartment_create.html' #template_name = 'rent_app/form_template.html' def get_success_url(self): return reverse('rent_app:apartment_create_success') urls.py from django.urls import path from . import views from django.contrib import admin app_name = 'rent_app' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('admin/', admin.site.urls), path('apartment_create/<slug:apt_id>', views.ApartmentCreate.as_view(), name='apartment_create'), path('apartments/<int:pk>/', views.ApartmentUpdate.as_view(), name='apartment_update'), path('apartments/<int:pk>/delete/', views.ApartmentDelete.as_view(), name='apartment_delete'), -
Error during template rendering (NoReverseMatch) in Django
I am trying to submit the form to my view: in trending.html: {% extends 'djangobin/base.html' %} {% load static %} {% load humanize %} {% block title %} Trending {{ lang.name }} Snippets - {{ block.super }} {% endblock %} {% block main %} <h5><i class="fas fa-chart-line"></i> Trending {{ lang.name }} Snippets</h5> <hr> <table class="table"> <thead> <tr> <th>Title</th> <th>Date</th> <th>Hits</th> <th>Language</th> <th>User</th> </tr> </thead> <tbody> {% for snippet in snippets %} <tr> <td><i class="fas fa-globe"></i> <a href="{{ snippet.get_absolute_url }}">{{ snippet.title }}</a> </td> <td title="{{ snippet.created_on }}">{{ snippet.created_on|naturaltime }}</td> <td>{{ snippet.hits }}</td> <td><a href="{% url 'trending_snippets' snippet.language.slug %}">{{ snippet.language }}</a></td> {% if not snippet.user.profile.private %} <td><a href="{{ snippet.user.profile.get_absolute_url }}">{{ snippet.user.username|title }}</a></td> {% else %} <td>-</td> {% endif %} </tr> {% empty %} <tr class="text-center"> <td colspan="4">There are no snippets.</td> </tr> {% endfor %} </tbody> </table> {% endblock %} in views.py: from django.shortcuts import HttpResponse, render, redirect, get_object_or_404, reverse from .forms import SnippetForm from .models import Language, Snippet def trending_snippets(request, language_slug=''): lang = None snippets = Snippet.objects if language_slug: snippets = snippets.filter(language__slug=language_slug) lang = get_object_or_404(Language, slug=language_slug) snippets = snippets.all() return render(request, 'djangobin/trending.html', {'snippets': snippets, 'lang': lang}) in urls.py: from django.conf.urls import url from . import views as views urlpatterns = [ url('^trending/$', … -
Django Sum positive values seperate from negative values
Can you sum positive values seperately from negative values? I have a table that looks like this: class Order(models.Model): date = models.DateField() amount = models.DecimalField() I'm looking to get a queryset that sums the postive amounts seperate from the negative amounts and groups by week: Year Week Sum of positive amounts Sum of negative amounts I'm able to get all positive amounts per week seperately by doing: Order.objects.filter(amount__gt=0).annotate(year_week=Trunc('date', 'week', output_field=DateField())).\ annotate(year=ExtractYear('year_week')).annotate(week=ExtractWeek('year_week')).\ values("year_week", "year", "week").annotate(value=Sum("amount")).order_by("-year_week") I can do this again for the negative value, but then I have two seperate querysets. Can I merge them efficiently without looping manually or is there a way to do both in a single query? -
How to correct TypeError: Unicode-objects must be encoded before hashing? - django - python
Does anyone know how to solve the following error ------activation_key = hashlib.sha1(short_hash+base).encoding.hexdigest() TypeError: Unicode-objects must be encoded before hashing----- all the code regarding the problem is attached below. All help appreaciated! import stripe import random import hashlib from django.conf import settings from django.contrib.auth.signals import user_logged_in from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile, UserStripe, EmailConfirmed stripe.api_key = settings.STRIPE_SECRET_KEY def get_create_stripe(user): new_user_stripe, created = UserStripe.objects.get_or_create(user=user) if created: customer = stripe.Customer.create( email = str(user.email) ) new_user_stripe.stripe_id = customer.id new_user_stripe.save() @receiver(post_save, sender=User) def create_profile(sender, instance, created, *args, **kwargs): user=instance if created: get_create_stripe(user) email_confirmed, email_is_created = EmailConfirmed.objects.get_or_create(user=user) if email_is_created: short_hash = hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5] base, domain = str(user.email).split("@") activation_key = hashlib.sha1(short_hash+base).encode('utf-8').hexdigest() email_confirmed.activation_key = activation_key email_confirmed.save() emailconfirmed.activate_user_email() -
'NoneType' object has no attribute in the form init
Gives me that error 'NoneType' object has no attribute 'tutor_courses', i am trying to get query set with courses where request.user is in the tutor field. How to fix that? models.py class Course(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=150, null=True, blank=True) description = models.TextField() image = models.ImageField(upload_to='courses/course_images',blank=True,null=True) cover = models.ImageField(upload_to='courses/course_covers',blank=True,null=True) tutor = models.ForeignKey(User,related_name='tutor_courses',on_delete=models.CASCADE) students = models.ForeignKey(User,related_name='course_students',blank=True,on_delete=models.CASCADE,null=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) category = models.ForeignKey(CourseCategories,on_delete=models.CASCADE) certificate = models.ImageField(upload_to='courses/course_certificates',blank=True,null=True) languages = LanguageField(blank=True) rank_score = models.FloatField(default=0.0) price = models.FloatField(default=0.0) discount_price = models.FloatField(blank=True, null=True) forms.py class SectionForm(forms.ModelForm): def get_tutor_courses(self): return self.user.tutor_courses course = forms.ModelChoiceField(queryset=Course.objects.all()) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(SectionForm, self).__init__(*args, **kwargs) tutor_courses = user.tutor_courses.all() self.fields['course'].queryset = tutor_courses if not tutor_courses: self.fields['course'].help_text = "You need to <b>create</b> a course to create sections in it" class Meta: model = CourseSections fields = ('title','course') -
Django Checkout form not being saved
Hi I'm trying to develop an e-commerce site with Django. So I'm at this point where, users can add items to their cart, proceed to checkout but for some reason, my checkout form is not being saved. I made sure that I have registered my models, and ran migrations, but everytime I fill out my form and go to check in my admin panel, it says: 0 user addresses. Also after clicking the submit button, it's not getting redirected to checkout, rather it's being redirected to: http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=a8vjroAuxAcGFjQmwZ6CdBL5DhYui0vKVnANaoi8lxY33uqjmLXaT90tze6Anyun&address=123+Main+Street%2C+234+Irvine&address2=234+Irvine&state=MA&country=United+States&zipcode=55525&phone=8773140742&billing=on What is the problem? Can anyone please help me out? My views.py: @login_required def checkout(request): if request.method == 'POST': address_form = UserAddressForm(request.POST) if address_form.is_valid(): new_address = address_form.save(commit= False) new_address.user = request.user new_address.save() return redirect(reverse("checkout")) else: address_form = UserAddressForm() context = {"address_form": address_form} template = "orders/checkout.html" return render(request, template, context) My checkout.html: <form method="POST" action=''> {% csrf_token %} <fieldset class="form-group"> {{ address_form|crispy }} </fieldset> <div class="form-group"> <input type="submit" class="btn btn-outline-dark" value="Place Order"/> </div> </form> My urls.py: from orders import views as orders_views path('checkout/', orders_views.checkout, name='checkout'), -
How to addd Content Security policy to heroapp?
I created a Python Heroku app. I want to put Content-Security-Policy to the header. I did some google search, but I still very confused. Some people said to add "headers": { "/**": { "Content-Security-Policy": "default-src 'self'; script-src https://static.ads-twitter.com https://www.google-analytics.com; img-src 'self' https://s3.amazonaws.com https://twitter.com https://pbs.twimg.com; font-src 'self' https://fonts.gstatic.com; style-src 'self' https://fonts.googleapis.com; frame-ancestors 'none';" } } into static.json. However, I don't have this file in my project. How should I link it? Thanks! -
How to correctly use MongoDB client connections
I'm building a simple test web application that stores info users enter in a mongo database. No errors come up, but I always get the following warning (Im using django) when using the client. /home/<User>/.local/share/virtualenvs/<Name>/lib/python3.7/site-packages/pymongo/topology.py:155: UserWarning: MongoClient opened before fork. Create MongoClient only after forking. See PyMongo's documentation for details: http://api.mongodb.org/python/current/faq.html#is-pymongo-fork-safe "MongoClient opened before fork. Create MongoClient only " After checking out the API docs, it seems that the warning pops up when using fork() which im not explicitly using. Maybe something that I'm doing is actually triggering the fork. I create my mongo client at __init__ and then import the variable to my mongoDB handler. Then, that client that I imported is used inserting or updating items in the DB. What is the correct way of creating and then using a mongo client to prevent this warning from appearing? -
Confused by Django Rest Framework Permissions
I have a complex set of permissions that I want to apply to my views, but I'm having a hard time understanding where to put them. Here are my basic permissions. List all projects: If the user is the owner and if their account is active Or if they are a superuser And the object is not private to a different user Or they are a member of the assigned group Problem is that when I add this logic to the permissions classes of the ModelApiViewset, it returns every project. How do I get it to show only the ones that meet the above criteria? To further illustrate the example, I have 2 accounts right now: my superuser, and a test_user. test_user is not an admin or staff account, and is not part of the manager group. The test_user account is an owner of project 2, but not project 1. But if I use the test_user credentials, I see both project 1 and 2: [ { "id": 1, "name": "Test Private Project", "slug": "test-private-project", "description": "Just testing the super private project", "group": { "name": "manager", "id": 1 }, "created_date": "2020-04-20T18:04:20.666564Z", "modified_date": "2020-04-20T18:04:20.666594Z", "owner": { "username": "admin", "full_name_display": "Administrator", "photo": null, … -
Why I cannot update my heroku app via gitlab CI
I have started messing around with Heroku docker and Django. I have followed the instructions of a tutorial and everything works great. My app is on Heroku, but I cannot update my App. According to the tutorial, when I push my new code to Gitlab the pipeline is run and it deploys the new code to my app in Heroku. Although the pipeline passes nothing changes on my Heroku app, what am I doing wrong? Here is my .gitlab-ci.yml: image: docker:stable services: - docker:dind variables: DOCKER_DRIVER: overlay2 HEROKU_APP_NAME: myapp HEROKU_REGISTRY_IMAGE: registry.heroku.com/${HEROKU_APP_NAME}/web stages: - build_and_deploy build_and_deploy: stage: build_and_deploy script: - apk add --no-cache curl - docker login -u _ -p $HEROKU_AUTH_TOKEN registry.heroku.com - docker pull $HEROKU_REGISTRY_IMAGE || true - docker build --cache-from $HEROKU_REGISTRY_IMAGE --tag $HEROKU_REGISTRY_IMAGE --file ./Dockerfile "." - docker push $HEROKU_REGISTRY_IMAGE - chmod +x ./release.sh And this is the release.sh #!/bin/sh IMAGE_ID=$(docker inspect ${HEROKU_REGISTRY_IMAGE} --format={{.Id}}) PAYLOAD='{"updates": [{"type": "web", "docker_image": "'"$IMAGE_ID"'"}]}' curl -n -X PATCH https://api.heroku.com/apps/"${HEROKU_APP_NAME}"/formation \ -d "${PAYLOAD}" \ -H "Content-Type: application/json" \ -H "Accept: application/vnd.heroku+json; version=3.docker-releases" \ -H "Authorization: Bearer ${HEROKU_AUTH_TOKEN}" Last but not least here are the last messages of the pipeline, as I think that the rest of them are irrelevant to my question. Successfully built dbd1d36dea04 … -
Initial value does not appears as selected value in my form?
I have a form and I want to set initial value does not appears as selected PAYS is a list like [(None, ''), (2, 'Ivory coast'), (1, 'France')] self.user_country = 1 I tought it was a problem of field format (charfield in my model) and try to manage with str() but it does not change forms.py class RandomizationEditForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): super(RandomizationEditForm, self).__init__(*args, **kwargs) self.user_country = request.session.get('user_country') self.language = request.session.get('language') self.user_site_type = request.session.get('user_site_type') PAYS = Pays.options_list(self.user_country,self.user_site_type,self.language) self.fields["pay_ide"] = forms.ChoiceField(label = "Patient's country code", widget=forms.Select, choices=PAYS, initial = self.user_country, disabled=True) self.fields["ran_dem_dat"] = forms.DateField( label = "Date of demand", initial = timezone.now(), required = True, ) self.fields['ran_dem_dat'].widget.attrs.update({ 'autocomplete': 'off' }) class Meta: model = Randomisation fields = ('pay_ide','ran_str_num','ran_bra','bra_lib','ran_act','pat','ran_nai','ran_sex','ran_st1','ran_st2','ran_bug','ran_dem_nom','ran_dem_dat',) models.py class Pays(SafeDeleteModel): """ A class to create a country site instance. """ _safedelete_policy = SOFT_DELETE_CASCADE pay_ide = models.AutoField("Code number", primary_key = True) pay_nom_eng = models.CharField("Nom", max_length = 150) pay_nom_fra = models.CharField("Nom", max_length = 150) pay_abr = models.CharField("Code lettre", max_length = 3) pay_ran = models.IntegerField("Randomization opened in the country? (y/n)",default=0, null=True, blank=True) log = HistoricalRecords() class Meta: db_table = 'adm_pay' verbose_name_plural = 'Pays' ordering = ['pay_nom_fra', 'pay_ide'] permissions = [ ('can_manage_randomization','Can activate randomization'), ] @classmethod def options_list(cls,pays,type,language): if type == 'International' or … -
django radio button on request.POST is not working
i am trying to read the value from the radio.input in the form below using def question_detail(request,question_id,quiz_id): q = Quiz.objects.get(pk = quiz_id) que = Question.objects.get(pk = question_id) count = q.question_set.count() try: selected_choice = que.answer_set.get(pk=request.POST['choice']) except(KeyError, Answer.DoesNotExist): come = que.rank came = come + 1 later_question = q.question_set.get(rank=came) return render(request, 'app/question_detail.html',{'que': que, 'count': count, 'later_question': later_question}) else: if selected_choice.correct is True: try: come = que.rank came = come + 1 later_question = q.question_set.get(rank=came) except: come = que.rank came = come later_question = q.question_set.get(rank=came) else: come = que.rank later_question = q.question_set.get(rank=come) return render(request, 'app/question_detail.html',{'count': count, 'que': que, 'later_question': later_question}) but when i try to access the webpage,it throws an Keyerror,please help <form action="{% url 'app:detail' quiz_id=que.quiz.id question_id=later_question.id%}" method="post">{% csrf_token%} {% for choice in que.answer_set.all %} <input type="radio" name='choice' value="{{choice.id}}"> <label>{{choice.answer}}-{{choice.correct}}-{{choice.rank}}</label><br> {% endfor %} -
How to unpack dictionary into models.TextChoices atributes in Django models?
Here is new option in Django 3.0 for choices in models by using ENUM library: https://docs.djangoproject.com/en/3.0/ref/models/fields/#enumeration-types I have been trying to use it to create countries choices for AbstractUser model: class User(AbstractUser): """ Custom user model based on AbstractUser model. """ class Countries_ISO3166(models.TextChoices): # This code should run when class is initialized. Instead of cls should be class object for country_code, country_name in countries.COUNTRIES_DICT.items(): setattr(cls, country_name, country_code) username = None email = models.EmailField(verbose_name='email address', unique=True) first_name = models.CharField(null=True, blank=False, max_length=30, verbose_name='first name') last_name = models.CharField(null=True, blank=False, max_length=150, verbose_name='last name') user_country = models.CharField(max_length=2, choices=Countries_ISO3166.choices, null=True, verbose_name='user country of origin') USERNAME_FIELD = 'email' # https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#django.contrib.auth.models.CustomUser.REQUIRED_FIELDS REQUIRED_FIELDS = [] #default_manager = BaseUserManager() objects = users_managers.CustomUserManager() class Meta: unique_together = ( ('first_name', 'last_name', ), ) index_together = unique_together verbose_name = 'user' verbose_name_plural = 'users' def __str__(self): return f'pk - {self.pk}, full name - {self.get_full_name()}, email - {self.email}' Problem is I dont know how to unpack countries dictionary in order to create Countries_ISO3166 class atributes like in Django documentation example. I have tried to do it in init, new but it doesn't work. COUNTRIES_DICT is a counties dict according ISO3166 format: COUNTRIES_DICT = { "AF": "Afghanistan", "AX": "Åland Islands", "AL": "Albania", "DZ": "Algeria", "AS": "American … -
Update foreign key related table field while inserting new record in first table django
I have two tables Table Tour class Tour(BaseModel): statuses = [ ('DRAFT', 'Draft'), ('ACTIVE', 'Active'), ('PAID', 'Paid'), ('COMPLETED', 'Completed') ] status = models.CharField(max_length= 100, choices=statuses, default="DRAFT") Table Billing class Billing(BaseModel): tour=models.ForeignKey(Tour, on_delete=models.PROTECT) total=models.FloatField(null=True) views.py class BillingViewSet(viewsets.ModelViewSet): queryset = Billing.objects.all() serializer_class=Billlingerializer serializers.py class Billlingerializer(serializers.ModelSerializer): class Meta: model = Billing fields ='__all__' whenever a new record is added to Billing table we need to change status to PAID in Tour table, I have other tables too, which is like Billing if any record is added there also need to change the status to complete or active etc.So we need common method that is defined in Tour model which can be called from serialiazers or views .Please help me, thanks in advance. -
Fetch rows field = true by BooleanFilter
I am making very simple booleanfilter I have model which has boolean column named 'is_show'. I want to fetch the items is_show is true. I accessAPI like this /api/items?is_show=true class Text(models.Model): is_show = models.BooleanField() class TextFilter(filters.FilterSet): is_show = filters.BooleanFilter(is_show=True) However it still returns all rows. -
Django HTML templates can't load CSS files
In my Django project I added a new 404 page, that gets called when I enter an invalid url. But, the CSS file is not loaded with page, so it appears mis-formatted. The browser gives me this error: "Refused to apply style from because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled." The point is, There are other CSS files in the 'static' folder that are loaded correctly without this error, like the bootstrap.css file... My settings.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1'] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] My urls.py urlpatterns = [ ... ] handler400 = 'utils.views.error_400' handler403 = 'utils.views.error_403' handler404 = 'utils.views.error_404' handler500 = 'utils.views.error_500' My utils.views.py def error_400(request, exception): data = {} return render(request, 'utils/mv_admin_400.html', data) def error_403(request, exception): data = {} return render(request, 'utils/mv_admin_403.html', data) def error_404(request, exception): data = {} return render(request, 'utils/mv_admin_404.html', data) def error_500(request): data = {} return render(request, 'utils/mv_admin_500.html', data) My 404.html {% load static %} <!DOCTYPE html> … -
Delete model objects involved in ManyToMany relationships in postgres
I am using postgres and have two very simple models in Django: class VariantTag(ModelWithGUID): saved_variants = models.ManyToManyField('SavedVariant') class SavedVariant(ModelWithGUID): xpos_start = models.BigIntegerField() xpos_end = models.BigIntegerField(null=True) Now, I want to delete SavedVariant but getting an error Key (id)=(24) is still referenced from table "seqr_varianttag_saved_variants". How to correctly delete SavedVariant objects in this case? In dbshell I mean, in postgres using SQL. -
Different time intervals creations
I have datetime objects for start_time and end_time. Both of these from user comes in 24 hours. for eg: 14:00hrs and 16:00hrs. I have an interval of 12 minutes per hour. dateTimeA = datetime.datetime.strptime(start_time, '%H:%M') dateTimeB = datetime.datetime.strptime(end_time, '%H:%M') I need to create slots in the following manner: Diff_in_time = dateTimeB - dateTimeA diff_in_hours = Diff_in_hours.total_seconds() / 3600 So, diff_in_hours gives me a time difference in hours. Here, diff_in_hours = 2.0 Now, the slots to be created should be. slots_interval = 60/12(interval) = 5 slots/hour with interval of 12 minutes. 14:00 - 14:12 14:12 - 14:24 14:24 - 14:36 14:36 - 14:48 14:48 - 15:00 15:00 - 15:12 15:12 - 15:24 15:24 - 15:36 15:36 - 15:48 15:48 - 16:00 Total slots = 10 However, I am unable to perform this operation. I need to keep a tally of both from_time and end_time here to create slots. Can anyone suggest some help? -
how to check whether user after login has submitted the form one , if yes again if he login he should redirect to form 2 not one again in django
I have an app where user login and after he logins he get redirect to dashboard where appears a form and user fill the form , once user fill the form he redirect to next page where it shows the progress of the form. So if user login again he should automatically redirect to the progress page he should not get the form page again if he has filled it . Can any one suggest me how to achieve these. views.py def create(request): if request.method == 'POST': post = AccountProfile() post.user = request.user post.name = request.POST['name'] post.email = request.POST['email'] post.mobile = request.POST['mobile'] post.date = request.POST['date'] post.sex = request.POST['sex'] post.save() return render (request,'posts/dashboard-post-a-job.html') These is the views where user get redirect after login and fill form.