Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django - How to add a comment form at the buttom of a poll
Please help with this. I created a poll app (follow a TraversyMedia tutorial). I want to be able to let user to add a comment along with the poll. I creaded a model "Comment" and from admin area i can set ca commment to a specific question and in front page i can display it alog with the resolts poll from that question. But I don't know how to bring this "comment" form to the user's page so that the user, after choosing one of the poll options, leaves a comment and it is saved together with the poll options. Below you will find my settings. (i created the form.py and set the class etc but i don't know what to do next). Thank you models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('publicat la:') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class Comment(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="comments") comment_text = models.TextField(null=True, blank=True) def __str__(self): return self.comment_text views from .models import Question, Choice, Comment # preluare si afisare intrebari din sondaj def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'sondaj/index.html', context) # afisare optiuni … -
Unable to catch GraphQL error in django testing
I am testing my resolver in graphQl, i am working with django and ariadne library. this is the test i wrote: def test_check_trigger(self): query = """ query GetTrigeer($id: ID!) { trigger(id:$id){ uuid agent threshold } } """ agent = Agent.objects.create( user=self.user, user_address=self.user_address, agent_address=self.agent_address1 ) trigger = Trigger.objects.create( user=self.user, agent=agent, pool=self.pool1, token=Trigger.TOKEN0, threshold=50, state=Trigger.ARMED ) trigger_id = agent.uuid #passing wrong value to get error variables = {"id": str(trigger_id)} with self.assertRaises(GraphQLError,msg="Trigger not found"): self.run_graphql_query( query=query, variables=variables, token=self.token) This is the function i am using to get response from graphql: def run_graphql_query(self, query, token, variables): c = Client(raise_request_exception=True) access_token = token["access"] AUTHORIZATION_HEADER = "HTTP_AUTHORIZATION" AUTHORIZATION_TYPE = "Bearer" headers = {AUTHORIZATION_HEADER: f"{AUTHORIZATION_TYPE} {access_token}"} r = c.post("/graphql/", data={ "operations": json.dumps( {"query": query, "variables": variables} ) }, **headers) return r But i am not able to catch the error, i may be using wrong approach but all i want to do is pass wrong value in query and match error messages as expected, this is error message i am getting in terminal: 617, in resolve_field result = resolve_fn(source, info, **args) File "/home/welcome/agents-platform/services/api/api/auth.py", line 12, in resolve_is_authenticated result = original_resolver(obj, info, **kwargs) File "/home/welcome/.local/share/virtualenvs/api-_WI5du6j/lib/python3.8/site-packages/ariadne/utils.py", line 75, in wrapper return func(*args, **convert_to_snake_case(kwargs)) File "/home/welcome/agents-platform/services/api/stoploss/resolvers.py", line 76, in resolve_trigger … -
python django vs php laravel
I'm a python Django back end developer, applied for a job as back end and they asked me to implement a minimal double-entry accounting system via PHP Laravel, I have not worked on PHP Laravel at all, and have 5 days to accomplish the task, should I dedicate the next 5 days to learn and accomplish the task or it won't be easy mission given that I'm not familiar with the language and the framework. Will my understanding of Django easier the process of learning? Please your input will really help me decide, I'm overthinking it alot. -
Django TypeError : expected str, bytes or os.PathLike object, not list || When adding new object
When I'm in the admin panel and I add this object called Cover I am getting this error. I have the same image, text, and char field in other models without any issue does anybody have a good idea of what is happening? TypeError : expected str, bytes or os.PathLike object, not list https://ibb.co/XzDwsXd But I don't have a list anywhere! Please help! models.py class Cover(models.Model): cover_image = models.ImageField(upload_to="images/", blank=True, null=True) cover_title = models.CharField(max_length=64, null=True) text = models.TextField(max_length=256, null=True) views.py def index(request): if request.method == 'POST': is_private = request.POST.get('is_private', False) message_email = request.POST['message_email'] send_mail( 'New Midas&Co litter and newsletter request from '+ message_email, # subject message_email + ' requests to be notified about upcoming litters.', # message 'Midas & Co Website', # from Email ['midasandcompany22@gmail.com', 'webmasterzzzbot@gmail.com'], # to email ) return render(request, "cattery/index.html", {'message_email': message_email, 'cover':cover}) return render(request, "cattery/index.html") admin.py from django.contrib import admin from .models import Cat, Stud, Queen, Cover admin.site.register(Cat) admin.site.register(Stud) admin.site.register(Queen) admin.site.register(Cover) -
Django TypeError at /admin/login in the admin AppConfig.__init__() missing 1 required positional argument: 'app_module'
I am not able to go to the admin site when I type /admin. With startproject this page should work as far as I know and I cannot find out what is the problem. -
how to make my django api publicily accessible?
I deployed it in the ubuntu server, it is running on localhost port 8000? I tried doing port 80 redirecting to 8000 using IP tables but its not helping -
Restricting user sending one form again and again?
I want to know how to restrict a user that he can't send form again and again, if it submitted already by him. The main goal is like, if I have a form like daily quiz that asks "What is the capital city of Italy?", a user should see it and send an answer once. And restrict a user to send an answer until the new question is active, like "What is the capital city of Germany". Are there any good approach? -
Reliably navigate route history for "back" button Django 4.0.3
On each of my app views, there is a page header with breadcrumbs & a back button to return to the previous view. I'd like to be able to reliably track & navigate the user's routing history to make sure to always send them back to the same view they came from. HTTP_REFERER doesn't factor in the potential of nested views. If you were to navigate from Page A -> Page B - Page C & use the back button on Page C you'd be taken to Page B, and then the HTTP_REFERER would become PAGE_C which sends the user in an infinite loop rather than taking them to Page A on clicking back again. window.history.back() or window.history.go(-1) doesn't consider that someone might be linked directly to Page B in which the back button would then send them to whatever is the previous page in their browsing history throughout the life of that tab, not direct them to Page A. My thought was maybe a middleware could append each route to a list in request.session, however, at this point I'm unsure how I'd detect a back button click to move backwards through this. As well, with this solution, I'm worried …