Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - 'dict' object has no attribute 'email'
I'm unable to change the object value This is the whole function def registration(request): errors = { 'username' : None, 'email' : None, 'password' : None, 'confirm_password' : None } if request.method == "POST": username = request.POST.get("username") email = request.POST.get("email") password = request.POST.get("password") confirm_password = request.POST.get("confirm_password") if(solve(email) != 1): errors.update({'email':'Please enter valid email'}) #errors.update(email='Please enter valid email') #errors['email'] = 'Please enter valid email' #errors.email = 'Please enter valid email' #setattr(errors, 'email', 'Please enter valid email') return HttpResponse("<h2>Hello, {0}</h2>".format(errors.email)) return render(request, "auth/successFullRegistration.html", { 'username' : username, 'email' : email, 'password' : password, 'confirm_password' : confirm_password }) else: userform = UserForm() return render(request, "auth/sign_up.html", {"form": userform}) I have already tried: errors.update({'email':'Please enter valid email'}) Also errors.update(email='Please enter valid email') Also errors['email'] = 'Please enter valid email' Also errors.email = 'Please enter valid email' Also setattr(errors, 'email', 'Please enter valid email') And everytime I get the same error message AttributeError at /registration 'dict' object has no attribute 'email' Request Method: POST Request URL: http://127.0.0.1:8000/registration Django Version: 4.0.3 Exception Type: AttributeError Exception Value: 'dict' object has no attribute 'email' Exception Location: D:\Django\gtunews\registration\views.py, line 29, in registration Python Executable: C:\Python310\python.exe Python Version: 3.10.3 Python Path: ['D:\Django\gtunews', 'C:\Python310\python310.zip', 'C:\Python310\DLLs', 'C:\Python310\lib', 'C:\Python310', 'C:\Python310\lib\site-packages'] Server time: Thu, 26 … -
I am getting duplicate responses in joined contest. I want only single response for every contest
i have worked very hard on this.Please help me out as this is very important. I am not able to find why is it happening. models.py class JoinContestlist(models.Model): user = models.ForeignKey(User,null=True,on_delete=models.CASCADE) contest_no = models.CharField(max_length=100,null=True, blank=True) match_id = models.CharField(max_length=100,null=True, blank=True) spots = models.IntegerField(null=True, blank=True) entry_fee = models.IntegerField(null=True, blank=True) price_pool = models.IntegerField(null=True, blank=True) level = models.JSONField(null=True, blank=True) no_of_team = models.IntegerField(null=True, blank=True) remaining_spots = models.IntegerField(null=True, blank=True) remaining_team = models.IntegerField(null=True, blank=True) views.py POST Function @api_view(['POST']) def post_join_contest_list(request, id, contest_no, match_id): try: if request.method == 'POST': user = User.objects.get(id=id) qs = Contest.objects.get(contest_no=contest_no) cs = MatchList.objects.get(match_id=match_id) serializer = JoinContestlistserializer(qs, data=request.data) ks = JoinContestlist.objects.filter(user=user, contest_no=qs.contest_no, match_id=match_id) if len(ks) < qs.no_of_team: js = JoinContestlist.objects.create(user=user, spots=qs.spots, entry_fee=qs.entry_fee, price_pool=qs.price_pool, level=qs.level, no_of_team=qs.no_of_team, contest_no=qs.contest_no, match_id=cs.match_id) js.save() return JsonResponse({"status": True, "message": "success"}) return JsonResponse({"status": False, "message": "Contest is full"}) except: return JsonResponse({"status": False, "message": "Service temporarily unavailable, try again later"}) GET Function @api_view(['GET']) def get_join_contest_list(request, id, match_id): try: if request.method == 'GET': # import pdb # pdb.set_trace() user = User.objects.get(id=id) cs = JoinContestlist.objects.filter(user=user, match_id=match_id) json_data_2 = [] json_data_4 = [] json_data_1 = [] for k in cs: qs = JoinContestlist.objects.filter(match_id=k.match_id, contest_no=k.contest_no) ds = JoinContestlist.objects.filter(user=user, match_id=k.match_id, contest_no=k.contest_no) a = len(qs) b = len(ds) remaining_spots = k.spots - a remaining_team = k.no_of_team - b json_data_1.append({ … -
I can't render page in Django
As in subject I have a problem when I try to open register page. I am trying to add registration with google. I get following Error: Error during template rendering In template C:\Users\Łukasz\PycharmProjects\Home_Concept\hc_web\HTML\registration\register.html, error at line 13 Some helpfull information about error. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/register/ Django Version: 4.0.4 Python Version: 3.10.4 Installed Applications: ['database', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Łukasz\PycharmProjects\Home_Concept\hc_web\HTML\registration\register.html, error at line 13 Google 3 : {% block content %} 4 : 5 : {% load socialaccount %} 6 : {% load static %} 7 : 8 : <div class="container mx-5"> 9 : 10 : 11 : <div class=" signin text-center"> 12 : 13 : <a href=" {% provider_login_url 'Google' %} " class="text-dark"> <img src="{% static 'btn_google_signin_light_normal_web@2x.png' %}" style="width:14rem; height:auto"></a> 14 : </div> 15 : 16 : <br><br> 17 : 18 : <div style="width: 100%; height: 15px; border-bottom: 1px solid lightgray; text-align: center"> 19 : <span class="text-muted" style="margin-top:-15% !important; font-size: 11px; background-color: white; padding: 0px 10px;"> 20 : OR 21 : </span> 22 : </div> 23 : Traceback (most recent call last): File "C:\Users\Łukasz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\handlers\exception.py", line 55, … -
What is more flexible way to organize User authentication model in Django?
I've started working on a new project and I would like to know what is more flexible and changable (improvable) way to work with User model? At first I want to make my project oriented towards employees of the company to allow them manage products and other entities. And then I want to expand the project by letting customers to register in the system and buy stuff. But of course I want employees and customers to have different fields and restrict customers from having access to certain parts of the system. Django offers two ways of dealing with Users: it's either Substituting a custom User model or Extending the existing (default) User model. I can't decide what way to go to have two kinds of users in the future. -
My Django code (forms and models) works just fine, but It's definitely a bad choice for large amounts of data. Would appreciate suggestions
this code works just fine when registering users and adding them to the database. With additional code in the template, it also shows the users that their chosen username/email already exists pretty well. However I am mostly certain that this code's quality is very bad, since It woudn't work well with large databases, since I search for all the users and their usernames/email. Then again, I don't know how to add better validation. I decided to add these validators(passwords excluded) because, unique=True in models have no effect on the forms. What I mean is, before these codes, if I registered with the same username and email over and over, if the passwords matched, the last password that I entered got added to the database(user number stayed the same), but form was considered valid (I think) and It didn't show any errors to the user. This is the best I came up with, but I'm pretty sure it's a bad one. I am taking any suggestions, what other kind of validation can I add to fix the mentioned problem. I thought unique=True would fix things, but apparently it's not enough. Note that I am also a beginner and if this question … -
How to create a class in django which will be deleted when the element in another class is deleted
I am new to python and django please help me with this doubt .How to create a class in django which will be deleted when the element in other class is deleted ? -
why css is not working correctly in download template
I am trying to use free templates for my website using Django, but it's working correctly. -
Using class based views in showing products by category
I am making a ecommerce website and want to display my products by category. Whereby products of the same category are displayed in one card. I am developing it in django but want to inquire if there is a way i could do this in class based views. since in my home page i used ListView. This is how my views.py looks like: from urllib import request from django.shortcuts import redirect, render, get_object_or_404 from account.models import Account from django.views.generic import ListView, DetailView, View from django.utils import timezone from homeapp.forms import SearchForm from homeapp.models import * from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.decorators import login_required class HomeView(ListView): paginate_by = 5 model = Product template_name = 'homeapp/home.html' class CartView(DetailView): model = Product template_name = 'homeapp/product.html' class shopView(LoginRequiredMixin, View): login_url='/account/login/' def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'homeapp/cart.html', context) except ObjectDoesNotExist: return redirect("/") @login_required(login_url='/account/login/') def add_to_cart(request, slug): product = get_object_or_404(Product, slug=slug) order_product, created = OrderProduct.objects.get_or_create(product=product, user=request.user, ordered=False) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.products.filter(product__slug=product.slug).exists(): order_product.quantity += 1 order_product.save() messages.info(request, "This item quantity was updated.") return redirect("homeapp:cart") else: order.products.add(order_product) messages.info(request, "This item was … -
Django: Global Exception Handler
I'm looking to create a global exception handler in a Django project. I've looked into the DRF middleware, but I want to capture all unhandled exceptions from functions in my project not just from requests/response, and log the details of the error(line, function, etc.). From there, I tried overriding sys.excepthook in manage.py but the traceback shows that it was invoked by manage.py. It does not show the actual function that caused the error. in manage.py: def exception_hook(exc_type, exc_value, tb): logger = logging.getLogger('django') logger.error(sys.exc_info(), exc_info=True) if __name__ == '__main__': sys.excepthook = exception_hook main() LOGGING in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '{levelname}; {asctime}; {module}; {filename}; {funcName}; {message}; {lineno}; {exc_info}', 'style': '{', }, }, 'loggers': { 'django':{ 'handlers': ['file'], 'level':os.getenv('DJANGO_LOG_LEVEL','INFO'), 'propagate': False, } }, 'handlers':{ 'file':{ 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'debug.log', 'formatter': 'standard' } } } Is there a way to do this properly or is the code missing something? -
Custom Django Form Widgets
I have a field for which I am populating data using js. The data in user field is being populated from view using ajax call. I want to create a custom widget which can be used to filter and select the values. like the TypedChoiceField Widget; I want to create TypedSelectField that can be used to filter and select from the options that are populated. user = forms.CharField(widget= forms.Select(),required=True) Any ideas on how to create such custom widget. I tried overriding forms.ChoiceField but it is not working. -
A table of MySQL database asociated to Django App is "corrupted"
I have problem that has never happened to me before. It is an application made with Django that has never given me errors. For some reason, a table in the database (MySQL) is corrupted, but the app is still working. However, when I make a call like this: queryset = Tuition.objects.filter(agent = user) Then, the database gives me this error: django.db.utils.OperationalError: (1712, 'Index base_tuition_agent_id_b1b4dfb6_fk_base_staff_user_ptr_id is corrupted') But, if I change the call to: queryset = Tuition.objects.filter(Q(date__lte="1900-01-01")|Q(agent__id=90)) Then, There is no error... Surprise! (Obviously in the database there is no date prior to 1900 so both functions are similar). But, if I change the call to: queryset = Tuition.objects.filter(Q(date__gte="1900-01-01")&Q(agent__id=90)) Then, the database through the error again... So: If I filter by "agent" doesn't work. If I filter with an "OR" conditional combining the "agent" field with another one it works. If I filter with an "AND" conditional combining the "agent" field with another one doesn't work. You can see the details of the table here: I don't know much about MySQL and would like to know how the result of the above calls is possible. Because from my ignorance, the normal thing would be that none of them work, or well, … -
Django: How to use OuterRef() for .get() in annotate?
I am using django-treebeard and use a model that allows recursive relations. So, I need to count the number of my descendants using .annotate(), but To get it, you need to go through .get() once, as shown below. However, in that case, OuterRef("pk") does not seem to work and the following error occurs. This queryset contains a reference to an outer query and may only be used in a subquery. What can I do to solve this problem? queryset.filter(post=post) .annotate( reply_count=Count( Comment.objects.get( pk=OuterRef("pk") ).get_descendants() ) ) -
Allow user to fill only one of the fields not both | Django
I'm creating an app like reddit where you can post videos and texts. I want to let the user choose between video and image field but not both here is what I've done: class CreatePostForm(ModelForm): class Meta: model = Post fields = ['title','video','image','text'] widgets ={'title':forms.TextInput({'placeholder':'تیتر'}), 'text':forms.Textarea({'placeholder':'متن'})} def clean(self): cleaned_data = super().clean() text = cleaned_data.get("text") video = cleaned_data.get("video") if text is not None and video is not None: raise ValidationError('this action is not allowed', 'invalid') this shows the validationError but even when the user only fills the video fileField and not the texField it still shows the validationError -
Send image as a JSON with Pytest
I have a DRF POST endpoint that accepts some data + image, my question is how can I test this endpoint using something like Pytest, I'm facing a prob with sending images as a JSON, I tried to use PIL but didn't work. serializer class CreateCategorySerializer(serializers.Serializer): title = serializers.CharField(max_length=255) description = serializers.CharField(max_length=500, required=False) priority = serializers.IntegerField(default=0) image = serializers.ImageField() test @pytest.mark.django_db def test_name_exist(authenticate_superuser, category): data = { "title": "CAT 1", "description": "Description", "priority": 20, "image": "??" } response = authenticate_superuser.post(reverse('category_admin:create'), data=data) assert response.status_code == status.HTTP_400_BAD_REQUEST assert response.data['detail'] == 'This title already exists' -
How to do SSO between Wordpress and Django?
Is it possible to do SSO with WordPress and Django as I have found old documentation related to SSO between WordPress and Django? Is there any implemented example or documentation from which I can get help Thanks -
Django - Log response for each request
I have an API built using Django framework . I have to log the following datapoints for each time a request hits the API. Request Method Request Path Request object Response Status code Response Latency (if possible) I tried using the request_finished signal but it does not bring the response object with it. How can I accomplish this? -
Vue.js-Failed to load resource: the server responded with a status of 401 (Unauthorized)
I'm currently working on a project that collects payment info(like the products the client wants to buy, and how much that product costs) and client details(client name, client address, client credit card info, etc.) and I need to access Stripe's online payment system for the purchase. However, during my trial run, every time I try to click all "Pay", I keep getting notifications that something went wrong. I checked the terminal and it keeps displaying this error: Failed to load resource: the server responded with a status of 401 (Unauthorized) I'm also using Django's rest framework for my backend development, and it keeps displaying this HTTP 401 Unauthorized Allow: POST, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Token { "detail": "Authentication credentials were not provided." } This is the code I think the problem is located in: <template> <div class="page-checkout"> <div class="columns is-multiline"> <div class="column is-12"> <h1 class="title">Checkout</h1> </div> <div class="column is-12 box"> <table class="table is-fullwidth"> <thead> <tr> <th>Product</th> <th>Price</th> <th>Quantity</th> <th>Total</th> </tr> </thead> <tbody> <tr v-for="item in cart.items" v-bind:key="item.product.id"> <td>{{ item.product.name }}</td> <td>{{ item.product.price }}</td> <td>{{ item.quantity }}</td> <td>₱{{ getItemTotal(item).toFixed(2) }}</td> </tr> </tbody> <tfoot> <tr> <td colspan="2">Total</td> <td>{{ cartTotalLength }}</td> <td>₱{{ cartTotalPrice.toFixed(2) }}</td> </tr> </tfoot> </table> </div> <div class="column is-12 … -
TypeError: context must be a dict rather than module
I am trying to follow along with a tutorial for Django. link In my views.py in the folder articles def article_create_view(request): # print(request.POST) if request.method == "POST": title = request.POST.get('title') content = request.POST.get('content') print(title, content) article_object = Article.objects.create(title = title, content = content) context['object'] = article_object context['created'] = True return render(request, "articles/create.html", context= context) articles/create.html is the following code: {% extends "base.html" %} {% block content %} {% if not created %} <div style="margin-top:30px;"></div> <form method = "POST"> {% csrf_token %} <div><input type = 'text' name ='title' placeholder = 'Title' /></div> <div><textarea name ='content' placeholder ='Content'></textarea></div> <div><button type='submit'>Create article </button></div> </form> </div> {% else %} <p> Your article was created</p> <a href="/articles/{{object.id}}/"> {{object.title}} - {{object.content}}</a> {% endif %} {% endblock content %} I am getting this error: TypeError: context must be a dict rather than module. [26/May/2022 15:06:36] "GET /articles/create HTTP/1.1" 500 81512 -
Django admin static files need to be redirected to different path
I am sorry if I am asking this question again. But I did try to find the answer without success. My static files of the admin page seem to be in different location then it is looking for them. How can change the location of where it should look? I could move the admin static folder but that would to much hassle if I make changes, right? Thanks -
POST Request to HTTPS(SSL) url from Android/Java
I am pretty new to Java and Android. Working on Python all the time. I am trying to make an Android Apps via Android Studio BumbleBee (2021.1.1 Patch 3) that can make GET and POST request to a https(SSL) server. The server is run by Django 3.2, deploy on IIS(version 10.0) powered by Window Server 2019. GET requests are fine but POST requests are not! What i am trying to do is to make a POST request to login to the website. My idea is to send a GET request to obtain the csrftoken and csrfmiddlewaretoken for subsequent POST request. (From my understanding, Django POST requires csrfmiddlewaretoken in the POST data and csrftoken in the cookies). Everything works fine when i tried on http://localhost:8000 OR i use @csrf_exempt decoration on both HTTP and HTTPS(SSL) server. But the actual server which run by Django is HTTPS(SSL) instead of HTTP and i want to remain the csrf function. Since i keep failing on Android Studio, I tried to make POST request to https by Java(on Eclipse IDE Version: 2022-03 (4.23.0)) and it keeps returned an error of 403. I tried with SSL Socket Factory in Java but still it does not work. … -
how to show many nested childs in a queryset in efficient way, for loops dont work
I have created two models, 1st is Book and 2nd is SubBookPart (Sub Part of Book) User creates a book first then add its sub part like "Chapter 1", "Chapter 2" and so on to that book then add "Page 1", "Page 2" and so on to each chapter then add "Paragraph 1", "Paragraph 2" and so on to each Para I successfully does this My Book Look Like This BookName |- Chapter 1 |- Page 1 |- Paragraph 1 |- Paragraph 2 |- Paragraph 3 |- Page 2 |- Paragraph 1 |- Paragraph 2 |- Paragraph 3 |- Chapter 2 |- Page 1 |- Paragraph 1 |- Paragraph 2 |- Paragraph 3 |- Page 2 |- Paragraph 1 |- Paragraph 2 |- Paragraph 3 |- Page 3 |- Paragraph 1 |- Paragraph 2 |- Paragraph 3 But I dont know how to show it in frontend, because it will take very very long nested for loop, Is There and other way models.py class Book(models.Model): name = models.CharField(max_length=50) subparts = models.ManyToManyField("SubBookPart", related_name="book_subparts", blank=True) class SubBookPart(models.Model): # for only first sub part subpart_of_book = models.ForeignKey(Book, on_delete=models.CASCADE,null=True, blank=True) # for only non-first sub parts, giving reference to previous subpart subpart_of = models.ForeignKey("SubBookPart", … -
Django - a.html include b.html file which is not located in the template folder
I have two htmls a.html and b.html. a.html is located in the template folder by default. b.html is located in appname/static/images/b.html In a.html, I am trying to include b.html but it's not working, unless b.html is in the same template folder. <body> {% include 'appname/static/images/b.html' %} </body> questions: how to include b.html? how to include b.html dynamically if it's in different folder, e.g. images/username/b.html where username is different. -
nested serializer error. 'str' object has no attribute 'values'
i am currently working social media type app where i wants to get the group detail and users detail which are posted the post. the problem is occure when i used nested serializer in post serializer the group serializer is working perfectly when i write the user serialize it gives the following error packages/rest_framework/serializers.py", line 368, in _readable_fields for field in self.fields.values(): AttributeError: 'str' object has no attribute 'values' [26/May/2022 09:01:21] "GET /group/posts/3 HTTP/1.1" 500 123293 Here is my models and serialzers post model class Post(models.Model): post_data = models.FileField(upload_to='group_post', null=True) post_description = models.TextField(null=True,blank=True) post_time = models.DateTimeField(auto_now=True) post_group = models.ForeignKey(to='Group', on_delete=models.DO_NOTHING, related_name='post_group') post_user = models.ForeignKey(to=MyUser, on_delete=models.DO_NOTHING, related_name='post_user') class Meta: db_table = "group\".\"Post" post serializers class PostSerializer(serializers.ModelSerializer): post_group = GroupSerializer(read_only=True) post_user = UserSerializer(read_only=True) class Meta: model = Post fields = '__all__' user Model class MyUser(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(verbose_name='Enter Email', max_length=50,unique=True) password = models.CharField(max_length=1000) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) user serialzer class UserSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = '__all__' -
How can I do a redirect in Django and React?
I need to do a redirect right after pressing a button. <Button onClick={changeCalendar}>Integrate Google Calendar</Button> So I'm sending a request to a server to do the redirect const changeCalendar = async () => { let response = await fetch("http://localhost:8000/gcalendar/", { mode: "no-cors", method: "GET", headers: { Authorization: "Bearer " + String(authTokens.access), }, }); On the server side I process the request, and get a URL def change_calendar(request): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES) flow.redirect_uri = 'http://localhost:3000/' authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') return redirect(authorization_url) If I print authorization_url it looks like this: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=**ID**&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.events&state=**STATE**&access_type=offline&include_granted_scopes=true If I copy and paste the link into a Google search, it opens a Google authorization window. I need to do the same one through code. But redirect doesn't work. Even if I try to do a redirect to other links. -
create custom mixin in DRF
I want to create custom mixin in Django Rest Framework, which will return data in CSV format. This to_csv method should convert fields to CSV format class ToCSVMixin: @action(detail=False, methods=['get']) def to_csv(self,request): fields = None /* some stuff here to convert fields list to CSV */ Problem is that I'm not sure how to use to_csv method in view. fields list should be populated in MyViewSet class MyViewSet(ModelViewSet,ToCSVMixin): /*.... */ Thank you in advance