Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elasticbeanstalk Django issues with ondeck vs current version
Using Elasticbeanstalk to deploy a Django application. Within the .ebextensions directory I've got the following (this is just a subset): commands: 00_pip_upgrade: command: /opt/python/run/venv/bin/pip install --upgrade pip leader_only: true 01_pip_install: command: /opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt leader_only: true container_commands: 111_collectstatic: command: "source /opt/python/run/venv/bin/activate && python /opt/python/ondeck/app/manage.py collectstatic --noinput" leader_only: true The issue is that anything with ondeck isn't found. I am having trouble finding AWS documentation regarding the transitions between bundle, ondeck, and current directories. When I ssh into the instances I don't see any directory at all for /opt/python/ondeck. Can someone help to explain if /opt/python/ondeck should still be used or what my issues may be? -
rest_framework_simplejwt post to an APIView
I have this settings: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } And this view: class Config(APIView): def get(self, request, *args, **kwargs): if 'config' in request.GET.dict(): if os.path.isfile(settings.CONFIG): yaml = read_config(settings.CONFIG) return Response(yaml) else: return Response({ "success": False, "error": "config file not found!"}) else: return Response({"success": False}) def post(self, request, *args, **kwargs): if 'data' in request.data: print(request.data['data']) return Response({"success": False}) With axios I manage my api calls, for example: axios.post('api/config/?config', { data: obj, headers: { Authorization: 'Bearer ' + rootState.auth.jwtToken } }) The problem is now, that I can not post data. I get an Unauthorized (401) error and in the response message it says: {"detail":"Authentication credentials were not provided."} Can you please tell me, what I'm missing here and how can I fix this issue? -
ReactJs: Passing a prop and using it within a map()
I'm trying to take a user inputted code and compare it to code within my database. Right now I can bring the code and display it outside the map function but when I try to add it, it doesn't work. here is my database: [ { "dwelling_code": "ABC-XYZ", "dwelling_name": "Neves Abode", "has_superAdmin": true, "room": [] } This is the parent component: class Dwel2 extends Component { state = { house: [], selectedMovie: null, data: "ABC-XYZ" } componentDidMount() { fetch('Removed for question', { method: 'GET', headers: { } }).then(resp => resp.json()) .then(resp => this.setState({ house: resp })) .catch(error => console.log(error)) } houseClicked = h => { console.log(h) } render() { return <div> <EnterCode dataFromParent={this.state.data} house={this.state.house} houseClicked={this.house} /> </div> } } This is the child component: function EnterCode(props) { return ( <div> <div> *THIS BIT DISPLAYS THE CODE*{props.dataFromParent} </div> {props.house.map(house => { var test = house.dwelling_name var code = house.dwelling_code if (code === {props.dataFromParent}) { test = "Test" } return ( <React.Fragment> <div>{test}</div> </React.Fragment> ) })} </div> ) } I just want to compare the code in the database to the code defined in the parent component -
Why Django does admin change page displays html instead of link after upgrading from Django 1.11 to 2.2?
I recently upgraded to Django 2.2 and now the HTML of my link is display instead of an actual link. Here is the code I suspect has changed in behavior: class RequestAdmin(admin.ModelAdmin): ordering = ('id', 'status', ) list_display = ('detail_link', 'status', 'requester', 'added', 'type', 'change_description', 'approve_or_deny') ... omitted for brevity ... # ID in list is rendered as link to open request details page def detail_link(self, obj): return '<a href="%s%s%s%s%s" target="_blank">%s</a>' % (('https://' if self.request.is_secure() else 'http://'), self.request.META['HTTP_HOST'], (settings.GUI_ROOT if settings.GUI_ROOT != '/' else ''), '/#/requests/', obj.id, obj.id) Before this would render a link. But now if renders this text instead: <a href="http://app-dev-001.example.com:5200/gui/#/requests/1" target="_blank">1</a> -
Sharing a database on 2 Django projects
I made a webapp on django and it's working great. However, I got feedback that my userbase prefers an app over visiting a website. This is completely understandable and I started researching in how to develop one for both android and iphone phones. I came across flutter and got to work. My flutter frontend has to communicate with an api which communicates to the same database as my webapp. So I installed djangorestframework and got it to work. The problem here is that I want to use token authentication for my app and basic authentication for my website. Since you can't have both [:(] I started the api as an extra project. Project 1 has the web application, built on Django. Project 2 is the rest API for my mobile phone apps. Now comes the great question, how do I make them share one database? -
django-encrypted-filefield with cloud storage
I'm new to this and can't find any resources, except this which does not provide a final answer and the orignal demo which only does things locally. I have a django-encrypted-filefield in a model, and a method to get the url: class Item(models.Model): file = EncryptedFileField(upload_to="files/") def get_url(self): return self.file.url This then pushes to an S3 bucket, say https://bucket.org/assests/. As mentioned in the docs, urls contains the line: url(r"^fetch/(?P<path>.+)", MyFetchView.as_view(), name=FETCH_URL_NAME), and the required environment variables are present. In the docs, when attempting to get the local url, we could simply access: {{ object.get_url }} And from that url we could download a non-encrypted version. However, in the bucket case, accessing in that way will return something resembling fetch/https://bucket.org/assets/files/item.txt, which is not a valid url. I know I am probably missing something very simple, but I can't remove the fetch because that would catch all urls. I don't know how to write a view that solves this either. Please could someone advise me or link me to a tutorial that helps with this. Thanks, Joshua. -
NoReverseMatch at /post/31/
I am new to django and creating a blog of which while using class-based views, my post detail was displaying properly. I decided to use function-based views and I am coming up with this error. Please help. This is my views.py file # class PostDetailView(DetailView): # model = Post # template_name = 'ecommerce/post_detail.html' # def get_context_data(self, *arg, **kwargs): # context = super().get_context_data(**kwargs) # form = CommentForm() # context['form'] = form # Your comment form # return context def post_detail(request, pk): post = get_object_or_404(Post, pk = pk) is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True context ={ 'post':post, 'is_liked':is_liked, } return render(request, 'ecommerce/post_detail.html', context) My urls.py path('post/<int:pk>/', views.post_detail, name='post-detail'), My post_detail.html {% extends "ecommerce/base.html" %} {% load crispy_forms_tags %} {% block content %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted|date:"F d, Y"}}</small> {% if object.author == user %} <div> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a> </div> {% endif %} </div> <h2 class="article-title">{{ object.title }}</h2> <p class="article-content">{{ object.content }}</p> </div> <form action="{% url 'like_post' %}" method="POST"> {% csrf_token … -
django add to model from model have foreign key to this model from admin
models.py from django.db import models # Create your models here. class Client(models.Model): name = models.CharField(max_length=100, blank=True, null=True) email = models.EmailField(max_length=150, blank=True, null=True) class ClientNum(models.Model): number = models.CharField(max_length=20, blank=True, null=True) client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) class Ad(models.Model): num = models.CharField(max_length=20, blank=True, null=True) client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) i want to be able to add client from Ad model from django admin as i able to add number to client from client model i'm able to add user from Ad model in django admin but it opens new window i want to be in same window Acmin.py from django.contrib import admin # Register your models here. from .models import ClientNum, Client, Ad class ClinetNumAdmin(admin.TabularInline): model = ClientNum extra = 1 class ClinetNumRel(admin.ModelAdmin): inlines = [ClinetNumAdmin] class ClinetAdmin(admin.TabularInline): model = Client extra = 1 admin.site.register(ClientNum) admin.site.register(Client, ClinetNumRel) admin.site.register(Ad) -
how ajax work in Django getting id for new page this problem
$(document).on("click", "#transactRequest", function() { var request_no = $("#request_no").val(); $.ajax({ url: "{% url 'bond_fund:create-transaction/' request_no%}", method: "GET", success: function(data) {}, }); }); url path('create-transaction/', create_transaction), -
Serving two websites on one VPS
I am trying to serve two Django sites on one VPS (Digital Ocean) using Nginx and Gunicorn. I have an application called life-cal. When I type www.thelifecal.com into my browser address bar, I get exactly the response I am looking for and the Django app is served. However, when I just type thelifecal.com (no www.) I get the "Welcome to Nginx" page displayed. I used the following two tutorials to set up my server: https://gist.github.com/bradtraversy/cfa565b879ff1458dba08f423cb01d71#copy-this-code-paste-it-in-and-save https://medium.com/@caterinadmitrieva/serving-multiple-django-apps-on-second-level-domains-with-gunicorn-and-nginx-a4a14804174c /etc/nginx/sites-enabled/life-cal server { listen 80; server_name 167.71.116.21 thelifecal.com www.thelifecal.com; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/keegadmin/pyapps/life_cal; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/run/life-cal.sock; } } And a screenshot form namecheap: -
How to use for loop
I'am making movie website in django and I want to order my list of all movies from database .So I have found this second card with image on https://materializecss.com/cards.html but I really don't know how to use {% for %} {% endfor %} so I could have descriptions ,name of movie and image(poster) of movies in database.Can someone here could help me ? -
Django Rest Filterset - how to filter by nested serializer?
Good evening colleagues! I have the following code: serializators.py class CoinCostsSerializer(serializers.ModelSerializer): class Meta: fields = ('price', 'timestamp',) model = CoinCosts class CoinSerializer(serializers.ModelSerializer): class Meta: fields = ('symbol', 'crr', 'costs') model = Coins costs = CoinCostsSerializer(source='coincosts_set.all', many=True) views.py class CoinCostFilterSet(filters.FilterSet): class Meta: model = Coins fields = { 'symbol': ['exact'], } class CoinCostViewSet(viewsets.ModelViewSet): queryset = Coins.objects.all() serializer_class = CoinSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = CoinCostFilterSet And by typing the address /CoinCost/?symbol=ZERO for example, I have filtering from Django on this coin. So i need this url: /CoinCost/?symbol=ZERO&timestamp_start=2019-12-14T00:00:00&timestamp_end=2019-12-17T00:00:00 get filtering not only by Zero coin but also by Timestamp. Can you help? What should my code look like for this task? How do I filter by the embedded serializer as well? Thanks for the help! Have a good weekend! -
Django Ajax request gets stuck after pressing "submit"
I am using AJAX to create a blog post object from the website, however, after pressing submit chrome freezes and the modal doesn't hide. I can see in the terminal the view is being called but my chrome freezes and I have to close the tab and then enter the website again. I have also tried using Safari but it happens there as well, I havent changed anything in my code I do not know why this is appening. My view for creating a post: @login_required def post_create(request): data = dict() if request.method == 'POST': image_form = ImageForm(request.POST or None, request.FILES or None) form = PostForm(request.POST) if form.is_valid() and image_form.is_valid(): post = form.save(False) post.author = request.user post.save() images = request.FILES.getlist('image') for i in images: image_instance = Images(file=i,post=post) image_instance.save() data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: image_form = ImageForm form = PostForm context = { 'form':form, 'image_form':image_form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) my javascript for handling Ajax: $(document).ready(function(){ $(document).ajaxSend(function (event, jqxhr, settings) { jqxhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); }); var ShowForm = function(e){ e.stopImmediatePropagation(); var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-post').modal('show'); }, success: function(data){ $('#modal-post … -
Axios Authorization not working - VueJS + Django
I am trying to build an application using VueJS and Django. I am also using Graphene-Django library, as the project utilize GraphQL. Now, The authentication works fine and i get a JWT Token back. But when i use the token for other queries that need authentication, i got this error in Vue: "Error decoding signature" and the Django Log also returns this: graphql.error.located_error.GraphQLLocatedError: Error decoding signature jwt.exceptions.DecodeError: Not enough segments ValueError: not enough values to unpack (expected 2, got 1) the bizarre thing is that the same query when executed in Postman just works fine. As i mentioned in the title is use Axios for my requests, here's an example of a request: axios({ method: "POST", headers: { Authorization: "JWT " + localStorage.getItem("token") }, data: { query: `{ dailyAppoint (today: "${today}") { id dateTime } }` } }); Note: It uses 'JWT' not 'Bearer' because somehow 'Bearer' didn't work for me. -
AJAX post-ing of python dictionary leads to JSONDecodeError
I am passing a python dictionary to a template then $.post-ing it to a view in django, and when I try to json.loads it in my post view, I get JSONDecodeError. Anyone know how I can fix this? //1. vars to templates @login_required def bracket(request): ''' :param request: :return: ''' ... context = {'arr':json.dumps(tournament_games_json_serializable), 'nested':nested_tournament_games['rounds']}#{'latest_question_list': latest_question_list} return render(request, 'madness/bracket.html', context) //2. AJAX post of template var $.post('{% url "update_bracket" %}', { bracketData: "{{arr}}" }, function(data, status, xhr) { console.log(JSON.stringify(data)); var nested = JSON.stringify(data); }).done(function() { }) .fail(function(jqxhr, settings, ex) { alert('failed, ' + ex); }); //3. update_bracket @csrf_exempt def update_bracket(request): bracketData = request.POST['bracketData'] print(json.loads(bracketData)) ... where tournament_games_json_serializable is tournament_games_json_serializable {'round_1_game_1': {'players': (2, 3), 'winner': None, 'loser': None, 'done': False}, 'round_2_game_1': {'players': (1, 'winner of Round 1 Game 1'), 'winner': None, 'loser': None, 'done': False}} request.POST['bracketData'] '{&quot;round_1_game_1&quot;: {&quot;players&quot;: [2, 3]... json.loads(bracketData) json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 -
Initiate new instance from UpdateView
I am making an app to create repair work orders which also has an inventory app in it. I create and edit repair work orders using class-based views. I have a model for work orders; class Order(models.Model): """Maintenance work orders""" ... parts = models.ManyToManyField(UsedPart, blank=True) model for parts inventory class Part(models.Model): """List of company equipment""" partnum = models.CharField(max_length=20) amount_in_stock = models.PositiveIntegerField() price = models.FloatField(blank=True, null=True) vendr = models.ManyToManyField('Vendor', blank=True) ... And a model for instances of used parts class UsedPart(models.Model): """List of company equipment""" part = models.ForeignKey(Part, on_delete=models.CASCADE) amount_used = models.PositiveIntegerField() The way i wanted to implement it was. I create a UpdateView for an order. Check the parts i need in a m2m form and on submit create instances of this parts with associated amount. But i can't figure out how to initiate the instances from request. i wrote this, but id doesn't work class AddPartView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Order form_class = AddPartForm template_name_suffix = '_add_part' def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update(request=self.request) return kwargs def post(self, request, **kwargs): UsedPart.__init__(self) request.POST = request.POST.copy() request.POST['parts'] = request.POST.get('parts') return super(SomeUpdateView, self).post(request, **kwargs) form class AddPartForm(forms.ModelForm): class Meta: model = Order fields = ['parts', ] labels = {'parts': "", } def filter_list(self, … -
how to show list view in my urls based on string not integer in django
this is my model where I have people class where every person in this people class lives in a zone this is my people class and zone class class Zones(models.Model): zone_name = models.CharField(max_length=120) def __str__(self): return self.zone_name class People(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) address = models.TextField() phone_number = models.CharField(max_length=12) national_number = models.CharField(max_length=14) no_of_members = models.PositiveIntegerField(null=False, blank=False) zone = models.ForeignKey(Zones, null=False, blank=False, on_delete=models.CASCADE) def __str__(self): return self.first_name and how I want to show them the in the route /zone will be list of my zones, and when the user click on any of those zone I want him to see list of people who are in this zone here is my views class PeopleView(ListView): model = People template_name = "people.html" context_object_name = 'people_list' class ZoneView(ListView): model = Zones template_name = "zones.html" context_object_name = 'zones_list' class PeopleDetailView(DetailView): model = People template_name = "people_detail.html" and here is my urls urlpatterns = [ path('admin/', admin.site.urls), path('people/', PeopleView.as_view(), name='people'), path('zone/', ZoneView.as_view(), name='zone'), path('zone/<int:pk>/', PeopleDetailView.as_view(), name='detail'), ] and here is my html template for zone <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Zones List</title> </head> <body> <h1>Zones List</h1> <ul> {% for zone in zones_list %} <a href="#"><li>{{ zone }}</li></a> {% endfor %} </ul> </body> </html> -
Implementing MVC pattern with Django Rest Framework
I was wondering how could I implement a MVC pattern on a Django Api project, when I start a django project it gives me the apps.py, admin.py, models.py and the views.py , I understand the the models, should be the "M", and the views the "V", but as i'm using the project like an api, the view would be an Angular or React App, so where I put the logical ? Where is the right place to put the "C" controller on a django rest framework project, is it on views.py ? -
Select one field from a filter in Django
I have a quick question: How can I select only one field from my filter form in Django? I'm currently displaying the whole thing: <div class="container"> <form method="GET" > {{ filter.form.Precio|crispy }} <button class="btn btn-primary" type="submit">Aplicar filtros</button> </form> </div> I'd like to separe the filter form. I used to do this: {{ form.username }} but it doesn't seem to work... EDIT: This is filters.py class PubFilters(django_filters.FilterSet): Precio = django_filters.NumericRangeFilter() o = django_filters.OrderingFilter( choices=( ('-Más nuevo', 'Más nuevo'), ('Más nuevo', 'Menos nuevo') ), fields={ 'Fecha': 'Más nuevo', } ) class Meta: model = publicaciones fields = ['Título', 'Precio', 'Categoría'] fields ={ 'Título': ['icontains'], } -
How to respond with child object based on its parent id?
I have a parent class and a child class, like so: class Animal(models.Model): age = models.IntegerField() class Bird(Animal) wingSpan = models.DecimalField() Here's the view to get birds: class BirdViewSet(viewsets.ModelViewSet): queryset = Bird.objects.all() serializer_class = BirdSerializer And here is the serializer: class BirdSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Bird fields = ['age', 'wingSpan'] In the database, jango appropriately created an animal_prt_id field in the birds table, so that this view/serializer pair knows where to find the age, which is mapped to the parent class, Animal. How to make a view/serializer pair that does the opposite, meaning, it receives the id of an Animal and responds with the complete Bird (or with any other Animal subclass I might have)? -
DRF Update cross-table data
In my project I have Job, Skill and JobSkills models: class Job(models.Model): name = models.CharField( max_length=127, verbose_name=_('Job name'), ) description = models.TextField( verbose_name=_('Job description'), ) class Skill(models.Model): name = models.CharField( max_length=63, verbose_name=_('Skill name'), ) class JobSkills(models.Model): class Meta: verbose_name = 'Job skill' verbose_name_plural = 'Job Skills' unique_together = ['job', 'skill'], job = models.ForeignKey( Job, on_delete=models.CASCADE, related_name='job_skills', null=True, ) skill = models.ForeignKey( Skill, on_delete=models.CASCADE, related_name='job_skills', null=True, ) # generate list of lists of number from 1 to 10 like ((0, 0), (1, 1), ... (10,10)) SKILL_LEVEL = [(i, i) for i in range(1, 11)] level = models.IntegerField( choices=SKILL_LEVEL ) One job has many skills with skill level. User can add skills to job from default list and can not create new skill example data: PUT /api/jobs/1 { "name": "Job", "description": "Job description", "job_skills": [ { "id": 1, # job_skill_id "skill": { "id": 4, # skill_id }, "level": 7 } ], } class JobViewSerializer(serializers.ModelSerializer): job_skills = JobSkillsSerializer(many=True) def update(self, instance, validated_data) -> Job: job_skills = validated_data.get('job_skills') instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.save() But how to write the right logic for update Job skills? I need add new relation between Job and Skill if it doesn't exist, change Job skill … -
Database Management on Django and Github
I am trying to set up a website using the Django Framework. Because of it's convenience, I had choosen SQLite as my database since the start of my project. It's very easy to use and I was very happy with this solution. Being a new developer, I am quite new to Github and database management. Since SQLite databases are located in a single file, I was able to push my updates on Github until that .db file reached a critical size larger than 100MB. Since then, it seems my file is too large to push on my repository (for others having the same problem I found satisfying answers here: GIT: Unable to delete file from repo). Because of this problem, I am now considering an alternative solution: Since my website will require users too interact with my database (they are expected post a certain amount data), I am thinking about switching SQLite for MySQL. I was told MySQL will handle better the user inputs and will scale more easily (I dare to expect a large volume of users). This is the first part of my question. Is switching to MySQL after having used SQLite for a while a good idea/good … -
Attribute error : 'WSGIRequest' object has no attribute 'get'
I've been working on a project lately and got the above error. It says " Error during template rendering".I have a similar model, which works perfectly fine. I've looked for similar errors but got none matching my situation. I don't know where I went wrong. It would be great if I get helpful answers. Models.py class ServiceTax(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="service_tax",null=True,blank=True) name=models.CharField(max_length=100) percent=models.FloatField(default='0') add_amount=models.IntegerField(default='0') def __str__(self): return self.name Forms.py class ServiceTaxForm(forms.ModelForm): class Meta: model = ServiceTax fields = "__all__" widgets = { 'name' : forms.TextInput(attrs={'class': 'form-control'}), 'percent' : forms.NumberInput(attrs={'class': 'form-control','step':'0.01'}), 'add_amount' : forms.NumberInput(attrs={'class':'form-control','maxlength':5}), } labels={ 'add_amount': "Additional Amount" } Views.py def tax_form(request,id=0): if request.method == 'GET': if id == 0: form = ServiceTaxForm(request) else: tax = ServiceTax.objects.get(pk=id) if tax in request.user.service_tax.all(): form = ServiceTaxForm(request,instance=tax) else: return redirect('/revenue/tax') return render(request,'tax-form.html',{'form':form}) else: if id==0: form = ServiceTaxForm(request,request.POST) if form.is_valid(): name = form.cleaned_data["name"] percent = form.cleaned_data["percent"] add_amount = form.cleaned_data["add_amount"] t = AnnualTax( name=name, percent=percent, add_amount=add_amount, ) t.save() request.user.service_tax.add(t) else: tax = ServiceTax.objects.get(pk=id) if tax in request.user.service_tax.all(): form = ServiceTaxForm(request,request.POST,instance=tax) if form.is_valid(): name = form.cleaned_data["name"] percent = form.cleaned_data["percent"] add_amount = form.cleaned_data["add_amount"] tax_obj = ServiceTax.objects.get(pk=id) tax_obj.name = name tax_obj.percent = percent tax_obj.add_amount = add_amount tax_obj.save() return redirect('/revenue/tax') tax-form.html {% extends 'base.html' %} {% load crispy_forms_tags %} … -
Django Rest API Url Pattern to handle . (dot) symbol
Creating Django REST API, Need suggestions to handle the .(dot char) in the urlpatterns. Below is the example detail: I have a Model (test) with name as one of the fields and name value is of format ABC.XYZ Below URL pattern does not work when name = ABC.XYZ url(r'^tests/(?P<string>[\w\-]+)/$', views.tests.as_view(), name='api_tests_name') -
Django3: Dynamic queryset function allocation performance
i am just experimenting on how to 'dynamically allocate queryset functions' and i would like to know the performance issues i might face later on. My querysets are working perfectly but i am a little skeptical about them. Please have a look at my code: settings.py: ... TODO_PRIORITY = ( ('LOW', 'Low'), ('MEDIUM', 'Medium'), ('HIGH', 'High'), ) ... models.py from django.db import models from django.contrib.auth import get_user_model from django.utils import timezone from .manager import TodoManager from django.conf import settings User = get_user_model() TODO_PRIORITY = getattr(settings, 'TODO_PRIORITY', None) assert TODO_PRIORITY is not None, "Your settings file is missing `TODO_PRIORITY` variable" assert isinstance(TODO_PRIORITY, tuple), "`TODO_PRIORITY` must be a tuple" # Create your models here. class Todo(models.Model): class Meta: ordering = ('start_time',) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todos") content = models.TextField(max_length=500, blank=False) start_time = models.DateTimeField(default=timezone.now) end_time = models.DateTimeField(blank=False) priority = models.CharField(max_length=6, choices=TODO_PRIORITY, default="MEDIUM") timestamp = models.DateTimeField(auto_now_add=True) objects = TodoManager() @property def todo_id(self): return self.id manager.py from django.db import models from django.utils import timezone from django.conf import settings now = timezone.now() today = now.replace(hour=0, minute=0, second=0, microsecond=0) tomorrow = today + timezone.timedelta(days=1) TODO_PRIORITY = getattr(settings, 'TODO_PRIORITY', None) assert TODO_PRIORITY is not None, "Your settings file is missing `TODO_PRIORITY` variable." assert isinstance(TODO_PRIORITY, tuple), "`TODO_PRIORITY` must be …