Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Vacate unique name if field is a particular value
What I want I want a field to be unique unless a other field in a the same model is a particular value. Allowing me to vacate this unique name to a future model instance. I also need to allow testname to be null encase there is no testname for that given test. Unique Field: testname Conditioner: cancelled=True models.py (Simplified) class Test(models.Model): testname = models.CharField(max_length=50, null=True, blank=True, unique=True) cancelled = models.BooleanField(default=False) -
Aggregate annotated field from Subquery in Django
I'm trying to implement a subquery with Django ORM, but I can't find a working solution. The SQL query that I would need to reverse-engineer is: select t1.location, sum(t1.value_relative::numeric) as total from ( select administrative_division_id as "location", jsonb_array_elements("values"->'loss'->'values')->>'dim_value' as dim_value, jsonb_array_elements("values"->'loss'->'values')->>'value_relative' as value_relative from assessments_entrybaserisk where "values"->'scenario'->>'value' = 'Total' ) t1 where t1.dim_value::numeric = 2 group by t1.location I tried to use Django Subquery like below: subq = EntryBaseRisk.objects \ .filter(id=OuterRef('pk'), values__scenario__value='Total') \ .annotate( _dim_value=Cast( KeyTextTransform('dim_value', JsonbArrayElements(KeyTransform('values', KeyTransform('loss', 'values')))), IntegerField()), _value_relative=Cast( KeyTextTransform('value_relative', JsonbArrayElements(KeyTransform('values', KeyTransform('loss', 'values')))), FloatField())) \ .values('assessment', 'administrative_division', '_dim_value', '_value_relative') data = EntryBaseRisk.objects \ .annotate( dim_value=Subquery(subq.values('_dim_value'), output_field=IntegerField()), total_relative_value=Sum(Subquery(subq.values('_value_relative'), output_field=FloatField()))) \ .filter(**filters) \ .values('administrative_division', 'total_relative_value') \ .order_by('administrative_division') but I get an error ProgrammingError: more than one row returned by a subquery used as an expression. The problem is that SQL generated by Django is different from my SQL above, because it doesn't select from a select and it works only if the subquery is returning only one row. I can't perform the Sum aggregation in the subquery, because aggregate function calls cannot contain set-returning function calls. Is there another way to make Django generate an SQL as per my needs? -
Using code from views.py in javascript of html in django
I am working on payment integration for my django website and in my views.py I have a function which checks whether the transaction was successful or not and I want to use that condition in my javascript so that I can save the details(shipping) that the user entered in the form if his transaction was successfully completed. This is my views.py for checking if trans. was successful or not: @csrf_exempt def handlerequest(request): # paytm will send you post request here form = request.POST response_dict = {} for i in form.keys(): response_dict[i] = form[i] if i == 'CHECKSUMHASH': checksum = form[i] verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': print('order successful') else: print('order was not successful because' + response_dict['RESPMSG']) return render(request, 'paymentstatus.html', {'response': response_dict}) and this is my javascript which automatically submits the details entered by the user when he clicks the payment button: document.getElementById('payment-info').addEventListener('click', function (e) { submitFormData() }) function submitFormData() { console.log('Payment Button Clicked') var userFormData = { 'name': null, } var shippingInfo = { 'address': null, } shippingInfo.address = form.address.value userFormData.name=form.name.value var url = "/process_order/" fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'form': userFormData, 'shipping': shippingInfo }), }) .then((response) => response.json()) … -
Create check constraint based on custom SQL and custom Django fucntion
Question is regarding usage of custom function in check constraint: I have a following model: class UserIP(models.Model): user = models.ForeignKey( to=User, on_delete=models.CASCADE, related_name='user_ip', ) ip = models.GenericIPAddressField( verbose_name='User ip address' ) sample_time = models.DateTimeField( auto_now=True, verbose_name='User ip sample time' ) and I have following custom function in database: create or replace function count_ips(v_ip inet , v_user_id int, v_limit int) returns boolean as $$ select count(*) > v_limit from users_userip where ip = v_ip and user_id = v_user_id $$ language sql; which returns True if there are more then X (meant to be 3) entries in DB with same ip and user. Based on this function I created Django function like this: class IpCount(Func): function = 'count_ips' arity = 3 output_field = BooleanField() usage example: UserIP.objects.all().annotate(ann=IpCount(Value('127.0.0.1'), 1,3)).first().ann works perfect Now I want to make a check constraint that would not allow to save in DB any new entry if there are already 3 or more entries in DB where user and ip are the same. constraints = [ models.CheckConstraint( name='max_3_ips', check=~models.Q(IpCount('ip', 'user_id', 3)), ), ] It says then since Django > 3.1. it supports boolean expressions inside chekc constraints but what I have written it does not work. Error is like … -
AttributeError at /apiv2/api/processorder/order/
I am trying to post multiple data into my DataBase Using Django Rest framework (DRF). AttributeError at /apiv2/api/processorder/order/ Got AttributeError when attempting to get a value for field subcategory on serializer MyProcessOrderSerializer. The serializer field might be named incorrectly and not match any attribute or key on the list instance. Original exception text was: 'list' object has no attribute 'subcategory'. models.py class SubCategory(models.Model): category = models.ForeignKey(Category, related_name='subcategory', on_delete=models.CASCADE) name = models.CharField("Food Name", max_length=50, help_text="Name of The Food") price = models.DecimalField("Food Price", max_digits=5, decimal_places=2) quantity = models.PositiveIntegerField("Qty.", help_text="Quantity of the food Item you want") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.name}' class Meta: verbose_name = 'SubCategory' verbose_name_plural = 'SubCategories' class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) bike = models.ForeignKey(User, related_name='bike', on_delete=models.CASCADE, blank=True, null=True) package = models.ForeignKey(PackageType, related_name='package', on_delete=models.CASCADE, blank=True, null=True) total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0000.0) qty = models.PositiveIntegerField(default=1) shipping_address = models.CharField("Delivery Address", max_length=150) paid = models.BooleanField(default=False) ordernote = models.TextField("Order Notes", null=True) shipped = models.BooleanField(default=False) complete = models.BooleanField(default=False) received = models.BooleanField(default=False) refund_requested = models.BooleanField(default=False) refund_granted = models.BooleanField(default=False) ref_code = models.CharField(max_length=20, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created_at',) def __str__(self): return '{}'.format(self.id) def order(self): if not hasattr(self, '_order'): self._order = self.order.all() return self._order ''' def … -
chart js not dispalying data array that comes from an axios request
I have an API end point that returns an array of 24 values that I want to use in my chartjs within a vue component. when the page loads I get no errors but the bars on the charts just don't show and I don't know why. here is the data return code, I have a function that populates the chart_data array : data(){ return { form:{ day: 'select day', workspace:'', machine_family: [], duration: [] }, res: [], total:[], chart_data: [], url: '/api/jobs/job_count_by_hour/', days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "sunday"], barChart2: { labels: ["6h", "7h", "8h", "9h","10h","11h", "12h", "13h", "14h", "15h", "16h", "17h", "18h", "19h", "20h", "21h","22h", "23h", "00h"], datasets: [{ label: ["popularity"], backgroundColor:"#f93232" , data: this.chart_data },], }, } }, methods: { async filterData() { let _url = `${this.url}` await this.$axios.get(_url) .then(response => { this.chart_data = response.data; }) return this.chart_data }, }, mounted() { this.filterData() } } -
Django: How to display context data from one template on multiple templates
I have to use the context update method in every view in order to show data from my sidebar.html template that I include in other templates as part of my navigation. Is there another way in which I can include the data from my sidebar.html other templates as well? I'm going to have to do this for a lot of templates and does not seem like the right way to do it. blog/views.py class BlogPostDetailView(DetailView): model = BlogPost context_object_name = "post" template_name = "blog/single.html" def get_context_data(self, **kwargs): context = super(BlogPostDetailView, self).get_context_data(**kwargs) context.update( { "categories": Category.objects.all().annotate( post_count=Count("categories") ) }, ) return context Core/views.py class HomeView(ListView): model = BlogPost context_object_name = "posts" template_name = "core/index.html" paginate_by = 4 ordering = ["-date_posted"] def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context.update( { "categories": Category.objects.all().annotate( post_count=Count("categories") ) }, ) return context core/includes/sidebar.html ... <div class="sidebar-box ftco-animate"> <h3 class="sidebar-heading">Categories</h3> <ul class="categories"> {% for category in categories %} <li><a href="#">{{ category.title }} <span>({{ category.post_count }})</span></a></li> {% endfor %} </ul> </div> ... -
Filter Articles in all Subcategories
I have this model: class Category(models.Model): ID = models.AutoField(primary_key=True) Name = models.CharField('Name', max_length=200) metaTitle = models.CharField('metaTitle', max_length=200, null=True, blank=True) metaDescription = models.TextField('metaDescription', max_length=200, null=True, blank=True) metaKeyword = models.CharField('metaKeywords', max_length=200, null=True, blank=True) IsActive = models.BooleanField(default = False) Parent = models.ForeignKey('self',on_delete=models.SET_NULL,blank=True,null=True) URL = models.SlugField(null=False, unique=True) UserID = models.ForeignKey('Stamdata', on_delete=models.CASCADE) And I have Articles class Artikel(models.Model): ID = models.AutoField(primary_key=True) Varenavn = models.CharField('Varenavn', max_length=128) UserID = models.ForeignKey('Stamdata', on_delete=models.CASCADE) Varetekst = FroalaField() Varekode = models.IntegerField('Varekode') EAN = models.IntegerField('EAN', null=True, blank=True) IsActive = models.BooleanField(default = False) Leverandoer = models.ForeignKey('Leverandor', on_delete=models.DO_NOTHING) SalgsPris = models.DecimalField('SalgsPris', max_digits=10, decimal_places=2) IndkoebsPris = models.DecimalField('IndkoebsPris', max_digits=10, decimal_places=2, null=True) IsInStock = models.BooleanField(default = False) IsStockArtikel = models.BooleanField(default = False) Stocklevel = models.IntegerField('Stocklevel', null=True) Tax = models.ForeignKey('Moms', on_delete=models.DO_NOTHING) metaTitle = models.CharField('metaTitle', max_length=200) metaDescription = models.TextField('metaDescription', max_length=200) metaKeyword = models.CharField('metaKeywords', max_length=200) Vaegt = models.DecimalField('Vaegt', decimal_places=2, max_digits=10) Category = models.ForeignKey('Kategorier', on_delete=models.DO_NOTHING) DateAdded = models.DateField() Slug = models.SlugField(null=False) I have a category view and its work if I go throw the category and the articles appears, but now I have URL where I want to see all articles in all subcategories and I did find out how I write the view or I make the query in the template. First my Idea was that I get an list … -
My Django web page is not rendering models. How can i fix it?
I was learning Django but I got in some trouble, Please Help! There is no error on either server or webpage. My HomePage(index.html) is working fine but DetailPage(post.html) is rendering blank. blog/views.py from .models import Article from django.views import generic class HomePage(generic.ListView): template_name = 'blog/index.html' queryset = Article.objects.filter().order_by('date') context_object_name = 'Article_list' class DetailPage(generic.DetailView): template_name = 'blog/post.html' model = Article blog/urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.HomePage.as_view(), name='home'), path('<int:pk>/', views.DetailPage.as_view(), name='detail') ] blog/models.py from django.db import models class Article(models.Model): title = models.CharField(max_length=200) body = models.TextField() slug = models.SlugField(max_length=200, unique=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def snippet(self): return self.body[:200] blog/templates/blog/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body style="margin:10%"> {% for Article in Article_list %} <h1 align="center" style="padding-bottom:20px"> <a href="{% url 'blog:detail' Article.id%}">{{Article.title}}</a> </h1> {{Article.date}}<br><br> {{Article.snippet}}...<br><hr> {% endfor %} </body> </html> blog/templates/blog/post.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <h1>{{Article.body}}</h1> {{Article.body}}<br> {{Article.body}} </body> </html> NOTE: other elements of the webpage are rendering except Python variables i.e, {{Article.body}}, {{Article.body}}, {{Article.body}} -
Form is being not created in Django and yet no errors are returned
I am trying to create a profile update page for applicant, but the profile html page is only displaying username and email and not other attributes, plus the all the forms I'm creating are not showing in the html page on debugging but the system is not showing any existence of any errors. what could be the problem views.py @login_required def applicant(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) a_form = ApplicantUpdateForm(request.POST, request.FILES, instance=request.user.applicant) if u_form.is_valid() and a_form.is_valid(): u_form.save() a_form.save() messages.success(request, f'Your account has been updated!') return redirect('account') else: u_form = UserUpdateForm(instance=request.user) a_form = ApplicantUpdateForm(instance=request.user.applicant) context = { 'u_form': u_form, 'a_form': a_form } return render(request, 'users/account_settings.html', context) forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email'] class ApplicantUpdateForm(forms.ModelForm): class Meta: model = Applicant fields = ['mobilephone', 'maddress', 'country', 'homecity', 'citizenship', 'denomination', 'anyspouse', profile model class Applicant(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) mobilephone = models.CharField(max_length=13) maddress = models.TextField() homecity = models.CharField(max_length=20) citizenship = models.CharField(max_length=100) country = models.CharField(max_length=100) denomination = models.CharField(max_length=20) anyspouse = models.BooleanField(default=False) img = models.ImageField(default='default.jpg', upload_to='media') def __str__(self): return f'{self.user.username} Applicant' Here is how the page appears, that's the only thing i see -
How to add radio button in Boolean field in django
I have a Custom user model. When I go to signup form when I select the checkbox select these their boolean field. I want to restrict in the Boolean field in which the user can select only one Boolean field in signup form. I want to add a radio button in Boolean fields. Is there is a way to add a radio button in the boolean field? Forms.py class SignupForm(forms.ModelForm): class Meta: model = User fields = [ "name", "username", "email", "password", 'is_superuser', 'is_Customer', 'is_Service_Provider' ] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'username': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.TextInput(attrs={'class': 'form-control'}), 'password': forms.TextInput(attrs={'class': 'form-control'}), 'is_superuser' : forms.CheckboxInput('input_type' == 'radio'), 'is_Service_Provider' :forms.CheckboxInput('input_type' == 'radio'), 'is_Customer' : forms.RadioSelect(), } *** Models.py*** class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True) email = models.EmailField(max_length=254, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_Customer = models.BooleanField(default=True) is_Service_Provider = models.BooleanField(default=False) phone_regex = RegexValidator( regex = r'^\+?1?\d{9,10}$', message = "Phone number must be in the form of =919999999999") phone = models.CharField('Phone', validators = [phone_regex], max_length=254, unique=True, null=True, blank=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % self.pk def get_username(self): … -
How to update with multiple images in django rest framework, its not getting saved here
I am a beginner with django rest framework, I have this code to update a post with multiple images, but the update after uploading multiple images is not getting saved. While creating the post I was able to make the multiple upload part work fine. How can I change this code to make it work? Thank you! serializer class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ['id', 'images',] class PostUpdateSerializer(serializers.ModelSerializer): images = serializers.ListField(child=serializers.ImageField(allow_empty_file=True)) class Meta: model = Post fields = ['id','title', 'image', 'images',] #images is from another model POSTIMAGE def validate(self, post): try: title = post['title'] image = post['image'] images = post['images'] except KeyError: pass return post views. def update_post_api_view(request, slug): if request.method == 'GET': try: post = Post.objects.get(slug=slug) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = PostSerializer(post) return Response(serializer.data, status=status.HTTP_200_OK) if request.method == 'PUT': try: post = Post.objects.get(slug=slug) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) user = request.user if post.user != user: return Response({'response': "You can't edit the post!"}) serializer = PostUpdateSerializer(post, data=request.data, partial=True) if serializer.is_valid(): serializer.save() data = { 'success': 'update successful', } return Response(data=data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
ForeignKey Dropdown in Django Form
I want to show a dropdown in Django Form where the dropdown items are specified in another model in another app. Here's what I mean: title/models.py TITLE_CHOICES = ( ('MR', 'Mr'), ('MS', 'Ms'), ('MISS', 'Miss'), ('MRS', 'Mrs'), ('MX', 'Mx'), ) class Title(models.Model): title_name = models.CharField(max_length=10, choices=TITLE_CHOICES) def __str__(self): return self.title_name user/models.py class User(models.Model): ... user_title = models.ForeignKey('title.Title', on_delete=models.CASCADE) ... user/forms.py class SignupForm(forms.ModelForm): class Meta: model = User fields = '__all__' def signup(self, request, user): #this is to override the **allauth** signup form user.user_title = self.cleaned_data['title_name'] ... ... user.save() With the above code, the dropdown field renders properly; however, it is empty. Any ideas or suggestions are greatly appreciated. Thanks. -
How do I fill a dropdown menu with a list of dictionaries based on a previous select?
I have to let the user select gears from a list I extracted from a database. <fieldset> <label>Wählen Sie Ihre Getriebeart aus: </label> <select name="typgetr" id="type"> <option value="k">Kegelradgetriebe</option> <option value="s">Stirnradgetriebe</option> </select> </fieldset> Depending on this select the user can either choose a bevel or a spur gear. Based on that I want to fill the following select with one of the two lists below (first one is called by stri, second by keri). [{'name': '4950491', 'typ': 'Ritzel', 'nzahn': 17, 'zahnver': 4.412}, {'name': '4559693', 'typ': 'Ritzel', 'nzahn': 18, 'zahnver': 4.39}, {'name': '4960360', 'typ': 'Ritzel', 'nzahn': 18, 'zahnver': 4.5556}, {'name': '4960346', 'typ': 'Ritzel', 'nzahn': 20, 'zahnver': 3.5}, {'name': '4960377', 'typ': 'Ritzel', 'nzahn': 19, 'zahnver': 3.53}, {'name': '4960356', 'typ': 'Ritzel', 'nzahn': 19, 'zahnver': 3.53}, {'name': '4960348', 'typ': 'Ritzel', 'nzahn': 19, 'zahnver': 3.53}, {'name': '4960314', 'typ': 'Ritzel', 'nzahn': 20, 'zahnver': 3.05}] [{'name': '4950428', 'typ': 'Ritzel', 'nzahn': 11, 'zahnver': 3.3636}, {'name': '4447822', 'typ': 'Ritzel', 'nzahn': 11, 'zahnver': 2.5455}, {'name': '4936736', 'typ': 'Ritzel', 'nzahn': 11, 'zahnver': 2.55}, {'name': '4564106', 'typ': 'Ritzel', 'nzahn': 9, 'zahnver': 4.778}] <fieldset><label>Geben Sie Ritzelwelle und Zahnrad der <strong>ersten</strong> Getriebestufe ein: </label> <select name="zr12" id="zr12">{% for i in keri %}<option value="{{i.name}}">{{i.typ}}: {{i.name}}</option>{% endfor %}</select> </fieldset> I pretty much just want to show the … -
Dealing with responsivity on a HTML/CSS slider
I'm trying to create an image slider inside my image component in Django. I've got it setup like this so far {% extends './base.html' %} {% load static %} {% block content %} <script src='../../static/pages/main.js'></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous" /> <link rel="stylesheet" href="style.css" /> <div class="gallery-container"> <img class="background-gallery" src="../../static/images/laptop_crop.png" /> <div id="slider"> <figure> <img src="../../static/images/logo/kingict-okvir.png" /> <img src="../../static/images/logo/pwc-okvir.png" /> <img src="../../static/images/logo/degordian-okvir.png" /> </figure> </div> </div> {% endblock %} .gallery-container { display: flex; justify-content: center; align-items: center; position: relative; } .background-gallery { max-width: 50%; height: auto; padding: 5em; } #slider { overflow: hidden; position: absolute; width: auto; max-width: 250px; height: auto; max-height: 250px; margin-right: 10%; margin-bottom: 12%; } #slider figure { position: relative; width: 500%; margin: 0; left: 0; animation: 15s slider infinite; } #slider figure img { width: 20%; float: left; } @keyframes slider { 0% { left: 0; } 20% { left: 0; } 25% { left: -100%; } 45% { left: -100%; } 50% { left: -200%; } 70% { left: -200%; } 75% { left: -200%; } 100% { left: -200%; } /* 100% { left: -400%; } */ } `extends '../base.html' is just extending some elements I'm using on every site and have no impact … -
How can I inherit country, state and city drop down
I fetch data from database(pgadmin), but where I put id_city .. I will try this but not inherit data just show data... in dropdown javascript $("#id_country").change(function () { var url = $("#personFORM").attr("data-cities-url"); var countryId = $(this).val(); $.ajax({ url: url, data: { 'country': countryId }, success: function (data) { $("#id_state").html(data); } }); }); postform.html {% block content %} <div class="content-section"> <form method="POST" id="personForm" data-cities-url="{% url 'ajax_load_cities' %}" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <div class="container"> <legend class="border-bottom mb-4">Blog Post</legend> {{ form|crispy }} <button class="btn btn-outline-info" type="submit">Post</button> </div> </fieldset> </form> </div> {% endblock content %} views but here I got problem blog/state_dropdown_list_options.html but I have blog/city_dropdown_list_options.html How do i merge this to html file.... def load_cities(request): country_id = request.GET.get('country') state_id = request.GET.get('state') states = State.objects.filter(country_id=country_id).order_by('name') cities = City.objects.filter(state_id=state_id).order_by('name') return render(request, 'blog/state_dropdown_list_options.html', {'states': states, 'cities':cities}) How can I put cities also in a file <option value="">---------</option> {% for state in states %} <option value="{{ state.pk }}">{{ state.name }}</option> {% endfor %} here is an image in this image all data will be fetch from database successfully but when I select country then its not related to that country state and same thing to city! -
'None Type' object has no attribute 'id' Hot to resolve Type Error
This is a medical inventory system. Can't seem to get around this Type error. I am new to python and django. I have looked at other similar errors but have not found a solution. here is my views.py file inside the home directory.enter image description here Kindly assist...thank you. from django.shortcuts import render, redirect, Http404, get_object_or_404 from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, JsonResponse from accounts.models import Registration, YearEnding from home.backup import BackupDatabase @login_required(login_url='/account/login/') def HomePage(request): if not request.user.is_authenticated(): raise Http404 try: current_session_id = request.session['session'] except: ** currentSession = YearEnding.objects.order_by("-id").first() ** ** request.session['session'] = currentSession.id ** current_session_id = currentSession.id current_session = get_object_or_404(YearEnding, id = current_session_id) return render(request, 'home/index.html', {"current_session":current_session}) @login_required(login_url='/account/login/') def takeBackup(request): if request.method == "GET" and request.is_ajax(): forcefully = request.GET.get("forcefully") backup = BackupDatabase() response = backup.run(forcefully = int(forcefully)) if response["code"] == 200: return JsonResponse(response, status=200) else: return JsonResponse(response, status=400) else: return JsonResponse({}, status=400) -
Django custom management command - adding default values for arguments
I am using Django 2.2 and I want to write to add a custom task (for an app) that loads fixtures into database tables. This is what I have so far: from django.core.management.base import BaseCommand from django.core import management class Command(BaseCommand): help = 'Generate Capture Data from loaded fixtures' def add_arguments(self, parser): parser.add_argument('definitions', type=str, help='Name of the definitions fixtures file', default='definitions.json') parser.add_argument('sections', type=str, help='Name of the sections fixtures file', default='sections.json') parser.add_argument('questions', type=str, help='Name of the questions fixtures file', default='questions.json') def handle(self, *args, **kwargs): print(kwargs) However, when I run python manage.py generate_data, I get the following exception thrown: usage: manage.py generate_data [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] definitions sections questions manage.py generate_data: error: the following arguments are required: definitions, sections, questions Why are the defaults I provide to add_arguments() being ignored? -
Get data without increasing depth in Django Rest Framework
In my Django application I am getting the 'pk` value of the related field, I want to replace it with a combination of some other fields Json: { "transaction_no": 2321, "dispatch_date": "2020-08-01T09:19:37Z", "send_from_warehouse": "ABC", "model": "Rent", "vehicle_number": "__________", "transport_by": "Market Transport Vendor", "is_delivered": false, "sales_order": { "owner": "2" } }, To replace 2 with first_name I tried the SlugRelatedField like the following: Serializers.py class AtableSOSerializer(serializers.ModelSerializer): owner = serializers.SlugRelatedField(read_only=True, slug_field='first_name') class Meta: model = MaterialRequest fields = ('owner',) class AllotmentTableSerializer(serializers.ModelSerializer): sales_order = AtableSOSerializer(read_only=True) send_from_warehouse = serializers.SlugRelatedField(read_only=True, slug_field='name') transport_by = serializers.SlugRelatedField(read_only=True, slug_field='name') class Meta: model = Allotment fields = ('transaction_no', 'dispatch_date', 'send_from_warehouse', 'model', 'vehicle_number', 'transport_by', 'is_delivered', 'sales_order') and I got the first_name Json: { "transaction_no": 2321, "dispatch_date": "2020-08-01T09:19:37Z", "send_from_warehouse": "Yantraksh Logistics Private limited_GGNPC1", "model": "Rent", "vehicle_number": "__________", "transport_by": "Market Transport Vendor", "is_delivered": false, "sales_order": { "owner": "Foo" } }, But How can I get the combination of first_name + last_name in the owner field ? Here owner is the User Related Field -
How display uploaded files as list and as detail by id?
I have upload app in my django project, which consist below code models.py class File(models.Model): file = models.FileField(blank=False, null=True, upload_to =file_directory_path) def __str__(self): return self.file.name serialisers.py class FileSerializer(serializers.ModelSerializer): file = serializers.FileField() class Meta: model = File fields = '__all__'#('file') def to_representation(self, instance): representation = super().to_representation(instance) file = { "url": representation.pop("file"), "size": instance.file.size, "name": instance.file.name, #"date": instance.file.date, } representation['file'] = file return representation views.py class FileUploadView(APIView): parser_class = (FileUploadParser,) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py router = routers.DefaultRouter() router.register('api/upload', FileViewSet, 'upload') router.register('api/file', FileViewSet, 'file') urlpatterns = router.urls When, i GET list by url /api/upload/ or /api/upload/ it return error: AssertionError at /api/upload/ AutoFilterSet resolved field 'file' with 'exact' lookup to an unrecognized field type FileField. Try adding an override to 'Meta.filter_overrides'. -
'QuerySet' object has no attribute 'save' using django
opportunity = Opportunity.objects.filter(created_by__client=client,id=pk).exclude(is_deleted=True) for opp in opportunity: id = opp.id name = opp.name contact = opp.contact.id project = Project.objects.filter(client=client) project.opportunity = id project.name = name project.contact = contact project.save() -
module 'razorpay.client' has no attribute 'order'
when i integrate razorpay with django. payment is successful but not getting order_id when i did order_amount = 50000 order_currency = 'INR' order_receipt = 'order_rcptid_11' notes = {'Shipping address': 'Bommanahalli, Bangalore'} client.order.create(amount=order_amount, currency=order_currency, receipt=order_receipt, notes=notes, payment_capture='0') getting an error as module 'razorpay.client' has no attribute 'order' -
Dynamic images which i uploaded using django admin after deployement in heroku not showing up?
I have a ecommerce django website hosted in heroku(free acc) ,i dynamically upload the image and price through django admin page . The images were showing up for one day and from the next day i am getting image not found (404) error. Whats the error here or any reason . Can someone pls help me on this? Failed to load resource: the server responded with a status of 404 (Not Found) -
['“Invalid date” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
Currently I am making fullcalendar using Django. The problem arises when I want to update the time. add_event looks like this. def add_event(request): title = request.GET.get("title", None) start = request.GET.get("start", None) end = request.GET.get("end", None) event = Events(title=str(title), start=start, end=end) event.save() data = {} return JsonResponse(data) Add_event function seems to have no problem because when I execute it, it works properly. "GET /fullcalendar/add_event?title=testtime6&start=2020-08-06T00%3A00%3A00&end=2020-08-06T00%3A00%3A00&id=365&allDay=true HTTP/1.1" 200 2 But when I want to update the date, the error came out like this. django.core.exceptions.ValidationError: ['“Invalid date” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] [06/Aug/2020 14:28:41] "GET /fullcalendar/update?title=testtime6&start=Invalid+date&end=Invalid+date&id=367&allDay=false HTTP/1.1" 500 17368 update looks like this. def update(request): start = request.GET.get("start", None) end = request.GET.get("end", None) title = request.GET.get("title", None) id = request.GET.get("id", None) event = Events.objects.get(id=id) event.start = start event.end = end event.title = title event.save() data = {} return JsonResponse(data) My question is why I can add_event without no problem but suddenly when I want to update it, the date becomes invalid? Any idea about it? -
Django: Add additional fields to UserCreationForm
Can we add additional fields to UserCreationForm in django. By default there are 5 fields in UserCreationForm: username email first_name last_name password If I want to add additional fields like age, gender then how can I add these in UserCreationForm. I am new to django any reference or descriptive code will be Added django-forms in tags appreciable.