Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use django model in another application
I have two different apps for homepage(main) and events(events) In the models.py of I have a class "Event". In the events/views.py def all_events(request): events_list = Event.objects.all() return render(request, 'event-listing.html', {'events_list': events_list}) which worked just fine. But I want to do the following in the homepage(main) application's views.py def all_events(request): events_list = Event.objects.all() return render(request, 'index.html', {'events_list': events_list}) I imported the following: from BV.events.models import Event but it says : ModuleNotFoundError: No module named 'BV.events' My goal is to show the events in the homepage. -
Not able to connect Azure MySql database in Django Project directly
* I was trying to connect Azure Mysql database in django using db_name, post, username, password, and host name.* ** File "C:\Users\somesh.hiremath\Desktop\Django\Somesh\dj-Somesh\lib\site-packages\MySQLdb_init_.py", line 123, in Connect return Connection(*args, **kwargs) File "C:\Users\somesh.hiremath\Desktop\Django\Somesh\dj-Somesh\lib\site-packages\MySQLdb\connections.py", line 185, in init super().init(*args, kwargs2) django.db.utils.OperationalError: (1045, "Access denied for user 'NewUswe123'@'localhost' (using password: YES)") C:\Users\somesh.hiremath\Desktop\Django\Somesh\TestDjango\TestDjango\settings.py changed, reloading. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'My_db', 'USER': 'NewUswe123', 'PASSWORD': 'Something@123', 'HOST': 'something_name.nothings.cloudapp.azure.com', 'PORT': '3389', 'OPTIONS': { 'read_default_file': '/path/to/my.cnf', }, } } -
Django: How to POST div element to views.py without reloading the page?
I have been struggling with this problem for more than days. I have looked at many documentations but nothing helped me. I am working on Django web application development. The problem is that I have to get the contents(i.e. text inside) of a div element through a form submit (submitted using a button). The catch is that the content inside div element is not fixed. It is initially empty, it changes and shows the info of the actions performed in the page. I am trying to save those info into a list on the server side one-by-one. The ideal solution will be "everytime I click save-info button and the info gets added to a list of info present in views.py (webpage not refreshed on button click)" I researched about posting div elements to server using JQuery and tried myself but could not be successful. Can someone please suggest how do I ach My effort: <form method="POST" id = 'notes_form' action="##" > {% csrf_token %} <div id="notes" cols="5" rows="2"></div> <input type="submit" id="note_btn_id" value="save info"> </form> <script> $(document).ready(function(){ $('#notes_form').submit(function(event){ event.preventDefault(); var notesForm = $(this); var posting = $.post(notesForm.attr('action'),notesForm.serialize()); posting.done(function(data){ console.log("SUCCESS"); }); posting.fail(function(data){ console.log("Try again"); }) }); }); </script> Server side: data_pos =[] … -
django: I accidentally deleted the admin.py file. how to recover it?
I deleted the admin.py file with the rm command. The project is working now. But it will not work after restarting Nginx. Who can help me? -
How to conditionally enable and disable Cursor Pagination on Django Rest Framework?
I have a specific usecase where I need to make available same queryset endpoint for the frontend with and without pagination. I need to use CursorPagination and currently I'm just setting pagination_class = CursorPagination on my *ViewSet class. Is there an easy way to achieve this requirement? -
Comparing between two user models
I have two models. UsersOne and UsersTwo. Both these databases looks like this: class UsersOne(models.Model): username = models.CharField(max_length=255, unique=True) firstname = models.CharField(max_length=255, blank=True, null=True) lastname = models.CharField(max_length=255, blank=True, null=True) password = models.CharField(max_length=255) email = models.CharField(max_length=255, blank=True, null=True) I am tyring to find every user with matching email in the UsersTwo model that. So if there are 10 users in UsersOne and 5 of them have matching email UsersTwo i want to write them out in a csv file. So for example if user John, Doe, ***, jondoe@gmail.com also is a user in UserTwo model i want to make a query to get him. So i have tried this. import both models... users_one = UsersOne.objects.all() matching = [] for i in users_one: matching.append(UsersTwo.object.filter(email=users_one[i].email)) And i get this error: QuerySet indices must be integers or slices, not User.` -
CustomUser Migration Failed Django
I tried making my migrations but can these error messages: ERRORS: accounts.CustomUser.groups: (fields.E304) Reverse accessor for 'accounts.CustomUser.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'accounts.CustomUser.groups' or 'auth.User.groups'. accounts.CustomUser.user_permissions: (fields.E304) Reverse accessor for 'accounts.CustomUser.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'accounts.CustomUser.user_permissions' or 'auth.User.user_permissions'. auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'accounts.CustomUser.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'accounts.CustomUser.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'accounts.CustomUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'accounts.CustomUser.user_permissions'. Here is my CustomUserManager: class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError("User must have an email") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): user = self.create_user(email, password=password, **extra_fields) user.is_active = True user.is_staff = True user.is_admin = True user.save(using=self._db) return user Let me know by making a comment if i should also upload my model. -
Code goes to except block only (not Try block) [closed]
I have written following code in django for forgot password, my views code as under, def forgot_password(request): if request.method=="POST": try: user=User.objects.get(email=request.POST['email']) subject='OTP for new password' otp=random.randint(1000,9999) message = 'OTP for forgot password is '+str(otp) email_from = settings.EMAIL_HOST_USER recipient_list=[user.email,] send_mail( subject,message,email_from,recipient_list ) return render(request,'otp.html',{'email':user.email,'otp':otp}) except: msg="Email Does Not Exists" return render(request,'forgot_password.html',{'msg':msg}) else: return render(request,'forgot_password.html') now whenever i try to get forgot password it says email id already exists. It does not go to OTP page. my urls is as under, path('forgot_password/',views.forgot_password,name='forgot_password'), path('varify_otp/',views.varify_otp,name='varify_otp'), path('new_password/',views.new_password,name='new_password'), pls help -
How to use email as username for Django registration
I am new to django and creating registration form using django's UserRegistrationForm, which requires username and password . I want to use email instead of username. How I can do this? def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request,f'Account Created For {username} !') return redirect('starting-page') else: form = UserRegisterForm() return render(request,'users/register.html',{'form': form}) -
Как получить id объекта при POST запросе от пользователя
Как мне получить id объекта Payment при отправке Post запроса пользователем? Если указать явно Payment.objects.get(pk=13), всё срабатывает КОд ошибки : stellaj_manager.models.Payment.DoesNotExist: Payment matching query does not exist. class MakePay(CreateAPIView): """Совершение покупки""" serializer_class = MakePaySerializer permission_classes = [permissions.IsAuthenticated] def perform_create(self, serializer): # Достаём объект пользователя для сохранения user = User.objects.get(user_id=self.request.user) obj = self.request.data.__getattribute__('id') serializer.save(user_id=user) p = Payment.objects.get(pk=obj) p.buy_item() class Payment(models.Model): """История покупок""" user_id = models.ForeignKey(to=User, verbose_name='Пользователь', on_delete=models.PROTECT) product_id = models.ForeignKey(to=Product, related_name='payments', verbose_name='Продукт', on_delete=models.PROTECT) total = models.PositiveSmallIntegerField(verbose_name='Итоговая сумма',default=0) date = models.DateTimeField(auto_now_add=True, verbose_name='Время покупки') quantity = models.IntegerField(verbose_name='Проданно штук', default=1) class Meta: verbose_name = 'История' verbose_name_plural = 'Истории' ordering = ['-date'] def __str__(self): return f'Покупка от: {self.date}' # Метод покупки товара пользователем @transaction.atomic() def buy_item(self): try: product = self.product_id product.quantity -= self.quantity product.save() self.total = product.price * self.quantity self.save() user_count = self.user_id user_count.balance -= self.total user_count.save() return 'Successeed' except: raise Exception('Something goes wrong, try later') -
I want custom pagination in this ListApiview but cannot resolve it
class ItemLedgerView(generics.ListAPIView): permission_classes = [ItemLedgerPermission] queryset = PurchaseDetail.objects.all() pagination_class= CustomPagination paginate_by = 10 def get(self, request): query_dict = { } for k, vals in request.GET.lists(): if vals[0] != '': k = str(k) query_dict[k] = vals[0] query_filter = {} if "date_after" in query_dict: query_filter['created_date_ad__date__gte'] = query_dict['date_after'] if "date_before" in query_dict: query_filter['created_date_ad__date__lte'] = query_dict['date_before'] page = self.paginate_queryset(self.queryset) data = get_item_ledger(query_dict) return self.get_paginated_response(data)enter code here I wrote this code when tried to go to next page. I got error like Cannot resolve keyword 'page' into field. -
django tests: client request an empty string instead of an WSGIRequest object
I am working on a django project for which I created an app that is used in other projects. The app and the project have their own repository and folder. I want to write tests that are specific to the app of that form: from django.test import TestCase from django.urls import reverse class SignUpTest(TestCase): def test_my_signup_get2(self): response = self.client.get(reverse('signup')) self.assertEqual(response.status_code, 200) When I run such tests from the folder of my app, the request object generated is an empty string, which will cause the test to fail. Within the logic of the project, the request.user is being accessed, which does not exist on a string. When i run the exact same tests from the project folder where this app is used, the request object is a WSGIRequest object and the test succeeds, as the request.user is present. How can I make sure that the request is always a WSGIRequest? -
How to update the options (django queryset variable) of select tag based on the value of onchange event in django template?
I will need to update the option values after a selection in Django template? For example, <select id="state" type="text" name="state" onChange="update()"> <option value="">Select state</option> {% for state in state %} <option value="{{state.id}}" {{state.name|capfirst}} </option> {% endfor %} </select> After selection of the state I want to update the city queryset according to the selected state. For example, if anyone select California as their state, I want to just give the options of the cities that are inside California state. <select id="city" type="text" name="city"> <option value="">Select city</option> {% for city in city %} <option value="{{city.id}}" {{city.name|capfirst}} </option> {% endfor %} </select> Can anyone suggest what would be the best way to approach this? -
representing generalization/specialization in django
I am new to Django, and I am working on my models, but I don't know exactly how I am gonna represent the generalization relationship in Django, I was following the method of creating the superclass table and all the subclass tables while the subclass tables gonna include the primary key of the superclass table, should I represent that as the foreign key in all subclass tables in Django? -
Create an object from a text which represents the class name
I do not know if this is possible but I am storing the output of type(...) in a string. The output is a class created by me: type(...) -> <class 'apps.X.Y.Z.Listings'> I am storing this as a text but later I want to use this to create an object. How can it be done? I used exec and did not worked and also callable says that is False. In which format should I store to be able to convert the string into the class name and instantiate an object? -
Appending to list replaces last item in Django middleware
I have a middleware I'm using to retain route history within my Django app to use with breadcrumbs, but for some reason the last item in the list keeps getting replaced rather than the item appending to the end of the list. ROOT_ROUTE_PATH = '/labels/' class RouteHistoryMiddleware(object): request = None history = None def __init__(self, get_response): self.get_response = get_response def __call__(self, request): self.request = request if 'history' not in request.session: request.session['history'] = [] self.history = request.session['history'] request.session['history'].append(request.path) if len(self.history) == 0: self.request.previous_route = ROOT_ROUTE_PATH elif len(self.history) == 1: self.request.previous_route = request.session['history'][-1] elif len(self.history) > 1: self.request.previous_route = request.session['history'][-2] return self.get_response(request) Illustration of request.session['history'] mutation with above: Open Page A ['/page_a/'] Open Page B ['/page_a/', '/page_b/'] Open Page C ['/page_a/', '/page_c/'] -
Django register form not showing up on admin users when submitted
I want to create a register and login but when I create account in http://127.0.0.1:8000/register/ it doesn't show in admin (http://127.0.0.1:8000/admin/auth/user/) views.py from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth import authenticate, login def register(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'user/register.html', context) def login(request): context = { } return render(request, 'user/login.html', context) urls.py from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('register/', views.register, name = "register"), path('login/', views.login, name="login"), ] user/register.html <form method="POST" action=" "> {% csrf_token %} {{form.as_p}} <input type="submit" name="Create User"> </form> I need help, Thank you! -
Queryset only on the first foreign key linked to the instance
Let's say for example I have these models: class Person(models.Model): name = models.CharField(max_length=50, blank=True, null=True, verbose_name=_('name')) class Keyword(models.Model): value = models.CharField(max_length=50, blank=True, null=True, verbose_name=_('name')) person = models.ForeignKey('Keyword', on_delete=models.CASCADE) I'd like to query on the Person model, where we filter on ONLY the first keyword linked to that person. -
Djang Update Mnagement Command
I am trying to give the command such a way when blacklist is TRUE and active will FALSE, But I am getting all the Blacklist TRUE and Active is FALSE. from django.core.management import BaseCommand from wm_data_collection.models import roses class Command(BaseCommand): help = "Blacklist_TRUE then Active_FALSE." def handle(self, *args, **options): roses.objects.filter(active=False).update(blacklist=True) -
ImportError: attempted rel
I trying make Django4 project. I added new field in modules and when making migrations. I have error: from ..users.models import Profile ImportError: attempted relative import beyond top-level package i have next structure of the project: django/devsearch/devseach/ /project/__init.py | /admin.py | /apps.py | /forms.py | /models.py | /test.py | /urls.py | /views.py /static /users/__init.py /admin.py /apps.py /forms.py /models.py /test.py /urls.py /views.py My files models.py: /project/models.py from django.db import models import uuid from ..users.models import Profile class Project(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) featured_image = models.ImageField(null=True, blank=True, default='default.jpg') id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) demo_link = models.CharField(max_length=2000, null=True, blank=True) source_link = models.CharField(max_length=2000, null=True, blank=True) tags = models.ManyToManyField('Tag', blank=True) vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title /users/models.py from django.db import models from django.contrib.auth.models import User import uuid class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) username = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) short_info = models.CharField(max_length=200, blank=True, null=True) bio = models.TextField(max_length=2000, blank=True, null=True) profile_image = models.ImageField( blank=True, null=True, upload_to='profiles/', default='profiles/user-default.png') social_github = models.CharField(max_length=200, blank=True, null=True) social_twitter = models.CharField(max_length=200, blank=True, null=True) social_youtube = models.CharField(max_length=200, blank=True, null=True) social_linkedin = … -
How i can split in python letters
I have this line of code to split letters ERT , but i need to split all letters , what i can write ? because in my file I have ERT or THUD or YY not just ERT sample_id = int(sample_name[0].split('ERT_')[1]) -
How to upload an CSV file that is created in Django to AWS S3?
I have a Django model that has a FileField, the file has to be saved in AWS S3. models.py: class Search(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='searches') type = models.CharField(max_length=150) keyword = models.CharField(max_length=150) amount = models.IntegerField() date = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=50) results = models.FileField(blank=True, storage=PrivateMediaStorage()) The upload to AWS S3 works when I create a new object in the admin area and upload a file there. However, I want to create a CSV file in the backend and upload it to S3 from there, not using any form.Inside the backend function: with open(f'results{search_id}.csv', 'w', newline='') as f: writer = csv.writer(f) header = ['name', 'email', 'follower_count', 'play count', 'share count', 'comment count', 'has email'] writer.writerow(header) for result in results: data = [result['author_name'], result['author_email'], result['follower_count'], result['play_count'], result['share_count'], result['comment_count'], result['has_email']] writer.writerow(data) # Updating database data search = Search.objects.get(id=search_id) search.status = 'Finished' search.results = ContentFile(f) search.save() However, right now this just creates a results.csv file in my Django directory and doesn't upload any file to S3. How can I fix this? -
Fetch Data from database and project it on a Datatable using django/ajax
I just recently learned Django/ajax/datatables. I can project my data using a {%for%} loop and im trying to do the same thing with ajax calls. My view: def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' def getfromServer(request): if is_ajax(request=request) and request.method == "GET": books= Book.objects.all() bookserial = serializers.serialize('json', books) return JsonResponse(bookserial, safe=False) return JsonResponse({'message':'Wrong validation'}) index.html <div class="container"> <table id="books" class="display" style="width:100%"> <thead> <tr> <th>Book</th> <th>Author</th> <th>Genre</th> <th>Date Publishedd</th> <th>Copies</th> </tr> </thead> </table> </div> <script> $(document).ready(function() { $('#books').DataTable({ ajax: { type: "GET", datatype : 'json', url: 'views/getfromServer', }, columns: [ { data: 'name' }, { data: 'author' }, { data: 'genre' }, { data: 'pub_date' }, { data: 'copies' }, ] }); </script> Im pretty sure it kinda works this way but i just cant figure it out . -
change Class property properties (verbose_name exmpl.) from base Django model
I have an abstract class with name and slug field.when i inherit from another class i want to change verbose_name parameter according to that class. How can I set this properties? I want to set the verbose_name parameter of the name field to "foo". but I want to use different parameter data for two different classes. An example: For ProductModel name field verbose_name="Foo" For CategoryModel name field verbose_name="Poo" class BaseProductModel(models.Model): name = models.CharField(max_length=200) slug = AutoSlugField(populate_from="name",unique=True,verbose_name="Slug") class Meta: abstract=True class ProductModel(BaseProductModel): # I want to set the verbose_Name parameter of the name field to "foo". #The two fields (name and slug) come from the inherited (BaseProductModel) class. description = models.TextField(max_length=500,verbose_name="Detay") class CategoryModel(BaseProductModel): # The two fields (name and slug) come from the inherited (BaseProductModel) class. # I want to set the verbose_Name parameter of the name field to "Poo". def __str__(self): return self.name -
Employee roster using HTML, CSS, JS, and Django Framework [closed]
I already have a website that has multiple functions and I want to add a webpage for creating and editing my employee's roster. right now, we are using excel so I want to create a webpage that is excel like so my employees can view their roster online. I need suggestions for a good and free library to do that or if someone knows how to do it using pure JavaScript, I would appreciate that. preferably something that works well with Django. I attached a picture of the current roster to make things clear.