Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
suppress form field errors in Django
I have my form (code below) - it's working perfectly. But it's showing the form field errors, even before it's been submitted (on page load!). Is there a way to supress the errors, if the form hasn't been submitted? <form method="post"> {% csrf_token %} {% for field in form %} <p> <font color = 'white'>{{ field.label_tag }}</font> <br>{{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> </form> -
Testing a custom auth backend with Django RestFramework
I created a custom authentication backend for my DRF application. I can't figure out how to test it. Calling the client.post calls my authenticate function (cause that's in my view) But I need to mock an internal method in my ModelBackend. Kinda confused how to go about this? View: class Web3UserToken(APIView): authentication_classes = [] permission_classes = [] def post(self, request, **kwargs): public_address = request.data["public_address"] web3 = Web3Backend() user, token = web3.authenticate(request) if token: return JsonResponse({'token': token}) else: return Response({'message': 'Missing token'}, status=400) Test: class TestWeb3AuthBackend(APITestCase): def setUp(self): #TODO: set up test user self.client = APIClient() #self.factory = APIRequestFactory() def test_authenticatepasseswithexistinguser(self): self.user = Web3User(public_address=TEST_PUBLIC_ADDRESS) auth_backend = Web3Backend() import ipdb; ipdb.sset_trace() request = self.client.post('/api/token/', {'public_address': TEST_PUBLIC_ADDRESS, 'nonce': '0xsomething_random'},follow=True) with mock.patch.object(auth_backend, '_check_nonce', return_value=True) as method: token, user = auth_backend.authenticate(request) self.assertTrue(token) self.assertTrue(user) -
Validation not working, defined max and error message but even then not working
I want that participant can not place bid for more than the remaining fund. If he has invested in 30 each in first three rounds, he can not invest more than 110 in the next round.(200-3*30) I am not getting any error while running this, but validation is not working, the error message is not popping up. even if the first investment bid is more than 200. I want that total bids compiled for all rounds should not cross the budget given initially. Please help class Constants(BaseConstants): name_in_url = 'C' players_per_group = None num_rounds = 18 budget = 200 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): invest = models.IntegerField( label="How much would you like to invest in this proposal?", min=0 ) total_invest = models.IntegerField() # PAGES class MyPage(Page): form_model = 'player' form_fields = ['invest'] @staticmethod def total_invest(player: Player): player_in_all_rounds = player.in_all_rounds() return sum([p.invest for p in player_in_all_rounds]) @staticmethod def avail_invest(player: Player): return Constants.budget - player.total_invest @staticmethod def invest_error_message(player, value): print('value is', value) if value > player.avail_invest: return 'Cannot invest more than your remaining fund' class ResultsWaitPage(WaitPage): pass **strong text** class Results(Page): pass page_sequence = [MyPage] -
Simulate server restart in Django tests
I am working on a package for caching Django querysets in redis. I want to simulate server restarts in tests so I can see if the objects are still cached after server restars. Package -
embedding jupyter notebook/ google colab in djnago app
I wanted to build a website and embed the jupyter notebook functionality of being able to create cells and run python code within it into my website For creating a website I m using Django and I would like to embed either the google collab or jupyter notebook By the way I have researched enough and have been stuck with the StackOverflow links where there no answer about this or the one where they want to use django in jupyter notebook Thanks in advance for any guidance or any reference that you guys can provide. -
Django Gmail auth fails despite correct credentials
My sending mail from django through gmail suddenly stopped working. It was working fine for over a year now, so I assume my basic setup should still be fine. The Google Account in question has 2FA enabled and the password used in the config below is a generated app-password, not the main accuont password. I already logged into Gmail via browser and checked that it hasn't been locked and that it isn't over quota. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = '<MY-MAIL-ADDRESS>' EMAIL_HOST_PASSWORD = '<PASSWORD>' DEFAULT_FROM_EMAIL = '<MY-MAIL-ADDRESS>' I already verified my credentials by using the command below: (ofc shell expansion doesn't work i just pasted the output of the command at that location) $ openssl s_client -connect smtp.gmail.com:587 -starttls smtp >AUTH PLAIN $(echo -ne '\0MY-MAIL-ADDRESS\0PASSWORD' | base64) >235 2.7.0 Accepted However, if I try to use send_mail it bounces: In [1]: from django.core.mail import send_mail In [2]: send_mail('Subject', 'This is a test message', 'MY-MAIL-ADDRESS', ('recipient@address.com',)) (Output shortened) SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials r17sm9826202wmq.5 - gsmtp') Any hints on what might (suddenly) be wrong? -
Django - TypeError: put() missing 1 required positional argument: 'filename'
I am trying to upload a pdf file or a pickle file through an API made in Django using FileUploadParser. However, when making the API call using postman using the put method, I get the following error, even using the right HTTP header: TypeError: put () missing 1 required positional argument: 'filename' Here is how it looks my POSTMAN header and body: views.py urls.py -
Can security vulnerabilities in npm packages be of concern for a ReactJs/Django website?
I am developing a website with React.js frontend and Django backend. After updating all npm packages to their newest versions and performing npm audit fix, I still get the following message from npm audit: found 14 vulnerabilities (8 moderate, 5 high, 1 critical) run `npm audit fix` to fix them, or `npm audit` for details I wonder whether I should be concerned about these vulnerabilities, given that they concern only the frontend? When I wrote the backend, I always assumed that an ill-intending user can substitute the frontend and submit any request whatsoever to the backend. -
Deploying asgi django on heroku
I'm unable to deploy asgi django on heroku. Build is successful but it shows Application Error after deployment. Here is my procfile Here is my asgi file here is routing.py here is settings.py Also i've no add-ons on heroku. Please help me out how can i deploy it on heroku. Your any advice would be highly appreciable. Thank you in advance -
Django virtual environment wrong directory
I need help with setting up my virtual environment for Django. I am creating a virtual environment for the Django directory, as shown in the picture. But somehow the virtual environment is created in the gurtaj directory. -
TypeError at /accounts/signup/ View.__init__() takes 1 positional argument but 2 were given
I am using Django allauth to authenticate users to signup and login. But this error TypeError at /accounts/signup/ View.__init__() takes 1 positional argument but 2 were given comes up as I try to access django allauth signup and login templates. callback <class 'allauth.account.views.SignupView'> callback_args () callback_kwargs {} middleware_method <bound method CsrfViewMiddleware.process_view of <django.middleware.csrf.CsrfViewMiddleware object at 0x0000017B8F25B070>> request <WSGIRequest: GET '/accounts/signup/'> response None self <django.core.handlers.wsgi.WSGIHandler object at 0x0000017B8DF32290> wrapped_callback <class 'allauth.account.views.SignupView'> -
Django 3.2 - querie multiple Models in view (SQL comparison)
I'm quite new to django and have problems with the ORM and the view-queries. We have already migrated and synched some Models from our productive DB to the django DB, but I have problems with connecting two Models to each other. e.g. models.py: class SsdgSendung(models.Model): sdg_sdgid = models.CharField(primary_key=True, max_length=30) sdg_konz = models.CharField(max_length=12, blank=True, null=True) class Meta: db_table = 'ssdg_sendung' class SsdaSdgadr(models.Model): sda_sdgid = models.ForeignKey(SsdgSendung, on_delete=models.CASCADE, blank=True, null=True) sda_satid = models.CharField(max_length=4, blank=True, null=True) class Meta: db_table = 'ssda_sdgadr' unique_together = (('sda_sdgid', 'sda_satid'),) Sample Data SsdgSendung: sdg_sdgid = BL-1237781-BL-1 sdg_konz = 009874 SsdaSdgadr: sdg_sdgid = BL-1237781-BL-1 sda_satid = IV sdg_sdgid = BL-1237781-BL-1 sda_satid = CN How should the correct "django"-query look for this equivalent SQL: SELECT * FROM SsdgSendung inner join SsdaSdgadr on sdg_sdgid = sda_sdgid and sda_satid = 'IV' WHERE sdg_konz = '1234' I tried this, but I don't get any result on the template: Sendungen = SsdgSendung.objects.filter(sdg_konz = current_user_konz).order_by('-sdg_datum').prefetch_related('sda_sdgid') template {% for la_item in SDG_Overview %} <tr> <td>{{ la_item.sdg_sdgid }}</td> <!-- works well --> <td>{{ la_item.sda_satid }}</td> <!-- don't work --> </tr> -
Django How to connect in local network to my chatt app (channels and redis)
I've implemented the Stein example! https://codewithstein.com/django-realtime-chat-app-tutorial-simple-django-tutorial-with-channels-and-redis/ It works! However, only on my computer! If I try to connect to the local network from another computer, nothing comes out. Earlier, when it was just WSGI, I connected. I think there is also docker involved. That my settings: docker run -p 6379:6379 -d redis:5 - ((I thing this note is wrong for local network) CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('192.168.1.126', 6379)], - my local ip # ('127.0.0.1', 6379) }, }, And last command what i use: python manage.py runserver 192.168.1.126:8000 -
Error with authentication (Django Rest Framework + JWT Auth)
I've been working on my first Django Rest Framework project and I'm having some trouble getting my JWT authentication to work properly. Upon logging into my (React) app, everything works as intended, but when coming back to the app after several hours and doing something in the site that requires authentication, I get the following error instead of the token being refreshed or redirected to my login screen. I'm totally new to authentication, and my code for my JWT Auth is taken from this tutorial, so I'm not completely sure if I've goofed something up or if the tutorial code isn't working properly. I suspect the issue is on the front-end, so here is my axios file where I handle the token refreshes (again, taken from the tutorial code) https://github.com/aesakof/gas-app-v2/blob/main/react-frontend/src/axios.js One issue that is probably notable and that I changed from the tutorial's code is that on line 9 of that file, I changed it to "Bearer " from "JWT " as with JWT I was getting not authorized errors when making requests. As I said I'm very new to JWT and working with authentication in general, so any help would be greatly appreciated! -
How do I go about putting my image classifier in a django server, so various appliances can access it?
I recently created an image classifier for an application, but it turned out to be a way larger of a file than I anticipated, so I looked up on various ways to find a way of compressing it, but that was in vain. So I thought of creating a django server where I could store this classifier, which I could then access with any device. I looked up tutorials, on exactly what I want, but they were all just full django tutorials. So im kinda stuck at this point, so can someone help me with what im exactly supposed to learn/do? Thanks! -
Django Rest Framework - An invalid form control with name='' is not focusable
I've been working with DRF HTML & Forms. I've encountered an issue while playing with it, and I was wondering if that has already happened before. The issue is related to this topic in Stack Overflow. Basically, I'm capable of rendering the form with the prepopulated data, but when it comes to sending the PATCH request to update. I get this: An invalid form control with name='name' is not focusable. An invalid form control with name='jobTitle' is not focusable. An invalid form control with name='salary' is not focusable. Here my requirements.txt: djangorestframework==3.12.4 # https://github.com/encode/django-rest-framework django-cors-headers==3.10.0 # https://github.com/adamchainz/django-cors-headers django==3.2.9 Here is my view.py: class UserRetrieveUpdateView(RetrieveUpdateAPIView): renderer_classes = [TemplateHTMLRenderer] permission_classes = [IsAuthenticated] template_name = "users/modals/user_modal_update.html" queryset = UserPie.objects.all() serializer_class = UserPieSerializer lookup_url_kwarg = "user_pk" def get(self, request, user_pk): user = get_object_or_404(UserPie, pk=user_pk) serializer = self.get_serializer(user) return Response({"serializer": serializer, "user": user}) Here is my template: {% load static %} {% load rest_framework %} <div class="modal fade" id="userFormModalUpdate" tabindex="-1" aria-labelledby="userFormModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="userFormModalLabel">Update existing user</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form id="formUser" action="{% url 'users:form' user_pk=user.pk %}" method="patch"> {% csrf_token %} {% render_form serializer %} </form> </div> <div class="modal-footer d-flex justify-content-center "> <button type="button" … -
I want to simulate/mimic an "external API" which will send certain responses to my Django project?
I am creating a web application for data visualizations and analytics. I am using Django for that purpose. Now the problem is that, in normal circumstances, this project will take its data (for visualizations purposes) from an external API owned by someone else. And for me to access that API I need to prove my identity and go through many formalities. To avoid this time-gap, I want an app to mimic those external APIs. Basically I want to tell the mimic to throw certain Responses on certain API endpoints. I heard that "Postman" is good for the purpose but don't have any idea even if it will help me. I'm also open to any alternatives, if any. P.S. I'm new to all this web-app stuff so I have no idea If my question is valid. Im working on Windows 10 platform Also this is an educational project by the way. It is not meant for any profit. -
Django: filter ManyToManyfield of all objects in QuerySet
I basically want to do something like this: I want a distinct list of all products from all completed orders, but I want to save/annotate? the order reference('refCode') to the Product object. Order.objects.filter(is_completed=True).order_by('-date_created').products.all().filter(dlLocation__isnull=True).distinct() Notice the ".products.all()". Unfortunately this is no valid code. So my solution was to make 2 seperate querysets like so: completedOrders = Order.objects.filter(is_completed=True).order_by('-date_created').values_list('refCode', 'products', named=True) #<QuerySet [Row(refCode='7822788', products=307691), Row(refCode='7822788', products=307905) Row(refCode='4083860', products=307874)]> downloads = Product.objects.filter(topicID__in=completedOrders.values('products')).filter(dlLocation__isnull=True).distinct() #<QuerySet [<Product: product12>, <Product: product43>, <Product: product35>> How can I insert a Product object on its matching topicID in completedOrders Row dict? The result could be something like this: #<QuerySet [Row(refCode='7822788', products=<Product: product12>), Row(refCode='7822788', products=<Product: product43>) Row(refCode='4083860', products=<Product: product35>)]> Order models.py: class Order(models.Model): refCode = models.CharField(max_length=15, unique=True, primary_key=True, default=generateOrderRefCode) products = models.ManyToManyField(Product) is_completed = models.BooleanField(null=False, default=False) Product models.py: class Product(models.Model): topicID = models.IntegerField(null=False, unique=True, primary_key=True) dlLocation = models.CharField(max_length=200, null=True, blank=True) Excuse me for my bad explanation and grammar faults, this is the first time I have to ask a question to StackOverflow and my head is basically broken from working on this project too long, or I am going crazy lol. Thank you in advance and I wish u a life filled with love and joy <3 -
Form is invalid but no errors
Whenever I submit the form, it is invalid and there is no error message attached to it when I try to read it with form.errors; it's empty. Here is what I have: models.py class Project(models.Model): project = models.CharField(unique=True, max_length=50) is_active = models.BooleanField(default=False) forms.py from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Row, Column, Submit, Field class SelectProjectForm(forms.Form): def __init__(self, active_choices, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['is_active'] = forms.ChoiceField(choices=active_choices, widget=forms.Select) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.layout = Layout( Row( Column(Field('is_active')) ), Row( Column(FormActions(Submit('activate', 'Activate Project'))) ), ) views.py class ProjectSettings(LoginRequiredMixin, TemplateView): template_name = 'Home/project_settings.html' def get(self, request, *args, **kwargs): active_choices = [] for project in Project.objects.all(): active_choices.append((project.id, project.project),) return render(request, self.template_name, {'create_project_form': ProjectSettingsForm(), 'form': SelectProjectForm(active_choices)}) def post(self, request, *args, **kwargs): if 'activate' in request.POST: form = SelectProjectForm(request.POST) if form.is_valid(): .... messages.error(request, 'Something went wrong') return redirect('project_settings') I think the problem might be in the POST method in views where I initialize the form, but I don't know how to pass the active_choices parameter in post. If that is not the problem then I am lost. -
Django how to split data by unique key using dynamic URL?
I am making Django API. I collected place and review data using crwaling program. I want to split review data by place name, but it seems all reviews are saved together and is spread to all URL. models.py from django.db import models import uuid # Create your models here. from django.utils.text import slugify def generate_unique_slug(klass, field): origin_slug = slugify(field, allow_unicode=True) unique_slug = origin_slug numb = 1 while klass.objects.filter(slug=unique_slug).exists(): unique_slug = '%s-%d' % (origin_slug, numb) numb += 1 return unique_slug class BuildingData(models.Model): building_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50, unique=True, allow_unicode=True, default=uuid.uuid1) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) #building_time = models.CharField(max_length=50) def save(self, *args, **kwargs): if self.slug: # edit if slugify(self.building_name, allow_unicode=True) != self.slug: self.slug = generate_unique_slug(BuildingData, self.building_name) else: # create self.slug = generate_unique_slug(BuildingData, self.building_name) super(BuildingData, self).save(*args, **kwargs) class ReviewData(models.Model): building_name = models.CharField(max_length=50) review_content = models.TextField() star_num = models.FloatField() urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<str:slug>/', ReviewListAPI.as_view()) ] A part of crwaling program if __name__=='__main__': for item in building_dict: BuildingData(building_name = item['place'], building_loc = item['location'], building_call = item['call']).save() #BuildingData(building_name = item['place'], building_loc = item['location'], building_call = item['call'], building_time = item['time']).save() for item in … -
How to disable cookies for all-auth cookie in safari
I implemented social login in django. In settings.py i added "allauth.socialaccount.providers.google", On the site i added a button google signin. When i use chrome as a browser everything works fine, the user is signed in over and over again. However with safari i have a problem. The first time when ik log in with the google sign in the user is logged in fine. But when i log out the user and try to login again in django its giving me a this error " Social Network Login Failure An error occurred while attempting to login via your social network account." The solution seems to be to delete the cookie in safari of my site. If i then login again its working fine. Is it possible to disable the cookie for allauth ? -
How to escape '/' in django urls
I am working on a project that generates dynamic urls for eg if you type mysite.com/<yourtexthere> The site should generate a url with mysite.com/yourtexthere (where yourtext here is a slug of a model)and I am able to do that but the problem arises when I put something like this mysite.com/yourtexthere/moretext, Django doesn't match it with any of my existing URL patterns and gives me 404. I wanted to ask is there a way by which I can treat '/' as just another character and generate unique url mymysite.com/yourtexthere/moretext where yourtexthere/moretext is now the slug. views.py def textview(request, slug): obj, created= Text.objects.get_or_create(slug=slug, defaults={'text':'', 'password':'123'}) return render(request, 'text/textpage.html', {'obj' : obj, 'created' : created}) urls.py # Only patterns urlpatterns = [ path('', home, name='home'), path('<slug:slug>/', textview, name='textview'), ] -
Django allauth - how to send users that just signed up with Google to an intermediate screen where they fill out additional informations
I integrated django-allauth with my Django app but I would like to make a small tweak on the current sign-up flow. Problem Currently if a user uses google sign-up to sign-up on my app, django-allauth creates an account for them extracting a certain amount of informations from google and then send the user to the home-page. Desired behavior I would like users who just finished the authentication process through google/allauth,to be sent to an intermediate screen (that they can skip if they really want) where they are asked additional informations (like phone number) so that I can complete their profile. Setup I have a custom user model where email is the main unique id of a user. from django.contrib.auth.base_user import BaseUserManager from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and … -
How to get Photos of each Product using foreign key and show in a list view django?
I'm working on a ecommerce website and i wrote a model for a Image album for each Product. But when i want to show products in a list view all of images will be show for each product. What should i do to show photos that related to each product? Here is my models.py class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) image = models.ImageField(blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name class ProductImage(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%y/%m/%d') def __str__(self): return self.product.name Using ProductImage class i can add multiple photos for each product. and other problem is that if i have product with 5 photos i want to show only first two photos in list view and not all of them.what should i do for this problem? Here is my admin.py: class ProductImageAdmin(admin.StackedInline): model = ProductImage @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [ProductImageAdmin] list_display = ['name', 'slug', 'price', 'available', 'created', 'updated'] list_filter = ['available', 'created', 'updated'] list_editable = ['price', 'available'] prepopulated_fields = … -
django get lazy reference by Model
To get model from lazy reference, we can do from django.apps import apps Article = apps.get_model('articles.Article') # app.Model But what about the reverse for it? I mean to get the lazy reference app.Model by Model class. from articles.models import Article # something like print(Article.lazy_reference) # <str> articles.Article you probably wonder why I do this, I need to tract user initiative and passive actions, there's no modelfield in django, hence I store the model reference and pk as indication.