Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO + JWT TOKEN AUTHENTICATION
So I was trying to build a backend for my Android application. I was try to apply a login procedure that works with JWT Token This is what I have done : I have made a custom User model. Customize my superuser to take phone number and password, instead of username and password I have successfully created superuser and store it in my database (using postgreSQL). I have also customize my token claims and response as seen in my serializers.py of class LoginSerializer. However, I encounter some problem after what I did : Right now, after customizing my user model, I was not able to login to Django administration with my new custom made User model, even though I have succesfully created a superuser. I still can't get the token even after I have made a customization for my token claims, with the success superuser account I just created. Here are some of the error message : Here are the some of the files attatched below : models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager from django.utils.translation import ugettext_lazy as _ from phone_field import PhoneField class RegisterUserManager(BaseUserManager): def create_user(self, phone_number,password): if not phone_number: raise ValueError('The phone number must be … -
Why is this python code not comparing two date?
I have written this simple code but even when i update my post from django admin section {% if post.is_updated %} Updated on: {{post.date_updated}}{%endif%} this piece of code doesnt run(updated on doesnt show on blog) models.py class Post(models.Model): title=models.CharField(max_length=100,help_text='Enter Title') content=models.CharField(max_length=500) author=models.ForeignKey(User,on_delete=models.CASCADE) date_posted=models.DateTimeField(default=timezone.now) date_updated=models.DateTimeField(auto_now=True) field def __str__(self): return self.title @property def is_updated(self): if self.date_updated > self.date_posted: return True else: return False article.html <div>{{ post.date_posted|date:"F d, Y" }} {% if post.is_updated %} Updated on: {{post.date_updated}}{%endif%}</div> -
Multi Process in Django
i am creating rest api using Django rest framework. while calling an api i want to excecute another process without effecting the actual api. i created like this def proces_add(request): emp=Employee.objects.get(EmployeeId=request.data.get("Emp")) result = { 'Status': success, 'Message': 'process called', 'Employee': emp.EmployeeId } p = Process(target=proce_new, args=(emp.EmployeeId, 1)) p.start() return Response(result, status=status.HTTP_200_OK) def proce_new(emp): try: device = Device.objects.filter(Employee=emp) for val in device: div = val.Device.DeviceCode div = Employee.objects.get(EmployeeId=val.Device.DeviceId) sync = Synchronization( Device=div, SyncType=1 ) sync.save() except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) but data is not getting saved.. what is the issue How can i make it working good? i am using multiprocess at first time .. is it correct ? -
Django Documentation 'ManyToManyField'
can anyone please tell how did they get all the articles of a particular publication as shown the documentation the query is >>>p2.article_set.all() but what is article_set in the query for model reference look into the documentation below is the link https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_many/# and the query is also present the documentation -
Video stream mp4/ogg/WebM File (NO CAMERA) using Python?
I am trying to stream a mp4 file using Python as my programming language for the back-end and a bootstrap index.html as my front-end. The general idea is there will be a gallery of sorts of pictures where you press as picture and you'll be redirected to another page with the video related to the image. I would prefer to be able to, for example, add a custom "back button" at the top to go back to the start page but pure html5 controls works as well. I have found multiple ways of streaming videos that are a direct live feed from cameras but NO working example that I can build around nor hints not using 100+ lines of code and openCV. I found one ffmpeg streaming solution that simply created a video variable and nothing more. I also found this django solution with some functions and a rather advanced explanation and solution that is NOT a working solution I can decipher and make work myself. So does anyone have any idea how to, preferably using either Django or Flask, stream video files to a wide variety of browsers using a Python back-end web server? I am not interested in … -
UML suggestions for a django project using 3 apps
hope you are doing! ... I build my app with django and I am stuck doing the UML class diagram , I have tried the graph_model by django-extensions and it generate something like the picture attached , my project contain 3 apps users , blog , dans dashboard. my app is showing statistics based on the imported data from the administrator of this web app 'the dashboard part ' and in the dashboard/views.py I made some functions to make some statistics, so the normal users can only write post 'blog' and can visualize the statistics from 'dahsboard'... but in this part I don't know how to do the association between the users and what he can visualize, can you help me out -
How to find a certain place is in a certain city or not using python
I was wondering if there's any way to find out a place is in a city or not using python. For example, I want to find if Central Park in New York by getting "Central Park" from a string and get feed it in API to get if it's in New York or not. is_in_place(sub_area, area) Like: is_in_place("Central Park","New York") if it's in New York it will return true otherwise false. -
avoid redirecting after form submission in Django
I'm trying to cancel the form redirect after submitting the form. but without success, what is the best way to handle it? my goal is : user is registering (Form submit) >> and then I use Jquery to hide the form and put other div with a message. what is the best way to do that? views.py def home(request): form = StudentForm(request.POST or None) mains = Speciality.objects.all() # the main class subs = Submain.objects.all() # the sub class classs = Sclass.objects.all() if form.is_valid(): form.save() email(form.cleaned_data['firstname']+" "+form.cleaned_data['lastname'], form.cleaned_data['sid'],form.cleaned_data['main'],form.cleaned_data['hog']) context = {'form': form, 'mains': mains, "subs": subs, "classs": classs} return render(request, "studentform/register.html", context) -
Django doesn't email 500 error when using handler500
My Django app sends emails correctly to all the ADMINS as long as I don't have a custom error handler. However, when I add a handler500 to show my custom 500_error.html page, no emails are sent. The 500_error.html page is shown properly. It seems that when you have a handler Django assumes that you take care of the error and thus does not mail anything. (Does this make any sense?) My questions are: How can I still force Django to send emails even when the handler500 is used?, or How can I get the error description and mail it within my handler500 view function using send_email? Thanks! -
How to identify the reason for getting NoReverseMatch
I have a function where a user can change the BooleanField from False to True. My issue is that after submitting the button in the view I have redirected the page to be the same but for some reason I can't identify I am getting NoReverseMatch I have written the name of the app before the name and everything correctly. I need to understand the reason when identified to avoid it in future Here is the complete error appearing: Reverse for 'designer-only-posts' with no arguments not found. 1 pattern(s) tried: ['usersheet/(?P<username>[^/]+)$'] Here is the models.py class Item(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) request_settle = models.BooleanField(default=False) Here is the views.py class DesignerOnlyPostListView(ListView): model = Item template_name = "designer_only_posts.html" context_object_name = 'items' paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Item.objects.filter(designer=user).order_by('-timestamp') def change_status(request, pk): item = Item.objects.get(id=pk) item.request_settle = True item.save() messages.success(request, 'Item Status has been Change To Active') return redirect('core:designer-only-posts') Here is the urls.py app_name = 'core' urlpatterns = [ path('', HomeView.as_view(), name='home'), path('bla/<int:pk>/', views.change_status, name='bla'), path('usersheet/<str:username>', DesignerOnlyPostListView.as_view(), name='designer-only-posts'), ] Here is the template: <a href="{% url 'core:bla' item.pk %}"> <button type="button" class="btn btn-primary btn-lg btn-block">Submit button</button> </a> I would like also to understand the steps for debugging the No … -
Annotate queryset with max value of subqueryset
I have the following set of models: Hikes(models.Model) name = ... difficulty = models.IntegerField Regions(models.Model) hike = models.ManyToManyField(Hikes) Now, I'm trying to return the most difficult hike within a region, but I need to display this on a queryset which returns multiple regions. I imagine the best way to do this would be to annotate each Region with a "hardesthike" field or something like that, but can't figure out the code. I can get the code to work for an individual region, but can't get it to work on a queryset of multiple regions. My code for an individual region is: q = Region.objects.get(id=1) hikes = q.hike.all().values('difficulty') max = hikes.aggregate(Max('difficulty')) How can I annotate this new value onto the initial region? Preferably in simple integer form, so that I can sort by "Hardest Hike in a Region". Also, when I try to do any forloop in my views with any sort of aggregate function, I notice my webpage slows down substantially (I have 10k+ regions/hikes in my DB) -- any way around this? Thanks! -
Automated data dumps from postgres database into .sql using django/python and celery
I'm trying to automate regular data dumps from my postgres database using django/python. I'm using celery to automate it as a task since I want the data dumps to run regularly - every day or every two days. Currently i'm using sh, here's my code: from sh import pg_dump @periodic_task( run_every=(crontab(minute='*/2')), #set to 2 min interval for testing name="portal_backup", ignore_result=True) def portal_backup(): filename = "portal_backup.sql" with gzip.open(filename) as f: pg_dump('-U', 'postgres', '-W', '-F', 'p', 'Portal', _out=f) print("backup done") All of my database information is in my .env file , however when I run my code I get this error: sh.ErrorReturnCode_1: RAN: /usr/bin/pg_dump -U postgres -W -F p Portal STDOUT: STDERR: Password: pg_dump: error: connection to database "Portal" failed: FATAL: Peer authentication failed for user "postgres" I don't know why the authentication failed. If anyone has an better ideas on how I can automate this process through django/python and celery any info would be appreciated. -
Error when including 'channels' in installed_apps of Django
I am getting the following error when I add 'channels' in INSTALLED_APPS of Settings.py of Django. AttributeError: module 'time' has no attribute 'clock' for channels Any idea why? -
accessing field value inside the model in Django
The model I created... class TableToRefer(models.Model): Item = models.ForeignKey('Products.Product_description',primary_key=True,on_delete=models.CASCADE) Qty = models.ForeignKey('Products.Quantity',null=True,default=0,on_delete=models.CASCADE) Rate = models.ForeignKey('Products.Rate',null=True,default=0,on_delete=models.CASCADE) price = models.FloatField(null=True,default = Rate*0.20) I want to access the value of Rate field and use it in price field and automatically add the calculated price in it. How do I do it? -
Getting "AssertionError: duplicate Parameters found" when I hit /swagger url
I am implementing swagger using drf-yasg for django rest framework APIs in my project. I follow the quick start section of drf-yasg. When I hit /swagger gets AssertionError: duplicate Parameters found. Below is my code and traceback. urls.py from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="Snippets API", default_version='v1', description="Test description", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@snippets.local"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), # path('graphql', csrf_exempt(GraphQLObservableUnboxingView.as_view(graphiql=True, schema=schema))), ] Traceback ```Traceback (most recent call last): File "/home/abc/development/sw_api/env_sw_api_python3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/abc/development/sw_api/env_sw_api_python3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/abc/development/sw_api/env_sw_api_python3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/abc/development/sw_api/env_sw_api_python3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/abc/development/sw_api/env_sw_api_python3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/abc/development/sw_api/env_sw_api_python3.7/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/abc/development/sw_api/env_sw_api_python3.7/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/abc/development/sw_api/env_sw_api_python3.7/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/abc/development/sw_api/env_sw_api_python3.7/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/home/abc/development/sw_api/env_sw_api_python3.7/lib/python3.7/site-packages/drf_yasg/views.py", line 94, in get schema = generator.get_schema(request, self.public) File "/home/abc/development/sw_api/env_sw_api_python3.7/lib/python3.7/site-packages/drf_yasg/generators.py", line 254, in get_schema paths, prefix = self.get_paths(endpoints, components, request, public) File "/home/abc/development/sw_api/env_sw_api_python3.7/lib/python3.7/site-packages/drf_yasg/generators.py", line 412, in … -
how to send an post request?
i am making a website only for learning purpose. When i try to use post request, it shows me the following error: RuntimeError at /analyse You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/analyse/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. Here is my views.py and index.html: views.py: "kindly refer to the djtext = request.post.get('text', 'default')" # I have created this file - Piyush from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request, 'index.html') # return HttpResponse("Home") def analyse(request): global line djtext = request.POST.get('text', 'default') print(djtext) # Check checkbox value removepunc = request.GET.get('removepunc', 'off') fullcaps = request.GET.get('fullcaps', 'off') newlineremover = request.GET.get('newlineremover', 'off') extraspaceremover = request.GET.get('extraspaceremover', 'off') # Check which checkbox is on if removepunc == "on": punctuations = '''!()-{}[]:;'",<>./?@#$%^&*_~''' analysed = "" for char in djtext: if char not in punctuations: analysed = analysed + char params = {'purpose': 'Removed punctuations', 'analysed_text': analysed} return render(request, 'analyse.html', params) elif fullcaps == "on": analysed = "" for char in djtext: analysed = analysed + char.upper() params = … -
block ability superuser to delete other superuser and himself
I have got the problem with my exercise where I have to block ability superuser to delete other superuser and himself. admin.py `def delete_selected(modeladmin, request, queryset): if not modeladmin.has_delete_permission(request): raise PermissionDenied if request.POST.get('post'): for obj in queryset: if not obj.is_superuser: obj.delete() else: return delete_selected_(modeladmin, request, queryset) delete_selected.short_description = "Delete selected objects" and url.py path("admin/auth/user/",delete_selected), ` -
Why am I unable to import my app to urls.py?
I'm trying to import my app's views to urls.py but I keep getting a module not found error.I've tried diffirent formats for the import statements without success, also tried creating another project and a new app with pycharm but still getting module not found error. Installed apps 'milk.apps.MilkConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from main.milk import views urlpatterns = [ path('admin/', admin.site.urls), path('milk/', include('milk.urls')), path('accounts/', include('django.contrib.auth.urls')), path('signup/', views.signup_view, name='signup'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
django stripemissing 1 required positional [closed]
I'm trying to create a stripe subscription cancel function, but facing and error "cancel_subscription() missing 1 required positional argument: 'user'" def cancel_subscription(self, user: settings.AUTH_USER_MODEL) -> None: customer = stripe.Customer.retrieve(request.user.stripe_id) subscription_id = customer.subscription.id subscription = stripe.Subscription.retrieve(subscription_id) subscription.delete() -
how can I group_by queryset in Django ORM WITHOUT using .values()?
I am using a generic view as following: class myClass(generics.ListAPIView): serializer_class = myModelSerializer def get_queryset(self): queryset = myModel.objects.values(client=F('clientid__name')) queryset = queryset .annotate( success=Sum(Case(When(state='Success', then=1), output_field=IntegerField())), Failed=Sum(Case(When(state='Failed, then=1), output_field=IntegerField())), ) pagination_class = PageNumberPagination return queryset My Model: class myModel(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. date = models.DateTimeField(db_column='nDate') # Field name made lowercase. clientid = models.ForeignKey(Client, models.DO_NOTHING, db_column='ClientId',related_name="result_client") # Field name made lowercase. environment = models.CharField(db_column='Enviroment', max_length=50) # Field name made lowercase. The client Model: class Client(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', unique=True, max_length=20) # Field name made lowercase. The serializer: class myModelSerializer(serializers.ModelSerializer): client = ClientSerializer(many=True, read_only=True, required=False) class Meta: model = myModel fields = '__all__' depth = 2 so now, the view I have above, will take .values('client=F('clientid__name')') into consideration, and will NOT allow the serializer to run (it gives me that myModel does not have a client filed). AND, if I remove the .values(), the output will not be grouped by client name anymore. Any suggestion please? Is there a way to group the queryset without using .values() method? (I need to keep the serializer, as I am using pagination which requires me to have serializer). THANKS. -
Tutor OpenEdx, bad request 400 in localhost and studio.localhost
After running the command successfully tutor local quickstart, on developement mode, localhost/studio.localhost displays bad request 400. -
Trying to get Total Sold for each Item in E-commerce Django Project
I am trying to get the total no. of a sold item after payment is made. When the order is paid ordered = models.BooleanField(default=False) become True I have tried to add the context with the total sold but it didn't work so I kept it in the code below but commented it. I have also tried to add a function with total count but I keep getting 'Item' object has no attribute 'order_set' I kept it below for reference Here is the Item models.py class Item(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title # def count_sold(self): # return self.order_set.filter(ordered=True).count() Here is the OrderItemmodels.py class OrderItem(models.Model): ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) Here is the Order class Order(models.Model): items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) Here is the views.py class DesignerOnlyPostListView(ListView): model = Item template_name = "designer_only_posts.html" context_object_name = 'items' paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Item.objects.filter(designer=user).order_by('-timestamp') def get_context_data(self, **kwargs): comments = Comment.objects.all() # total_sold = Order.objects.all() context = super().get_context_data(**kwargs) context["total_comments"] = comments.count() # context["total_sold"] = total_sold.count() return context Here is the template {% for item in items %} <tr> <td>No. of Sold:</td> <td>{{ item.total_sold.all.count }}</td> </tr> {% endfor %} This is the template when I tried … -
DB2 And Django - Why Tables Always Created As Column Organized?
I have used the steps mentioned in the answer to this question Django connect to IBM Cloud database. But all the tables are getting created as column organized which creates issues while altering the table, and this issue is for the initial migrate itself admin, auth, contenttypes, etc. Can we some how change the table creation to row organized ? -
Footer moves into a div
hey, i just faced a problem and i can't resolve it : i don't understand why the footer comes beetween the button of my calendar and the calendar itself. Callendar.html : {% extends 'base.html' %} {% block title %} Calendar {% endblock %} {% block content %} <div class="clearfix"> <a class="btn btn-info left" href="{% url 'cal:calendar' %}?{{ prev_month }}"> Previous Month </a> <a class="btn btn-info right" href="{% url 'cal:calendar' %}?{{ next_month }}"> Next Month </a> <a class="btn btn-info right" href="{% url 'cal:event_new' %}"> New Imputation </a> </div> {{calendar}} {% endblock %} base.html : <div class="wrapper"> {% include "header.html" %} {% include "menu.html" %} <div class="content-wrapper"> <section class="content-header"> {% block title_page %}{% endblock %} </section> <section class="content container-fluid"> {% block content %} {% endblock %} </section> </div> {% include "footer.html" %} </div> and the view of of my calendar : Views.py: @method_decorator(login_required(login_url='/userprofile/login/'), name='dispatch') class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) d = get_date(self.request.GET.get('month', None)) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context As the result actually i got this when i press F12 (inspect element) on the web page : <div class="clearfix"> <a class="btn … -
how use date__range filter to summation annotate fields
i need to summation total objects of a field by its date created class Item(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE) order = models.IntegerField(default=1) price = models.IntegerField() cash = models.IntegerField() date = models.DateTimeField(auto_now_add=True) i want to filter by date times then summation all order ,and some more fields by date__range if start_time and end_time: data['dates'] = Item.objects.filter(active=True,date__range=(start_time,end_time).annotate( paid_price=( F('price') * F('order')), storage_price=( (F('item__price')+F('item__cost'))*F('order')), incomes= Case( When(paid_price__gte=F('storage_price') , then=F('paid_price') - F('storage_price')),default=0, output_field=IntegerField()) ).annotate(loss=Case( When(storage_price__gt=F('paid_price'),then=F('storage_price')-F('paid_price')),default=0 )).annotate(total_loan=((F('order')*F('price')) - F('cash')) ).annotate(quantity=(Sum(F('order')) )).annotate(incomes=(Sum(F('incomes')))).annotate(total_lost=(Sum(F('loss'))) ).annotate(store_price=(Sum(F('price')*F('order'))) )) but it still show each date differently , but i need to calculate all store_price total_lost incomes in one row ?thanks for answering