Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which AWS service to use when i have different backend and frontend?
I have my backend written in django. I researched and understand that AWS EC2 or AWS lightsail are cost effective solutions for me. What I am confused is about frontend. Should I use the same instance or create a container and use Amazon Container services ? The concerns I have is flexible load of containers during multiple users coming to website, CORS/Same origin issues when deployed in same instance, security issues when deployed in same instance, cost effectiveness Please help how do you decide in this situation -
Resizing django text forms and allowing users to make linebreaks with enter
I'm currently developing a web app with django and I have some forms where the users can enter a lot of text (up to 5.000 chars). I'm doing this using a CharField in forms.py: from django import forms class text_form(forms.Form): ... longer_text = forms.CharField( max_length=5000, widget=forms.Textarea( attrs={ 'rows':10, 'cols':2, 'data-length':5000, }), help_text='Some help text', label = 'Label Text', required=True ) The problems I'm facing right now (and I couldn't solve them even though I read a lot of related SO question) are: 1) I want the users to see a larger field (multiple rows) where they can insert text. Right now it's about maybe two rows and doesn't resize regardless the values I insert as rows value in attrs. 2) The users should be able to use the Enter key on their keyboard within those textareas to make a linebreak Any ideas how to achieve this? Thanks! -
updating a webpage every minute
I have a python function that crawls a website and returns a dictionary every minute. I want to show this dictionary in a table on a website and in case of any change in the crawled data to update the website and make a chrome notification. I don't know how it can be possible. -
DRF field validation on subset of Model's field
Allow me to first sketch the relevant parts of my Django/DRF project using some relevant snippets (Note that the following code snippets do not result in working code, but are there to show the overall structure of my problem): models.py class Sample(models.model): property_one = models.CharField(max_length=10, validators=property_one_validators) property_two = models.CharField(max_length=10, validators=property_two_validators) property_three = models.CharField(max_length=10, validators=property_three_validators) property_four = models.CharField(max_length=10, validators=property_four_validators) serializers.py class SampleSerializer(serializers.ModelSerializer): class Meta: model = Sample fields = '__all__' views.py class SampleViewSet(viewsets.ModelViewSet): serializer = SampleSerializer @action(detail=True, methods=["get"]) def method_one(self, request, pk): # Require property_one and property_three in request.data @action(detail=True, methods=["get"]) def method_two(self, request, pk): # Require property_one and property_two in request.data @action(detail=True, methods=["get"]) def method_three(self, request, pk): # Require property_two and property_four in request.data As you can see various subsets of the Sample model's parameters are used within the available API requests. What I would like to do is validate the required parameters within each API request using their respective validators (e.g. validate property_one with property_one_validators defined in models.py). From what I understand from the Serializer documentation, you are able to use validate to validate a complete filled in Model class (e.g. with property_one to property_four), but I would want use the same Serializer or at least its functionality to … -
How to include user_id (foreignKey) when posting an new record?
I'm new to python Django rest-framework, I'm facing this problem when creating a new address: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (21, full name, 123456789, any, any, any, any, any, any, f, null). This is The address model: from django.db import models from django.contrib.auth.models import User class UserAddress (models.Model): user = models.ForeignKey( User, related_name='addresses', on_delete=models.CASCADE) full_name = models.TextField(default='') phone = models.CharField(max_length=30, default='') city = models.TextField() province = models.TextField() street = models.TextField() description = models.TextField() postcode = models.CharField(max_length=20) country = models.CharField(max_length=100) is_default = models.BooleanField(default=True) class Meta: db_table = 'user_addresses' And this is the serializer: from rest_framework import serializers from user_action.models.address import UserAddress class UserAddressSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) class Meta: model = UserAddress fields = ['id', 'full_name', 'phone', 'city', 'province', 'street', 'description', 'postcode', 'country', 'is_default'] And the POST method: @api_view(['POST']) @permission_classes((IsAuthenticated,)) def createUserAddress(request): user = request.user if request.method == 'POST': serializer = UserAddressSerializer(data=request.data) if serializer.is_valid(): newAddress = serializer.save() else: return Response(serializer.errors) return Response(serializer.data) Thanks in advance. -
Querying Parent from the foreign key django
I have the following models : class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=32) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' # unique identifier, changed to email (default was username) REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() # custom manager for interacting with database def __str__(self): return self.email class Refer(models.Model) : referred_by = models.ForeignKey(CustomUser, on_delete=models.CASCADE, default='admin', related_name='reffered_by') referrals = models.ManyToManyField(CustomUser, related_name='refferals', blank=True) unique_ref_id = models.CharField(max_length=8, blank=True, default=generate()) def __str__(self) : return f'Referred By: {self.referred_by}' I want to implement referral system using this, I have unique_for_id field (example 'exbvagtl'), how can i create new referral under that user? Something like : Refer.objects.create(referred_by= CustomUser.objects.get(Refer__unique_for_id='exbvagtl')) Better model designs, resources and improvements are heavily welcomed! -
Django query annotation to serialize data to the network
Here I have data as listed below. category order_no status cat1 11 success cat1 12 success cat1 12 success cat2 11 success cat2 11 success cat1 15 success cat3 50 failed And I want to aggregate data like as tabled below. O/P- Order_no category order type total order successful failed 11 cat1 2(composite) 1 1 0 11 cat2 2(composite) 2 2 0 12 cat1 1(single) 2 2 0 15 cat1 1(single) 1 1 0 50 cat3 1 (single) 1 0 1 if any order no is associated with two different categories(like cat1,cat2) then its order_type will be 2(composite) otherwise it will be 1(single) Now I am trying to write Django query in viewset to serialize the data to the jquery datatables. However, my query is getting some different results or giving error. queryset = Model.objects.annotate(order_no=F('order_no'),category=F('category'),\ order_type=Count('category','order_no',distinct=True),total_orders=Count('category'),\ total_success_order=Count('service_status', filter=Q(service_status='success')),\ total_failed_order=Count('service_status', filter=Q(service_status='failed'))) What approach should I follow ... and I can not use raw SQL queries due to project limitations. -
how to use temporary database for every user in django
so i am learning Django and making a todo application but i am stuck with a problem. I am storing every task on sqlite3 database(default by django) with models but when anyone store any task it is also visible to other person also how can i fix that? models.py:- from django.db import models # Create your models here. class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.title -
how do i disable browser back button after login?
def login(request): if request.session.has_key('is_logged'): return redirect('/') if request.method == 'POST': email = request.POST['email'] psw = request.POST['psw'] user = auth.authenticate(username=email, password=psw) if user is not None: auth.login(request, user) request.session['is_logged'] = True return redirect('/') else: messages.info(request, 'invalid user name or password') return redirect('login') else: return render(request, 'login.html') def logout(request): auth.logout(request) return redirect('/') how do i disable browser back button after login? is it good idea to disable backbutton from preventing logged users ? after login it redirects to the home page and from home page if i click browser back button it goes the previous page login. -
Django 3 vs Django 2
Is django 3 backward compatible with django 2? Are there any syntax changes in django 3 compared to django 2? Will i be able to follow django 2 tutorial on YouTube and be okay to apply it in django 3 as there are not many django 3 tutorials available? -
Django, following a tutorial and there's an issue where my {% block content %} is not being recognized
Here's the dir structure: directory structure If the image isn't displaying here's a text version: templates myapp new_search.html base.html base.html code: {% block content %} {% endblock content %} new_search.html code: {% extends "base.html" %} {% block content %} <h2>NEW SEARCH</h2> {% endblock %} I can display the base.html fine. The new_search.html however displays like this: new_search.html I also want to mention a side question. My Django server isn't running however I can still open the html in my browser. Is that supposed to happen? My URLs when opening both html's are: base.html: http://localhost:63342/Full-Stack%20Web%20App/myapp/templates/base.html?_ijt=rtiq5iv3jude6ijjmu0ept2i82 new_search.html: http://localhost:63342/Full-Stack%20Web%20App/myapp/templates/myapp/new_search.html?_ijt=rtiq5iv3jude6ijjmu0ept2i82 -
Retrieve all entries from a ForeignKey and display them in the html template in Django
I'm writing after checking different threads on similar issues with no luck whatsoever, hence I'm sharing with you my problem hoping you can give me a hint on how to solve it. I am trying to build a keyword ranking checker and I have two models, Keyword and Ranking: models.py class Keyword(models.Model): keyword = models.CharField(max_length=100) date_added = models.DateTimeField(default=timezone.now) market = models.CharField(max_length=100) domain = models.CharField(max_length=100) class Ranking(models.Model): keyword = models.ForeignKey(Keyword, on_delete=models.CASCADE) position = models.IntegerField() position_date = models.DateTimeField(default=timezone.now) Basically, user will insert a list of keywords in the DB and an API will check each month the ranking for each keyword. The ranking model will store each ranking check and relate it to the keyword. What I'd like to do is to display in the html template the list of keywords with their rankings (all of them because I want to show historical rankings too), and here is where I'm having issues. Basically I'm not able to retrieve all the rankings for a given keyword and pass it to the html as a template tag. I only can show the complete list of keywords and that's it. views.py def rankings(request): keywords = Keyword.objects.filter(market="es") return render(request, 'rankapi/marketview.html', {'keywords': keywords}) I've tried to do … -
Need Help: Django-CMS toolbar disabled
i am making a site on djangoCMS and for a better view i disabled the the toolbar. now i can't enable it or i can't find any option to do that. Here the toolbar means DjangoCMS own toolbar....not the website's toolbar which i enable it from the template by inserting {% cms_toolbar %} & {% show_menu 0 100 100 100 %}. it's a silly thing but it is driving me crazy.... please let me know of you use that djangoCMS or know the option. i went to documentation .... all they have talked about website's own toolbar and it's customization. Django version 2.2.12 and i am using python3.8 ...FYI -
Django admin - "Please enter the correct email address and password for a staff account" AND user exists
Screenshot failing attempt to log in to django admin panel with an existing user Using a custom User model where the required fields are email, DOB, phone and password. models.py class UserManager(BaseUserManager): def create_user(self, email, date_of_birth, phone, password=None): """" Creates and saves a User with the given email,phone, date of birth and password. """"" if not email: raise ValueError('Users must have an email address') if not phone: raise ValueError('Please provide a phone number') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, phone=phone ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, phone, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email=email, password=password, date_of_birth=date_of_birth, phone=phone ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser, auth_models.PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) phone = models.CharField(max_length=80) city = models.CharField(max_length=80) province = models.CharField(max_length=80) street = models.CharField(max_length=60) postcode = models.CharField(max_length=16) date_of_birth = models.DateField() date_joined = models.DateTimeField(default=datetime.now, blank=True) # Is the user currently active? is_active = models.BooleanField(default=False) # Is the user an app administrator? is_admin = models.BooleanField(default=False) # Is the user a Point Of Sale Owner? is_manager = models.BooleanField(default=False) objects = UserManager() class Meta: ordering = ('id',) USERNAME_FIELD = … -
Django with ajax Request
I have below code function OpenModal() { var fname="Quartz"; var mname="Rohit"; var lname="Patel"; var url="{% url 'display_modal' %}"+fname +"/"+mname+"/"+lname; alert(url); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById('divcontent').innerHTML=this.responseText; } }; xmlhttp.open("GET",url,true); xmlhttp.send(); } How to execute the above code on click of a button in django templating language. url is like path('member/search/', views.displayModalView, name="display_modal"), -
Display all of a Users info on the one page within Admin
My Users have both a ONE-ONE personal_information table, and a ONE-ONE previous_studies table. I know that I could use Inline to display both the personal_information and previous_studies tables on the one page if they had a relationship, but within the admin panel I am instead wanting to click a User, then see both their personal_information and previous_studies (at the moment I need to access the User, personal_information and previous_studies on different pages). Any pointers on how to accomplish this would be greatly appreciated. Thank you. -
Populate dropdonw and multiselect from get_initial()
I am trying to prefill a CreateView form with date, get_initial() seems the right way. It uses a dict to prefill data. But how to fill dropdown and multiselect? What should I put in the dict? -
Django take value from url
I have problem with take value from url (? Site = value). When I had function in views.py it was work, but now I moved this to another file. Can someone solve this problem? functionAjax.py: def htmlMain(request): if request.is_ajax and request.method == "POST": UrlCut = request.GET.get('site','Main') Messages = NewsMessage.objects.all().order_by('-Data').values() context = { "Messags" : Messages } return render(request, 'ajax'+UrlCut+'.html', context) -
Name error at / in django while trying to use Users.objects.save_user
I am trying to create a bank form which can be saved to the database.I am getting name error exception value: name txt1 is not defined my app/views: from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth # Create your views here. def formregister(request): if request.method=='POST': Name_of_branch=request.POST['txt1'] Purpose_of_loan=request.POST['POL1'] Type=request.POST['TOL1'] Amount=request.POST['A1'] Full_name_of_Ap=request.POST['FN1'] Minorities_zororashtrians=request.POST.get('r2', False) user=User.objects.create_user( Name_of_branch=txt1, Purpose_of_loan=POL1, Type=TOL1, Full_name_of_Ap=FN1, user.save(); print('user created') return redirect('form.html') else: return render(request,'form.html') This is my views. -
Select a specific button in Javascript/AJAX
I have a list where a user can save various items in a Django app. Next to each items I have a button that can be used to delete this item. Items are stored in a database and are displayed with a for loop. The problem is whatever button I press, the first one is selected and deleted. I am new to JavaScript but I do understand that my issue is coming from my var.product selector because .val() returns the first element that matches ('.substitut'). I have tried to tweak a little with $(this) but with no luck... How can I select each product in each button individually? My HTML: {% for saved in saved_list %} <form class="form_id" method='post'>{% csrf_token %}{{ saved.id}} <button class='substitut' value='{{ saved.id}}'><i class='fas fa-trash'></i></button> </form> {% endfor %} My AJAX: $(".form_id").on('submit', function(event) { event.preventDefault(); var product = $('.substitut').val(); console.log(product); var url = '/register/delete/'; $.ajax({ url: url, type: "POST", data:{ 'product': product, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { if (data['success']) console.log(product); $("#fav_list").load(location.href + " #fav_list > *"); } }); }); -
How to add the option that checks if checkbox is checked and deletes checked objects in Django
Hello I'm a new comer to Django. I'm confused now having the thought of how django admin panel deleting option works and how to use that option in my site.The purpose is to use all CRUD options in one template not just with url like deleting one by one. I have a models.py: GRADES = ( ('1', '1',), ('2', '2',), ('3', '3',), ('4', '4',), ('5', '5',), ('6', '6',), ('7', '7',), ('8', '8',), ('9', '9',), ('10', '10',), ('11', '11',), ) class Grade(models.Model): grade = models.CharField(null=True, max_length=200, choices=GRADES, unique=True) def __str__(self): return self.grade class Unique_grade(models.Model): grades = models.ForeignKey( Grade, null=True, on_delete=models.SET_NULL, verbose_name="Sinf raqamini kiriting", ) A_B_C = models.CharField(max_length=1, null=True,) motto = models.TextField(max_length=200, null=True, verbose_name='Shior', blank=True, unique=True, default=None) class Meta: unique_together = ['grades', 'A_B_C'] def clean_motto(self): if self.cleaned_data['motto'] == "": return None else: return self.cleaned_data['motto'] def __str__(self): return f"{self.grades}-{self.A_B_C}" class Pupil(models.Model): first_name = models.CharField(max_length=200, null=True) surname = models.CharField(max_length=200, null=True) date_of_birth = models.DateField( null=True) nation = models.CharField( max_length=100, null=True, verbose_name="Nation") grade = models.ForeignKey(Unique_grade, null=True, on_delete=models.SET_NULL) m_full_name = models.CharField( max_length=200, null=True, verbose_name="Mother's full name") f_full_name = models.CharField( max_length=200, null=True, verbose_name="Father's full name") date_added = models.DateTimeField(auto_now_add=True) class Meta: unique_together = [ ['first_name', 'date_of_birth', 'surname', 'nation', 'grade', 'm_full_name', 'f_full_name'], ] def __str__(self): return f"{self.first_name} {self.surname}." my forms.py: … -
Django retrieve checkbox values sent by Ajax POST request
I am trying to send form data to Django server via Javascript Ajax request specifically checkbox values, but at the server I read None values. here's the server code that reads: @csrf_protect def order_pizza(request): if request.is_ajax() and request.method == "POST": topps = Topping.objects.all() for topp in topps: mytop = request.POST.getlist('topping') print(f"topp is {topp.__str__()} mytop is {mytop}") return HttpResponse("pizza order!!") And here's the html for the form: <form id="form_pizza_order" class="form_pizza_order" method="post"> {% csrf_token %} <div class="row"> <div class="order_topp_col col-12"> <header> Topping </header> {% for topp in toppings %} <input type="checkbox" id="{{ topp.name }}" name="topping" value="{{ topp.name }}"> <label for="{{ topp.name }}"> {{topp.name}}</label> {% endfor %} </div> ... the print function returns a result : topp is Pepperoni mytop is [] topp is Sausage mytop is [] topp is Mushrooms mytop is [] topp is Onions mytop is [] topp is Ham mytop is [] etc ... what do I have to do to be able to read the checkboxes values ? thanks. -
Django html form data is invalid with function as well as class based view
Unable to save the create view in the database as the POST request says all fields are required, even though the data is mentioned in the form fields before submitting. All the data fields are provided before submitting and the dropdown and checkboxes data is pre-populated as per context data correctly. models.py class RawMaterial(models.Model): rm_code = models.CharField(max_length = 10, unique = True) rm_name = models.CharField(max_length = 100, unique = True) rm_unit = models.ForeignKey(RMUnit, blank = False, on_delete = models.CASCADE) rm_category = models.ForeignKey(RMCategory, on_delete = models.CASCADE) rm_rate = models.FloatField() rm_tax = models.FloatField(null = True) rm_price = models.FloatField(blank = False) rm_vendor = models.ManyToManyField(Vendor) rm_store_issue_price = models.FloatField(null = True) rm_dept_use = models.ManyToManyField(Department) def __str__(self): return self.rm_name def get_absolute_url(self): return reverse('rm-create', kwargs=None) views.py class RawMaterialCreateView(CreateView): model = RawMaterial fields = '__all__' template_name = 'rm_registration.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['itemcode'] = generateCode(RawMaterial, 'RM', 'rm_code') context['categories'] = RMCategory.objects.all() context['units'] = RMUnit.objects.all() context['departments'] = Department.objects.all() context['vendors'] = Vendor.objects.all() return context def form_valid(self, form): itemcode = self.instance.itemcode print("Item Code is : " + itemcode) instance = form.save(commit=False) instance.save() return super(RawMaterialCreateView, self).form_valid(form) registration.html <form method="POST" action=""> {% csrf_token %} <div class="row"> <div class="form-group col-6"> <label for="rm_code">Item Code : </label> <input type="text" class="form-control form-control-sm" id="rm_code" value = "{{ … -
How to mutate django taggit in graphql?
@property def get_tags(self): return self.article_tag.all() @convert_django_field.register(TaggableManager) def convert_field_to_string(field, registry=None): return List(String, source='get_tags') conversion is working but mutation is not?? -
Django Rest Framework using Viewsets with different renderers
does it make sense to use Django Rest Framework also to render my HTML Code with Bootstrap and so on...? If no, what is the best solution to split the API endpoints and HTML view? I exposed an API with DRF Viewsets and JSON serializers. It's working pretty well. Additionally I would like to add a HTML rendered version of this API and design a HTML form for it. Both API and HTML rendered version are supposed to run on the same machine. Thanks in advance