Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SQL query count
I have the following models in Django: class Author(models.Model): name = models.CharField(max_length=120) country = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=1024) publisher = models.CharField(max_length=255) published_date = models.DateField() author = models.ForeignKey(Author) There are 9 records in the Author table and 4 in the Book table. How many SQL queries would be issued when Book.objects.select_related().all() is evaluated? My guess was 4, because there are 4 rows in the Book table, so 1 query each to search for all the authors related to each book. Why is my answer wrong? The possible choices are 5, 4, 10 and 1. -
Django - Can't retrieve URL Parameter and make it a value in a form
I'm trying to retrieve the product_id from the url and make it the value for the "Product" field (in the CreateView) but it doesn't seem to get the parameter. I've tried using **kwargs but kept running into errors.I've tried def get() method also self.kwargs['pk'], none of which worked.What's the best way to go about this? product.html {% for prod in Products %} <a class="btn btn-primary" href="{% url 'review-create' pk=prod.id %}">Create Review</a> {% endfor %} urls.py path('review/new/<int:pk>', ReviewCreateView.as_view(), name='review-create'), views.py class ReviewCreateView(LoginRequiredMixin, CreateView): model = Review fields = ['product', 'profile', 'author', 'rating', 'reviewtext'] -
Making modelformset fields user specific?
I am using django as a framework for an inventory system. The inventory list is represented by a model with a field for the product name and 3 fields for the order amount for each individual location. What I would like to do is have a user log on go to the form and only see the Product field and the order amount field that is specific to them. Idk if this is possible to do it this way, I'm open to other ways of solving this problem. So far I've tried using init in my form to no avail. I know this isn't correct but hopefully it'll help you understand what I'm trying to accomplish. models.py class Sysco_Products(models.Model): Products = models.CharField(max_length = 200) order_amount = models.IntegerField(blank=True, null=True,) shop1_order_amount = models.IntegerField(blank=True, null=True,) shop2_order_amount = models.IntegerField(blank=True, null=True,) shop3_order_amount = models.IntegerField(blank=True, null=True,) def __str__(self): return self.Products class meta: managed = True db_table = 'sysco_products' form.py class orderform(forms.ModelForm): def __init__(self, *args, user, **kwargs): self.user = user super().__init__( *args, **kwargs ) if AuthUser.objects.filter(username=self.user).is_PSJManager1 == True: self.fields.pop('shop1_order_amount') elif AuthUser.objects.filter(username=self.user).is_CocoaManager1 == True: self.fields.pop('shop2_order_amount') else: self.fields.pop('shop3_order_amount') class Meta: model = Sysco_Products fields = ('order_amount', 'shop1_order_amount',) views.py class SyscoOrder(TemplateView): template_name= "SyscoOrder.html" def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update({ 'user' … -
How to know how much storage was occupied by a Python / Django application?
I developed a web application with Python and Django. I would like to limit the amount of space used for each user, since in the application it is possible to insert images and documents. I use Postgres as DBMS. How do I know how much storage a user occupies in Python and Django? -
Django tables2 paginate with filter, and add a custom column
I have implemented Django tables2 with pagination, 2000 pages 25 records per page. There are 2 things I'm trying to do: Add a filter Add a custom column to the table Detail: I've installed Django-filters, but I'm having trouble using it within tables2, I show the code from the docs in the filter.py, I already have bootstrap css implemented, but I only want to filter on the table columns, preferably with the ability to customise the layout of the filter form. I need to add a column which contains a link to a function, a simple url - details not important here: <td><a href="{% url 'depot:change_container' operation='add' pk=container.container_id fk=contents.sample_id %}" class="badge badge-primary" role="button">add</a></td>. So how can I add an extra column to the table? My code in summary to the relevent parts # tables.py import django_tables2 as tables from .models import Sample class SampleTable(tables.Table): class Meta: model = Sample # views.py def detailcontainer(request, container_id): unassigned_samples2 = Sample.objects.all() table = SampleTable(unassigned_samples2) RequestConfig(request, paginate={'per_page': 25}).configure(table) return render(request, 'container/detailcontainer.html', {'table':table}) # filters.py from django_filters.views import FilterView from django_tables2.views import SingleTableMixin class FilterSample(SingleTableMixin, FilterView): table_class = SampleTable model = Sample filterset_class = SampleFilter # template # this is what the docs say, but I … -
How to increase the counter on my Foreign Key Model
I have the following doubt: Let's assume that my Django project has the following models: class State(models.Model): initials = models.CharField('Initials', max_length=2, blank = False) name = models.CharField('State', max_length=50, blank = False) count = models.IntegerField('Foo Counter', default=0) .... class Foo(models.Model): name = models.CharField('Name', max_length=50, blank = False) state = models.ForeignKey(State, verbose_name='State', related_name='state_fk', on_delete=models.DO_NOTHING), .... So i have a form to add Foo instances to my db: class FooForm(forms.ModelForm): class Meta: model = Foo fields = '__all__' this is the view.py file: def home(request): template_name = 'home.html' form = FooForm(request.POST or None) if form.is_valid(): salvar = form.save(commit=False) salvar.save() return redirect('FooApp:home') else: context = { 'form': form } return render(request, template_name, context) I need that, every time the user registers a new 'Foo' the counter of the 'State' chosen by him is increased by 1, i search a lot here and in docs of Django but i could not find a way to do this. -
Why can't this subquery return more than one row?
This Query is being generated by Django ORM using RawSQL: SELECT `productos`.`codigo_barras`, ( SELECT articulos.costo_us * (1 + articulos.iva_coef) FROM articulos INNER JOIN ( SELECT articulos.id, MAX(encargosProveedor.fecha_entrega) FROM articulos, encargosProveedor_listado_articulos, encargosProveedor, itemArticulosProveedor WHERE articulos.id = itemArticulosProveedor.articulos_id AND encargosProveedor.id = encargosProveedor_listado_articulos.encargosproveedor_id GROUP BY articulos.producto_id ) AS ultimos ON articulos.id = ultimos.id ) AS `ultimo_precio` FROM `productos` It's giving an error 1242 - Subquery returns more than 1 row This is the result of the subquery +----+--------------------------------------+ | id | MAX(encargosProveedor.fecha_entrega) | +----+--------------------------------------+ | 1 | 2019-04-17 | +----+--------------------------------------+ | 3 | 2019-04-17 | +----+--------------------------------------+ I read the MYSQL documentation but i can't understand why is there a problem with returning two rows. I've tried a lot of alternatives. Where is the problem? -
Call same function from multiple views
I'd like to be able to call a function from different views in django. For example, say I need to generate a random number from within various views, I don't want to have to have the same 'random number' code repeated in each view - I just want to 'call on a function'. I'm greatly simplifying the following code for the sake of keeping this question brief: views.py def viewOne(request): #code for this view, including needing to generate a random number import random myrandomnumber = random.randint(1,21)*5 def viewTwo(request): #code for this view, including needing to generate a random number import random myrandomnumber = random.randint(1,21)*5 As you can see, I'm using the same code in both views to generate a random number. If I wanted to update how I generate a random number, I'd have to update it in both views. This is the sort of thing I want to do: views.py def createRandomNumber(): import random myrandomnumber = random.randint(1,21)*5 def viewOne(request): #code for this view, including needing to generate a random number createRandomNumber() def viewTwo(request): #code for this view, including needing to generate a random number createRandomNumber() Thanks very much for any help you can give me -
Using multiple login fields, email or phone number in Django All Auth
I am using Django All Auth to authenticate user but I need to use phone number or email field when logging in user. I extended user class as follows: class User(AbstractUser): phone_number = models.CharField(max_length=10, unique=True) def __unicode__(self): return self.username My signup form looks like this: class SignupForm(forms.Form): phone_number = forms.CharField(max_length=10,label='phone_number') def signup(self, request, user): user.phone_number = self.cleaned_data['phone_number'] user.save() Phone number is saved in the backend using this but I need to authenticate user if he enters either email or phone number. What class do i need to extend for Django All Auth. I have read a lot of questions but could not find anything good. If I place ACCOUNT_USER_MODEL_USERNAME_FIELD = 'phone_number' in settings.py , it authenticates via phone but not email. -
How to display only the filter form?
So I have set a filter for my model. Below works just fine. However, when I press filter (on home.html), it would fetch and display the whole database first below the filter form (please see screenshot). I don't want the program to pull all data from database in the first place. Instead I'd like it when I press filter from home.html, displays filter form only then wait for user input and show the result below the form. views.py: def search(request): option = option2019.objects.get_queryset() option_filter = optionFilter(request.GET, queryset=option) return render(request, 'option.html', {'filter':option_filter}) url.py urlpatterns = [ path('simple_upload', views.simple_upload, name='simple_upload'), path('search/', FilterView.as_view(filterset_class=optionFilter, template_name='option.html'), name='search'), path('OptionUpdate/<int:id>', views.OptionUpdate.as_view(), name='OptionUpdate'),] option.html: {% extends 'base.html' %} {% load widget_tweaks %} {% block content %} {% if user.is_authenticated %} <form method="get"> <div class="well container"> <h4 style="margin-top: 0">Filter</h4> {{ filter.form.as_p }} <button type="submit" class="btn btn-primary"> Search </button> </div> </form> <div style="margin: 20px;"> <h3>Demographics:</h3> <table class="table table-bordered"> <thead class="thead-dark"> <tr> <th>Last Name</th> <th>First Name</th> <th>DOB</th> <th>SSN</th> <th>Home Phone</th> <th>Phone1</th> <th>Phone2</th> </tr> </thead> <tbody> {% for hha in filter.qs %} <tr> <td>{{ hha.LastName }}</td> <td>{{ hha.FirstName }}</td> <td>{{ hha.dob }}</td> <td>{{ hha.SSN }}</td> <td>{{ hha.HomePhone}}</td> <td>{{ hha.Phone1}}</td> <td>{{ hha.Phone2}}</td> </tr> {% endfor %} </tbody> </table> </div> <div style="margin: 20px;"> <h3>Records:</h3> … -
Django : problem authentification page on some pages
In my Django project, I have created an authentification page but some other pages ask me to log in. If i take the code of another function there is no problem, that's really strange login page with name and password work. my main page : {% extends "base.html" %} //include {% if user.is_authenticated %} {% block body %} <a href="{% url 'list_users' %}">Afficher la liste des users</a>//work <br> <a href="{% url 'create_user' %}">Créer un nouvel utilisateur</a>//work <br> <a href="{% url 'test' %}">Test</a>//doesn't work ask me to login {% endblock %} my list_user page : def list_users(request): couch = couchdb.Server('http://foo:bar@localhost:5984/') x = []//useful information return render(request, 'blog/list_users.html', locals()) my test page, where I try new things : def test(request): couch = couchdb.Server('http://foo:bar@localhost:5984/') db = couch['_users'] list_profile = [] x = -1 for id in db: if id != "_design/_auth": user = db[id] db_user = couch['userdb-' + user['name'].encode('utf-8').hex()] list_profile.append([]) x = x + 1 try: doc = db_user['profile'] list_profile[x].append(id[17:]) list_profile[x].append(doc['firstName']) list_profile[x].append(doc['lastName']) list_profile[x].append(doc['email']) except: list_profile[x].append(id[17:]) list_profile[x].append("") list_profile[x].append("") list_profile[x].append("") return render(request, 'blog/test.html', locals()) this last function ask me to login, not any other. If i take the code of list_user and pu it inside function test, everything ok I don't understand what append. -
Как отправить через ajax файл на сервер?
уже больше недели не могу разобраться, нужно отправить картинку на сервер Django но я получаю ошибку: 415 (Unsupported Media Type) {"detail":"Неподдерживаемый тип данных \"text/plain;charset=UTF-8\" в запросе."} Если меняю ContentType на multipart/form-data, то получаю: 400 (Bad Request) Через postman отправляется нормально, в чем может быть ошибка?:( Скрипт: $(function() { // при нажатии на кнопку "Отправить" $('#upload-image').click(function() { // элемент, с помощью которого пользователь выбирает файл var file = $('#file'); var result = $('#result'); // если файл выбран, то if (file.prop('files').length) { // создаём объект FormData var formData = new FormData(); // добавляем в объект FormData файл formData.append('img', file.prop('files')[0]); $.ajax({ url: "http://127.0.0.1:8000/api/v2/update-ava/11/", data: { pk: 11, img: formData, }, DataServiceVersion: 2.0, processData: false, contentType: false, // contentType:"multipart/form-data", type: 'PUT', success: function(data) { result.html(data); } }); } else { result.html("Не выбран файл для загрузки!"); } }); }); На сервере: class UpdateProfile(APIView): """Редактирование аватара""" permission_classes = [permissions.AllowAny] # parser_classes = (FileUploadParser,) # parser_classes = (MultiPartParser, FormParser) # parser_classes = (FileUploadParser,) def get_object(self, pk): try: return Profile.objects.get(pk=pk) except Profile.DoesNotExist: raise Http404 def put(self, request, pk, format=None): snippet = self.get_object(pk) serializer = RedactIMG(instance=snippet, data=request.data, partial=True) if serializer.is_valid(): if "img" in request.FILES: serializer.save(img=request.data["img"]) serializer.save() return Response(serializer.data,status=201) return Response(serializer.errors,status=400) else: return Response(serializer.errors,status=400) -
save two forms on the same page
summarizing: I need the field Pets in the Pets table to be saved at the same time as the Usuario table is saved. And the user be FK in the Pets table the two forms are on the same page, with a single submit button then when the user is created in the system, the User's FK is already linked at the same time in the Pets table models.py class Pets(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) pets = models.CharField(max_length=255, choices=PET_CHOICES) class Usuario(models.Model): nome = models.CharField(max_length=50, blank=False) sobrenome = models.CharField(max_length=50, blank=False) user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(blank=False) forms.py class PetsForm(forms.ModelForm): pets = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, choices=PET_CHOICES, ) class Meta: model = Pets fields = '__all__' class UsuarioForm(UserCreationForm): nome = forms.CharField() sobrenome = forms.CharField( widget=forms.TextInput( attrs={ 'placeholder': 'Sobrenome'})) email = forms.EmailField( widget=forms.TextInput( attrs={ 'placeholder': 'Email Válido', 'id': 'email'})) views.py def cadastro(request): usuario = Usuario.objects.all() form = UsuarioForm() pets = Pets.objects.all() form2 = PetsForm() data = {'usuario': usuario, 'form': form, 'pets': pets, 'form2': form2} return render(request, 'cadastro.html', data) def cadastro_novo(request): if request.method == 'POST': form = UsuarioForm(request.POST, request.FILES) form2 = PetsForm(request.POST) if form.is_valid() and form2.is_valid(): user = form.save(commit=False) user.is_active = False user.is_staff = True user = form.save() user.refresh_from_db() # load the profile instance created … -
How to fix Django DetailView Missing query set exception error
When I try to use DetailView to view my posts I keep getting an exception error. ImproperlyConfigured at /post/1/ BlogDetailView is missing a QuerySet. Define BlogDetailView.model, BlogDetailView.queryset, or override BlogDetailView.get_queryset(). Request Method: GET Request URL: http://127.0.0.1:8000/post/1/ Django Version: 2.2 Exception Type: ImproperlyConfigured Exception Value: BlogDetailView is missing a QuerySet. Define BlogDetailView.model, BlogDetailView.queryset, or override BlogDetailView.get_queryset(). Exception Location: C:\Users\julia.virtualenvs\Documents-SYi_ANcG\lib\site-packages\django\views\generic\detail.py in get_queryset, line 73 Python Executable: C:\Users\julia.virtualenvs\Documents-SYi_ANcG\Scripts\python.exe Python Version: 3.7.3 I have reviewed my code against the book Django For Beginners by Will Vicent Still I can't find any problems models.py from django.db import models # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() def __str__(self): return self.title views.py from django.views.generic import ListView, DetailView # new from .models import Post # Create your views here. class BlogListView(ListView): model = Post template_name = 'home.html' class BlogDetailView(DetailView): # new Model = Post template_name = 'post_detail.html' urls.py # blog/urls.py from django.urls import path from .views import BlogListView, BlogDetailView # new urlpatterns = [ path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), # new path('', BlogListView.as_view(), name='home'), ] post_detail.html <!-- templates/post_detail.html--> {% extends 'base.html' %} {% block content %} <div class="post-entry"> <h2>{{ post.title }}</h2> <p>{{ post.body }}</p> </div> {% endblock content … -
How to Create Django Application Backup Automatically
I have developed a web application in Python and Django and need to back up the data daily. Currently, Postgres is used as DBMS. To perform the backup I discovered the django-dbbackup module, but to use it, I need to run the command python manage.py dbbackup. How do I automatically back up every day at a certain time? -
Autheticate before redirecting to dashboard
I placed a authentication before displaying a view but when i run it it give this error TypeError:'bool' object is not callable user.is_autheticated() not work in django 2.1.5 def Login_View(request): if request.method == "POST": username = request.POST['username'] password = request.POST['pwd'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) data_user = User.objects.get(username=request.user) request.session['username'] = username return render(request,'dashboard_app/index.html',{'data_user':data_user.username}) else: return render(request, 'login_app/index.html', {'error_message': 'Your account has been disabled'}) else: return render(request, 'login_app/index.html', {'error_message': 'Invalid login'}) return render(request, 'login_app/index.html') def Dashboard_View(request): if request.user.is_authenticated(): if request.session.has_key('username'): name=request.session['username'] return render(request, "dashboard_app/index.html",{'name':name}) else: request.session['username'] = User.username else: return render(request, "Login_app/index.html") I want to authenticate before redirection of page -
Creating a new link to python3 and renaming it to python
I just started using django. My problem is that it uses by default python 2 which is installed in my Comupetr. However I have also python3 and I prefer that django use python3 rather than python2. I discovered that when I type "python" inside the terminal python2 opens. This is because The python link points to python2 according to the PEP. The question is: how can I change it to point to python3 by creating a new link to python3 ? -
modifying request session in django
this code is from djagno 2 by example book which is very helpful by the way. the question here is how we managed to modify the request session although we didn't modify it except in save method ((( and it's on the session of the cart which in the first line after init))) what i see is that we have made a copy from the session dictionary at this line self.session = request.session class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): ''' Add a product to the cart or update it is quantity ''' product_id = product.id if not product_id in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session['modified'] = True for more clarification you can find the whole code of the project here code i managed to see the user session as I passed it from the context to the template and it's already modified -
There is a bug that changes the size of the file transferred from axios to django
I am building a react frontend server and a django backend server. I transferred the image file from react fronted to Django backend using axios. However, the contents of the image file in the backend media folder are not visible. So, I compared the size of the original file before transmission and the size of the transferred file in the media folder. The size of the original file was 687,687, and the size of the transferred file was slightly increased to 687,870. However, rather than transferring from a react frontend server, www.localhost:8000/admin I connected to django backend server admin and uploaded the file, and it was confirmed that it uploaded normally. I think react axios seems to have some dummy data in the process of transferring files. react axios frontend code. const formData = new FormData(); formData.append('file', file) const config = { headers: { 'Content-Type': 'multipart/form-data' } }; return (dispatch) => { axios.post(url, formData).then(response => { dispatch({ type: UPLOAD_FILE, payload: response }) }) django rest framework backend code models.py class File(models.Model): file = models.FileField(blank=False, null=False) def __str__(self): return self.file.name serializer.py class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = ("__all__") views.py class FileUploadView(CreateAPIView): parser_classes = (FileUploadParser, ) def post(self, request, … -
SocketException: OS Error: Connection refused, errno = 111 in flutter using django backend
I m building a flutter app with django rest-framework. The registration api is working fine in Postman but after some successful registration from the flutter app it is showing the above error. The request is been sent on https address. Removed csrf. Nothing happens. Request: var data={'email': signupemailidcontroller.text,'password1':passwordcontroller.text,'password2':confirmpasswordcontroller.text}; //http request here await http.post(websitesignupurl,headers: headers,body: json.encode(data)).then((onResponse){ print(onResponse.body); }).catchError((onerror){ print(onerror.toString()); }); Output in Console: SocketException: OS Error: Connection refused, errno = 111 I Expect the response of this request to be a Json object containing the user and token. -
Image is send in request.POST but cleaned in form.cleaned_data
I've a Profile form that accepts an Image to be used to display User's Profile Pic. I don't have problems sumitting the form, but when accessing the admin panel I can see that the file has not been saved. Even thought, It is send in request.POST: 'photo': ['es_usted_inteligente.jpg']}> SIGNUP REQUEST POST: <QueryDict: {'csrfmiddlewaretoken': ['SXoar0hPxsKCcMgFG1lJ5XoxjCzbEEqa9x5livVw4M0m9ZB25SGKmL3IUogJnxHz'], 'first_name': ['a'], 'last_name': ['gonzales'] , 'username': ['agonzales'], 'dni': ['744484848'], 'phone_number': ['89898989'], 'birthdate_month': ['1'], 'birthdate_day': ['1'], 'birthdate_year': ['1980'], 'email': ['agon zales@gmail.com'], 'password1': ['caballo123'], 'password2': ['caballo123'], 'shipping_address1': ['Urb. La Merced Mz.G Lot.32'], 'address_reference': ['Tienda Roja'], 'shipp ing_department': ['San Martín'], 'shipping_province': ['El Dorado'], 'shipping_district': ['Shatoja'], 'photo': ['es_usted_inteligente.jpg']}> profile_form.cleaned_data: 'photo': None} profile_form.cleaned_data: {'dni': '48494949', 'phone_number': '9898989', 'birthdate': datetime.date(1980, 1, 1), 'shipping_address1': 'Urb. La Merced Mz.G Lot.32', 'address _reference': 'Tienda Roja', 'shipping_department': 'Lambayeque', 'shipping_province': 'Chiclayo', 'shipping_district': 'Saña', 'photo': None} View: @transaction.atomic def signupView(request): peru = Peru.objects.all() department_list = set() province_list = set() district_list = set() for p in peru: department_list.add(p.departamento) department_list = list(department_list) # print("Department List: ", department_list) if len(department_list): province_list = set(Peru.objects.filter(departamento=department_list[0]).values_list("provincia", flat=True)) # print("Provice List: ", province_list) province_list = list(province_list) # print("dfsfs", province_list) else: province_list = set() if len(province_list): district_list = set( Peru.objects.filter(departamento=department_list[0], provincia=province_list[0]).values_list("distrito", flat=True)) # print("district List: ", district_list) else: district_list = set() if request.method == 'POST': ##### … -
IntegrityError: null value in column "image" violates not-null constraint
When I register a new user the website was creating a profile automatically and was using default.jpg image. Suddenly it stopped working. And the error says that I have a problem with my 'image' field. This is the error I get: IntegrityError at /accounts/register/ null value in column "image" violates not-null constraint DETAIL: Failing row contains (20, pbkdf2_sha256$150000$72dkND5yT5M0$+/chH/5Vu76KM7oNMjU694EWFZ/p+B..., null, f, kazanda, f, 2019-04-21 17:41:29.969889+00, Andreas, Swarchft, Germany, Frankfurt, andreas_sw@gmail.com, t, null). This is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics', null=True) def __str__(self): return self.user.username def save(self, force_insert=False, force_update=False, using=None): super().save() img = Image.open(self.image.path) if img.height > 250 or img.width > 250: output_size = (250, 250) img.thumbnail(output_size) img.save(self.image.path) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) my views.py class UserRegistrationView(SuccessMessageMixin, CreateView): form_class = UserCreationModelForm model = User success_url = reverse_lazy('login') success_message = "Account for %(first_name)s was created successfully. You will get email notification when admin will activate your account!" template_name = 'users/registration.html' def get_success_message(self, cleaned_data): return self.success_message % dict(cleaned_data) @login_required def profile(request): if request.method == 'POST': uform = UserUpdateForm(request.POST, instance=request.user) pform = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) posts = Post.objects.filter(author=request.user) if uform.is_valid() and pform.is_valid(): uform.save() pform.save() messages.success(request, 'Your account has been updated!') return redirect('users:cabinet') else: … -
How to create serializers of rmultiple class in Django rest framework?
This is my views class FindKeyWordNews(ListAPIView): queryset = [] serializer_class = KeyWordSerializers def get_queryset(self): query_list = [] keyword = self.kwargs.get("keyword") if keyword: republic = Republic.objects.filter(Q(headline__icontains=keyword)).order_by('-id') ndtv = Ndtv.objects.filter(Q(headline__icontains=keyword)).order_by('-id') indiatoday = Indiatv.objects.filter(Q(headline__icontains=keyword)).order_by('-id') hindustan = Hindustan.objects.filter(Q(headline__icontains=keyword)).order_by('-id') thehindu = Thehindu.objects.filter(Q(headline__icontains=keyword)).order_by('-id') zee = Zeenews.objects.filter(Q(headline__icontains=keyword)).order_by('-id') query_list = list(chain(republic, ndtv, indiatoday, hindustan, thehindu, zee)) return query_list I know to create serializer class for a single model class NdtvSerializers(serializers.ModelSerializer): class Meta: model =Ndtv fields = ('headline', 'link', 'date', 'category', 'sentiment') How can I create serializer class for multiple models insrtance for my above views? The schema of the model is the same. -
Name of JSON object appears in JSON itself when passed?
Very new to webdev stuff I'm trying to pass a JSON object to Django via AJAX, but the name of the JSON object I'm trying to pass keeps showing up in the data of the object itself. Wondering what I can do to fix this? jsonObj = {"pan":"cakes", "soy":"sauce"}; $.ajax({ url: "/AddItem", type: "POST", dataType: "json", data: { jsonObj }, def AddItem(request): if request.method == 'POST': QueryDict = request.POST q = dict(QueryDict.lists()) print (q) q shows up printed as {'jsonObj[pan]': ['cakes'], 'jsonObj[soy]': ['sauce']} Any help would be appreciated, many thanks (: -
What's happening with this formset?
I create a formset using a queryset I defined. Just before I render the template with the formset, I update the records the queryset returned in such a way that they no longer would have met the queryset's filter criteria. If i do "something" (i.e. print(formset) or num_forms = formset.total_form_count()) w/ the formset prior to rendering the template, it returns all of the records the original query returns. If I don't do something w/ the formset prior to rendering the template, the formset is empty. Easy enough for me to leave some arbitrary operation in the code but would love to understand what's going on here. Code from views.py: batch = (Ad.objects.filter( (Q(labeler_expiration__lt=timezone.now()) | Q(labeler_expiration__isnull=True)) & Q(category__isnull=True)) .order_by('id')[:25] ) formset = AdFormSet(queryset=batch) #Here I need to do something w/ the formset: num_forms = formset.total_form_count() # print(formset) #This print could also work instead of the line above (Ad.objects.filter(pk__in=batch.values('pk')) .update(labeler=request.user.labeler, labeler_expiration=(timezone.now() + timedelta(minutes=25)))) return render(request, 'label_ads_batch.html', {'formset': formset}) Trying to understand what is happening w/ the num_forms= (or the print statement) that is changing what is in the formset by the time the render comes along.