Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nodejs + Express vs Django: Choosing the best suitable backend component for given requirements
I'm trying to build a software architecture for my web development. The main requirements of the website are as follows: visualize real-time data carry out machine learning analysis Report visualization information via Email or SMS The concept for such an web application consists of a database, a backend and a frontend component. I have already selected a time series database. Despite my research, I cannot determine which backend component best meets the requirements: Nodejs + Expressjs or Django. My programming knowledge in Javascript and Python is on the same level. Why Node: its Single Threaded Event Loop Model for real-time web applications same programming language for selecting a javascript framework on the frontend-side (but python for machine learning analysis) More flexibility than Django due to its MTV pattern (usually) less execution time than python-Code Why Django: Django Channels for real-time web applications python language in backend, frontend and for data analysis quicker development process because of the language simplicity more secure due to its build-in security tools Question: Are there any other technical arguments why I should consider choosing Nodejs or Django or any arguments for not choosing one of them? -
how to convert relationship OneToOne to OneToMany keeping the existing data in django
I had created these models in the past but I need to change the relationship between the User model and Profile from oneToOne to OneToMany so that the User can have multiple profiles. since the database already exists if I run the classic modification the data will disappear class User(AbstractBaseUser, PermissionsMixin): phone = models.CharField( _('phone number'), max_length=50, unique=True, blank=True, null=True, default=None,) email = models.EmailField( _('email address') ,unique = True, blank=True, null=True, default=None,) #email and phone defaults are set to None to avoid duplicated key errors because empty charfields are stored as #empty strings email_confirmed = models.BooleanField( _('email is confirmed'), default=False ) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) profile = models.OneToOneField("OrdinaryProfile", on_delete=models.CASCADE, blank=True, null=True) # roles = models.ManyToManyField(Role, through='UserRole') objects = UserManager() USERNAME_FIELD = 'id' class Profile(models.Model): first_name = models.CharField(max_length=30, ) last_name = models.CharField(max_length=30) picture = models.ImageField(upload_to="profiles", null=True, blank=True, ) created_by = models.ForeignKey("Profile", on_delete=models.CASCADE, null=True, related_name='creator', default=None) # address = models.OneToOneField(Address, on_delete=models.CASCADE, null=True, blank=True) address = models.CharField(max_length=100, blank=True, null=True) location = … -
How to Search Comma Separated Strings or List in Django
I have a column in a Django Model Where the text is separated by Commas or the list of user ids. I used this column to search the number of occurrences this user's id is linked in newly registered users. [17, 3, 1] in DB it is saved like this separated by commas. When I used the MyModel.objects.filter(column__contains="7".count() when tried with other options like iregex, iexact, icontains or exact nothing shows. It includes the 7 from 17 and fetches the result. Is there any efficient solution for this problem? -
Deny to access to id of user in Foreignkey model
--WHY I CANT TO ACCESS TO ID OF USER AND PRODUCT WITH user__id and product__id? i have error: (The view store.views.submit_review didn't return an HttpResponse object. It returned None instead). <pre><code> i define some code for rating post for any user user --#views def submit_review(request, product_id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': try: reviews = ReviewRating.objects.get(user__id=request.user.id,Product__id=product_id) #my problem is here form = Reviewform(request.POST, instance=reviews) form.save() messages.success(request, 'Thank you!your review has been updated.') return redirect(url) except ReviewRating.DoesNotExist: form = Reviewform(request.POST) if form.is_valid(): data = ReviewRating() data.subject = form.cleaned_data['subject'] data.review = form.cleaned_data['review'] data.rating = form.cleaned_data['rating'] data.ip = request.META.get['REMOTE_ADDR'] data.product_id = product_id data.user_id = request.user.id data.save() messages.success(request, 'Thank you! Your review has been submitted') return redirect(url) </code></pre> this section i define model.I checked this part it work correctly define model for views in my app #models class ReviewRating(models.Model): Product = models.ForeignKey(product, on_delete=models.CASCADE) user = models.ForeignKey(Account, on_delete=models.CASCADE) subject = models.CharField(max_length=100, blank=True) review = models.TextField(max_length=500, blank=True) rating = models.FloatField() ip = models.CharField(max_length=20, blank=True) status = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject this part i define url #urls define path for html and views urlpatterns = [ path('submit_review/int:product_id/',views.submit_review,name='submit_review') ] -
Mapbox Add a default marker to a web map - django
context Using Add a default marker to a web map, I want to add a number of points as markers. Within views.py under 'marker format' I use the marker format const marker6 = new mapboxgl.Marker() .setLngLat([12.554729, 55.70651]) .addTo(map); as a template for each iteration of the loop. Problem The p tag with id 'test' results in below const marker0 = new mapboxgl.Marker().setLngLat([-2.97,53.43890841]).addTo(map); const marker1 = new mapboxgl.Marker().setLngLat([-2.29,53.46303566]).addTo(map); However using the same code "{{context.vf|join:""}}" that produces above, which is the same format as the working markers, doesn't result in markers appearing. Ask Is it possible to do so in a more efficient way? Views.py from django.shortcuts import render from django.views.generic import TemplateView import requests from datetime import date from datetime import timedelta from .models import Regions class HomePageView(TemplateView): # template_name = 'home.html' def get(self,request): # current date is start date start_date = date.today() # end date end_date = start_date #+ timedelta(days=3) # footbal api url = "http://api.football-data.org/v2/matches" querystring = {"dateFrom": start_date, "dateTo": end_date} headers = {'X-Auth-Token': "", } response = requests.request( "GET", url, headers=headers, params=querystring).json() #### extract data # count of returned fixtures count = response['count'] # count of premier league games plist = [] for i in range(0, count): if … -
Serialise an extended User Model in Django
I'm extending a django auth user model in a Profile model: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) activity = models.IntegerField(default=500) def _str_(self): return self in my views I'm getting the current auth user and I get the associated profile: @api_view(['GET']) @permission_classes([IsAuthenticated]) def getUserProfile(request): profile = Profile.objects.get(user = request.user) serializer = profileSerializer(profile, many=False) return Response(serializer.data) Here is my serializers code: from rest_framework import serializers from .models import Profile class profileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('first_name', 'activity') The error I'm getting that Profie object has not a first_name attribute, but when I replace 'first_name' with 'user' I get only the id of the user, so I want to show the first_name as well. Thank you -
django, INFO:waitress:Serving on http://0.0.0.0:8000 , its showing me error Plese help me?
While I use the url http://0.0.0.0:8000 in browser, it says "The site cannot be reached." How to solve this problem. Any one help me, please! my django project name is: testtodo and I use command -> waitress-serve --port=8000 testtodo.wsgi:application when i click on this link on my browser http://0.0.0.0:8000 then it's showing me error, this site can't be reached, and also this error The webpage at http://0.0.0.0:8000/ might be temporarily down or it may have moved permanently to a new web address. ERR_ADDRESS_INVALID -
Django Admin, how to hide change password?
Some users of my Django application come from a LDAP server. These users must not be able to change their django-admin password. The best, if they don't even have one. That's why I subclassed django_auth_ldap.backend.LDAPBackend like this: from django_auth_ldap.backend import LDAPBackend from django.contrib.auth import get_user_model class CustomLDAPBackend(LDAPBackend) def authenticate_ldap_user(self, ldap_user, password): user = ldap_user.authenticate(password) print("BEFORE set_unusable_password(): ", user.has_usable_password()) user.set_unusable_password() user.save() print("AFTER set_unusable_password(): ", user.has_usable_password()) return user By user.set_unusable_password() I try to hide the password, because I read it in several places (here in SO as well as in the docs). But all I can achieve is having no password set: Furthermore if I login multiple times, the result of print("BEFORE set_unusable_password(): ", user.has_usable_password()) is always True, despite calling user.set_unusable_password() and saving the user. As if a new user object is getting created every time. This question does not solve my problem because user.set_unusable_password() apparently does not hide the password-changing area. So what am I missing? How can I hide the 'change password' area? Below is the LDAP-relevant part of the settings.py: import ldap from django_auth_ldap.config import LDAPSearch, LDAPGroupQuery,GroupOfNamesType,PosixGroupType AUTH_LDAP_SERVER_URI = 'ldap://localhost' AUTH_LDAP_BIND_DN = 'cn=admin,dc=example,dc=com' AUTH_LDAP_BIND_PASSWORD = 'secret' AUTH_LDAP_USER_SEARCH = LDAPSearch('dc=example,dc=com',ldap.SCOPE_SUBTREE, '(uid=%(user)s)') AUTH_LDAP_GROUP_SEARCH = LDAPSearch('dc=example,dc=com',ldap.SCOPE_SUBTREE, '(objectClass=top)') AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr="cn") AUTH_LDAP_MIRROR_GROUPS = … -
TypeError: CheckNewsDateStatus() takes no arguments
I'm trying to update a django/mezzanine application from python 2.7 to python 3.7. Can you help me in fixing the error below (CheckNewsDateStatus() takes no arguments)? Seems that this class is not used at all; if I grep through all code only the attached settings.py and middleware.py match. Is it something partly implemented in django/mezzanine or it it so that the whole class can be removed as unnecessary ? I don't know how the code was planned to work and I don't know is the feature has been used at all... (python-3.7) miettinj@ramen:~/pika> python manage.py runserver BASE_DIR /srv/work/miettinj/pika PROJECT_ROOT /srv/work/miettinj/pika/pika /srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/timezone.py:13: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. For more details on how to do so, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html zone_name = tzlocal.get_localzone().zone /srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/conf.py:67: UserWarning: TIME_ZONE setting is not set, using closest match: Europe/Helsinki warn("TIME_ZONE setting is not set, using closest match: %s" % tz) BASE_DIR /srv/work/miettinj/pika PROJECT_ROOT /srv/work/miettinj/pika/pika /srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/timezone.py:13: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. For more details on how to do so, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html zone_name = tzlocal.get_localzone().zone /srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/conf.py:67: UserWarning: TIME_ZONE setting is not set, using closest match: Europe/Helsinki warn("TIME_ZONE … -
render() got an unexpected keyword argument 'context_instance' in Django 3.0
I had updated my project from Django 1.8 to Django 3.0 Let us consider my views.py as: class StockPricingView(View): def get(self, request, pk): data1 = OtherOrder.objects.get(id=pk) data = PricingModule.objects.filter(item__other_order_id=pk) charges = OtherOrderAdditionalCharges.objects.filter(order_id=pk) if charges.exists(): total_charges = charges.aggregate(Sum('amount')).get('amount__sum') or 0.00 order_total = data1.otherorderitem_set.all().aggregate(Sum('total_cost')).get('total_cost__sum') or 0.00 per_charges = (total_charges/order_total)*100 return render_to_response( 'stock/otherorders/stock_pricing_view.html', locals(), context_instance=RequestContext(request)) Please help me solve this isssue -
How to categorize WhiteNoise?
I am writing scientifically about a Django application. The application returns static files via WhiteNoise and I would like to learn more about it to be able to write precise. How is WhiteNoise classified? Is it correct to speak of a middleware? How is the request processed until WhiteNoise comes into play? Is WhiteNoise responsible for providing the correct reference to the static file in the Django template or does it do more? Does the behavior change if the static files are hosted on a CDN? I highly appreciate any input or reference to helpful articles! Thanks in advance. -
How to add multiple reviews or products using for loop in Django? (fetching data)
I need to add multiple reviews using "for loop". I made the model, and then through the admin panel (of Django)added a review. Now within the same code, I need to add another review. I'm pretty new at this and have to follow the instructions and can't do it any other way. This is how I have looped one review: {% for display in Review %} <i><img src="{{display.image}}"/><span>{{display.name}}</span></i> <p>{{display.desc}}</p> {% endfor %} This is the model: class Review(models.Model): image = models.ImageField(upload_to="static/images") name = models.CharField(max_length=20) desc = models.TextField() -
Certbot Authenticator Plugin error for Nginx
I'm trying to issue an SSL certificate using Cerbot. The command that I'm using is as follows. sudo certbot --nginx -d example.com -d '*.example.com' But every time I run this command, I'm getting the following error. Plugins selected: Authenticator nginx, Installer nginx Obtaining a new certificate Performing the following challenges: Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA. You may need to use an authenticator plugin that can do challenges over DNS. Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA. You may need to use an authenticator plugin that can do challenges over DNS. Now, I don't understand how to fix this issue. Please help. I'm following this guide from DigitalOcean to issue an SSL certificate for Nginx using Cerbot. Thank You. -
Update/Remove Many to Many Field in Django
I have saved the object in the database with the many to many fields, after saving the object in the database I want to append one more ID in the many to many field so how can I do that in Django. models.py class Project(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, default='') account = models.ManyToManyField(User) JSON from Frontend { "name": "Project 1", "description": "description of project 1", "account": [1, 2] } it objects is saved now, what if I want to add id 3 to account? -
How to serialize an extended model in Django
I'm extending a django auth user in a Profile model: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) activity = models.IntegerField(default=500) def _str_(self): return self in my views I'm getting the current auth user and I want to return his profile: @api_view(['GET']) @permission_classes([IsAuthenticated]) def getUserProfile(request): user= request.user # this will give us the current authenticated user serializer = profileSerializer(user, many=False) #here I know that I must enter a user + activity but I don't know how (it is the place from what I'm getting the error) return Response(serializer.data) Here is my serializers code: from rest_framework import serializers from .models import Profile class profileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('__all__') I thought of saving a new profile to db whenever a User signed up, but I use only logging in from an external server (LDAP) and my login code is : class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) data['username'] = self.user.username data['first_name'] = self.user.first_name data['last_name'] = self.user.last_name #data['activity'] = self.user.activity (it won't work because self.user is the auth user not the profile ) return data class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer urls.py : from django.urls import path from .views import getUserProfile urlpatterns = … -
Django context not passing in HTML template
I am not understanding where I am doing mistake. I am trying to passing context in my html page but why context isn't passing. see my code: #views.py def SupportReply(request): replyAgent = Contact.objects.all() context = { replyAgent:'replyAgent', } print(context) return render(request,'contact/support-reply.html',context) urls.py path('support-agent/',views.SupportReply,name='support-agent'), HTML {% for i in replyAgent %} {{i.support_ticket}} {%endfor%} See my terminal result where all object printing from context: [30/Dec/2021 17:41:29] "GET /support-agent/ HTTP/1.1" 200 6571 {<QuerySet [<Contact: Contact object (45)>, <Contact: Contact object (44)>, <Contact: Contact object (43)>, <Contact: Contact object (42)>, <Contact: Contact object (41)>, <Contact: Contact object (40)>, <Contact: Contact object (39)>, <Contact: Contact object (38)>, <Contact: Contact object (37)>, <Contact: Contact object (36)>, <Contact: Contact object (35)>, <Contact: Contact object (34)>, <Contact: Contact object (33)>, <Contact: Contact object (32)>, <Contact: Contact object (31)>, <Contact: Contact object (30)>, <Contact: Contact object (29)>, <Contact: Contact object (28)>, <Contact: Contact object (27)>, <Contact: Contact object (26)>, '...(remaining elements truncated)...']>: 'replyAgent'} why I am not seeing any object in my HTML page? where I am doing mistake? -
Website hangs in mobile but runs well in desktop
The home page of https://inscignis.in/ runs well in desktop but in mobile devices, when we scroll down to the bottom and try to scroll up, it kind of gets stuck in the motion and the experience isn't smooth. Couldn't figure out any possible bugs. it will be really helpful if anyone can give any general solutions to it. Sorry couldn't post the website code here as it is owned by my university. Thanks in advance. -
Django-filter issue
I have this problem, so i did a filtering by categories on my AllProducts Page and it worked perfectly (django-filter). The thing is that the startup im working at has another Django Model which is ProductInStore and that's an additional model connected to Product which has to show all the products that a certain shop has. class Product(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) product_category = models.ManyToManyField(EcommerceProductCategory) description = RichTextField(max_length=2000, null=True, blank=True) product_producer = models.ForeignKey('ProductProducer', on_delete=models.CASCADE) creator = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, blank=True, related_name='product_creator') points_from_reviews = models.DecimalField(max_digits=6, decimal_places=2, default=0, help_text='Średnia ocena produktu') unique_id = models.CharField(max_length=256, unique=True) type_of_unique_id = models.CharField(max_length=64) product_img = models.FileField(upload_to='ecommerce_product_img/', null=True, blank=True) class ProductInStore(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) store = models.ForeignKey('Store', on_delete=models.CASCADE) price = models.DecimalField(max_digits=6, decimal_places=2, default=0, help_text='Cena w sklepie') currency = models.CharField(max_length=4) url = models.CharField(max_length=200) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) The thing is that when im filtering by categories in Product model it works flawlessly and here's how it looks with Product Model def all_products(request): product = Product.objects.all().order_by('-created_at') search_filter = ProductFilter(request.GET) product = search_filter.qs paginator = Paginator(product, 20) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'page_obj': page_obj, 'search_filter': search_filter, } return render(request, 'ecommerce/all_products.html', context) … -
How to integrate oauth2 with credentials login?
I am building a web service in which I want to implement oauth authorization, to make login process faster and more user friendly. However, I also need to enable old fashion login+password signing in method for those who do not have accounts in oauth providers platforms. What is the best approach to connect these two methods? I am using Django. Thanks for the answer. -
Delete old file when uploaded new in django rest-framework
I wanted to delete old image from folder when uploaded new image and I tried but couldn't get result. serializers.py from base.services import delete_old_file class CourseCenterSerializer(serializers.ModelSerializer): class Meta: model = CourseUser fields = [ 'id', 'name', 'slug', 'profile_img', ] def update(self, instance, validated_data): delete_old_file(instance.profile_img.path) return super().update(instance, validated_data) services.py import os def delete_old_file(path_file): #Delete old file when upload new one if os.path.exists(path_file): os.remove(path_file) What I did so far, I don't know what's wrong with it -
What's the best way playing around a Django queryset, without having to runserver
Due to an import error i get when trying to import a Django data model in a file running under my apps folder, i'm writing this post to have some help on this. What is another way i can play around with a MyDataModel.objects.all() (doing for loops for example), without running the server and using the outputs on HTML. What i mean is that i want, from my text editor (Sublime Text), to be able to run something like this (within my apps folder): from .models import Article all_articles = Article.objects.all() -
WHY I CAN'T ACCESS TO USER__id FOREIGNKEY MODEL IN VIEW.PY
def submit_review(request, product_id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': try: reviews = ReviewRating.objects.get(user__id=request.user.id,Product__id=product_id) form = Reviewform(request.POST, instance=reviews) form.save() messages.success(request, 'Thank you!your review has been updated.') return redirect(url) except ReviewRating.DoesNotExist: form = Reviewform(request.POST) if form.is_valid(): data = ReviewRating() data.subject = form.cleaned_data['subject'] data.review = form.cleaned_data['review'] data.rating = form.cleaned_data['rating'] data.ip = request.META.get['REMOTE_ADDR'] data.product_id = product_id data.user_id = request.user.id data.save() messages.success(request, 'Thank you! Your review has been submitted') return redirect(url) -
Django user is_staff field set to true in instance but reads false in permission class
I am trying to create an api endpoint that lists all the users in the database, but I only want staff members to be able to do this. By default when a secretary is created, the is_staff field in the users model is set to True. In the permission class, I am checking to see if this field is set to true and grant permissions accordingly. Since I have many different types of users with slightly different attributes, I created a concrete base user model that is inherited by other user models. The SECRETARY role is assigned by the serializer when handling the secretary creation endpoint request. class User(AbstractBaseUser): class Roles(models.TextChoices): """define the user roles""" ADMIN = "ADMIN", "Admin" PRINTER = "PRINTER", "Printer" SECRETARY = "SECRETARY", "Secretary" PHOTOGRAPHER = "PHOTOGRAPHER", "Photographer" EDITOR = "EDITOR", "Editor" CLIENT = "CLIENT", "Client" SYSTEM = "SYSTEM", "System" APPLICANT = "APPLICANT", "Applicant" id = models.CharField( max_length=8, unique=True, primary_key=True, default=uidgen, editable=False ) first_name = models.CharField("First Name", max_length=30, null=False) last_name = models.CharField("Last Name", max_length=30, null=True, blank=True) email = models.EmailField( verbose_name="Email", max_length=255, unique=True, null=False ) username = None phone_number = models.CharField( "Phone Number", max_length=20, null=False, unique=True ) dob = models.DateField(verbose_name="Date Of Birth", blank=True, null=True) role = models.CharField(max_length=50, default=Roles.CLIENT) … -
Why is my forms content showing in the title for my edit function? Django
I am currently doing an assignment where one of the requirements for the edit function is that the user should be able to click on an edit button and be taken to a page where they have the option of editing what they wrote before. The issue I am having is that I am using INITIAL to push the previously populated content so that it will show, but this keeps showing on the title of the page instead of inside the textarea content. I have tried to tweak this but after several attempts, I keep getting the same issue, when i submit this, it gives me a new entry/page when what I want to do is edit the page and not create a new page. VIEWS.PY class AddPageForm(forms.Form): title = forms.CharField() content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", }) ) def edit_page(request, title): if request.method == "GET": title = title content = util.get_entry(title) form = AddPageForm({"title": title, "content": content}) return render( request, "encyclopedia/editpage.html", {"form": form, "title": title} ) form = AddPageForm(request.POST) if form.is_valid(): title = form.cleaned_data.get("title") content = form.cleaned_data.get("content") util.save_entry(title=title, content=content) return redirect('encyclopedia:entrypage', title) EDIT PAGE {% block body %} <h1>Edit</h1> <form action="{% url 'encyclopedia:editpage' title %}" method="post"> {% csrf_token %} … -
Unittest code for Ldap login authentication in DRF
I want to write unittest code for ldap login authentcation. I have no idea about how to start also. I got assigned for this task. I watched tutorials regarding unt test there i got basic things only. Please refer any idea or link or tutorial about this.Plz rescue me out,..