Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Unable to hit api with other pc on the same network for a multi tenancy application in django
I have successfully applied multi tenancy architecture with same database and separate schema for each tenant using Django and postgresql. But while trying to access the api's with a computer on the same network using the ip address I am getting 404 Not found. While on the main computer I am able to hit the api using localhost when the tenant domain is tenant1.localhost and to allow other computers on the same network I tried changing tenant domain to <my_ip>.tenant1 but it is not working. Any help would be appreciated. -
Get data from django database
So,how get data from django database?I have django models and created 2 objects there.I want to get 2 objects and write in html file. admin panel: https://i.stack.imgur.com/7WUZr.png view.py def vds(request): HTML_STRING = render_to_string("vds.html", context=context1) return HttpResponse(HTML_STRING) VDSTARIFS_obj = VDSTARIFS.objects.get(id=1) context1 = { "prise": VDSTARIFS_obj.prise, } file with models class VDSTARIFS( models.Model): prise = models.CharField(max_length= 10,) def __str__(self): return str(self.prise)``` -
Django html templates issue
I am a beginner in python. I scraped a website title and dates but dates are in different formats like Dec 4, 2021 and Dec 04, 2021. I used the condition to compare these dates from today's date so that my data will be present if the date matches the requirnment but when I used the below function in the HTML template by using Django it didn't work. The reason is that it only includes one space gap either I need 2 spaces between ", and 2021". nows = datetime.datetime.today() today_date=nows.strftime( "%b %d, %Y").replace(' 0', ' ') when i call today_date in html template it shows me only one gap like this 'Dec 4, 2021' and i need this 'Dec 4, 2021 result1=result.loc[data['LastUpdated']== today_date] json_records1=result1.reset_index().to_json(orient='records') arr1=json.loads(json_records1) ab={'abc':arr1} return render(request, "index.html",ab) This is my HTML template where I call today date {{abc}} If someone knows then kindly solve my problem. -
"This field is required." in DRF serializers
I am facing an issue in DRF serializers. I have a model named Issue which has a foreign Key of User Model to save the user who has created the particular Issue. Now the Get request is working fine when I request to get the issues I get it perfectly fine with username who has created the issue, but when I do the post request I get the error on "created_by" field that "This field is requied" even though I am providing this field. Following is my code: Model class Issues(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='issue_created_by') title = models.CharField(max_length=225, default='', null=False) details = models.CharField(max_length=1000, default='') created_on = models.DateField(default=timezone.now) tags = models.CharField(max_length=225, blank=True, null=True, default='') Issue Serializer class IssueSerializer(serializers.ModelSerializer): created_by = UserSerializer() class Meta: model = Issues fields = ['created_by', 'title', 'details', 'created_on', 'tags'] UserSerializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = super().create(validated_data) user.set_password(validated_data['password']) user.save() return True views.py class IssueView(viewsets.ViewSet): def create(self, request): serialized_issues = IssueSerializer(data=request.data) if serialized_issues.is_valid(): serialized_issues.save() return Response({'message': 'Issue Created', 'status': status.HTTP_200_OK}) else: return Response({'error': serialized_issues.errors, 'status': status.HTTP_400_BAD_REQUEST}) def list(self, request): all_issues = Issues.objects.all() serialized_issues = IssueSerializer(all_issues, many=True) return Response(serialized_issues.data) -
How to use dynamic global variables in Django view functions?
I now need to use RPY2 to get some value in one view and use that value in another view. In the development environment:it works view.py: PACds='abc' #Defining global variables def upload(request): global PACds robjects.r.source(path+"Upload.R") PACds=robjects.r.readPAC(.....) #Storing data globally def use(request): # Using the global variable But when deployed to the server, ajax requests using the Use view had a strange problem: PACds=' abc' was the global variable accessed the first time and changed the value the second time. Is there a better way to solve this problem? or Is it possible to save R type values obtained using RPY2 in one view and used in another view? Software version: Django 3.1 Python 3.8 rpy2 3.4.5 -
I am new to Django and just follow the Django official document, but here is a problem
I need to upload to another html template whose name depends on the variable that the server gives. How to make it work? I'm trying to do this: {% include 'ui_interface/tables/{{ item.product.title }}.html' %} But it gives an error: TemplateDoesNotExist at / in which the link to the template looks like this: Exception Type: TemplateDoesNotExist Exception Value: ui_interface/tables/{{ item.product.title }}.html that is, it does not translate the variable in the template engine -
how do I style and align errorlist from django forms?
This form errorfield comes with ul and li elements and I can't find a way to change it. So is it possible to have "email is taken" as error instead of having the whole ul element "email" before that, if that's not possible then can we at least align it inline together the ul and li. Thx in advance. css .errorlist li { list-style-type: none; display: inline-block; } .account-errors { font-family: "Circular Std Book"; color: black; } html {% if form.errors %} <div class="account-errors"> <div class="container-error"> {{ form.errors }} </div> </div> {% endif %}