Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create multiple text contains filter in Django filters?
I am working with a django site and using django-filters to make filters. so i created a model as follows: class Bids(models.Model): Services=models.CharField(max_length=300) and that field contains many random words like 'services,manpower,security,machines,chemical,.. etc' so i created a django-filter as follows: class BidsFilter(django_filters.FilterSet): Services=CharFilter(field_name='Services',lookup_expr='icontains') class Meta: model=Bids fields="Services" and on my view i am using this filter as follows: def index(request): bidsData= Bids.objects.all() myFilter=BidsFilter(request.GET,queryset=bidsData) bidsData=myFilter.qs context = { 'Bids': bidsData, 'myFilter':myFilter } return render(request,"base.html",context) and on my template i am showing this filter as form: <form method="GET" >{{ myFilter.form }}<button class="btn-btn- primary"type="submit">Apply Filter</button></form> right now what happening is when i type a word eg. manpower the records having this word are printed. and if i type another word 'services' than those records are getting printed. What i want is to create multiple keyword filter for example if someone type 'manpower' than those records which have 'manpower 'are printed and also if someone types 'services' than those records which have 'services' word also printed and so on. its like a Tag filter you know like twitter and instagram can anyone show a good way of doing it. thanks in advance <3 -
Recommended file manager for Django Jazzmin admin
I am using Jazzmin theme in my Django admin panel and I am wondering if there is any recommended library to handle media files? I've installed django-filer but I see no option to integrate it with my summernote/tinyMCE or CKEditor. It doesn't matter for me which one I will be using. The most important is to have an option to insert uploaded images from body field in my model (it is textfield). I want to integrate it only in admin panel. -
what is equivalent to url(r'name/$') using path? I don't want users to access a django path
When considering url() in django, '$' allows you to block the url path. What is equivalent when considering 'path'? To be more precise I have the following path('',views.home,name='home'), path('json', json, name="json"), my home page calls the json file to plot a chart, however if user types in the url '.../json' they can access the json data file. I want users to not have access to the path /json but I still want my home page to access this json path. Thanks -
How to create custom button in Django admin, which create many object?
I have a model Student: from django.db import models from django.contrib import admin class Student(models.Model): name = models.CharField(max_length=30, default='') lastname = models.CharField(max_length=30, default='') grade= models.CharField(max_length=8, default='') class StudentAdmin(admin.ModelAdmin): list_display= ('name','lastname','grade') from django.contrib import admin from .models import * admin.site.register(Student, StudentAdmin) Imagine, that I have an additional model Person ( with name and surname fields). My situation is just an example. I want to create a button in the Django admin (it's very important to implement this in Django admin page), that creates many Student objects at once (name and lastname we take from Person, with empty grade field, which we can fill in the future). -
Async Stripe Function call
I am new to Django and I have been working on a Stripe based application and I found out that my class based views are quiet slow and I need to make them run as fast as possible. I discovered that in Django there is Asynchronous Support available but I am unable to figure how can I use it in class based views everywhere I find there are functional based example just. class BillSerializer(ReturnNoneSerializer, serializers.ModelSerializer): interval = serializers.CharField(read_only=True, required=False) amount = serializers.IntegerField(read_only=True, required=False) date = serializers.DateTimeField(read_only=True, required=False) is_active = serializers.BooleanField(read_only=True, required=False) subscription_expiry = serializers.BooleanField(read_only=True, required=False) active_jobs = serializers.IntegerField(read_only=True, required=False) class Meta: model = Billing fields = "__all__" def to_representation(self, validated_data): stripe.api_key = settings.STRIPE_API_KEY stripe_sub = stripe.Subscription.retrieve( self.context["request"].billing.stripe_subscription_id ) stripe_object = stripe_sub.get("items") quantity = stripe_object.get("data")[0].get("quantity") amount = ( stripe_object.get("data")[0].get("price").get("unit_amount") // 100 * quantity ) interval = stripe_object.get("data")[0].get("plan").get("interval") date = datetime.fromtimestamp(stripe_sub.current_period_end).strftime( "%Y-%m-%d %H:%M:%S" ) if validated_data.subscription_end < make_aware(datetime.now()): is_active = False else: is_active = True if validated_data.subscription_end <= make_aware(datetime.now()): subscription_expiry = True else: subscription_expiry = False return { "date": date, "interval": interval, "amount": amount, "quantity": quantity, "is_active": is_active, "subscription_expiry": subscription_expiry, } -
A better way to orgainize django-channels one to one private chat models?
I want to model the database table of a django channels private chat in the most effective way possible so that retrieving the messages would not take a lot of time. For that I have create a one to one room since every two users should have their unique room. And I created a separate message table with a foreign key relation with the (oneToOneRoom) table.But what bothers me is that since the sender and the receiver of the message can only be one of the two users of the room I do not want set (sender and receiver) as foreign Key to the users table. Can I have a better implementation of that. Or is their any other way of modeling those tables. Any help would be highly appreciated. Here is the models.py file. class singleOneToOneRoom(models.Model): first_user = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="first_user", blank=True, null=True) second_user = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="second_user", blank=True, null=True) room_name = models.CharField(max_length=200, blank=True, unique=True) def __str__(self): return f"{self.first_user}-{self.second_user}-room" class Meta: unique_together = ["first_user", "second_user"] class messages(models.Model): room = models.ForeignKey( singleOneToOneRoom, on_delete=models.CASCADE, related_name="messages") message_body = models.TextField() sender = models.ForeignKey( User, on_delete=models.CASCADE, related_name="msg_sender") receiver = models.ForeignKey( User, on_delete=models.CASCADE, related_name="msg_receiver") date_sent = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.sender}_to_{self.receiver}" -
TypeError: 'module' object is not iterable in django 4
TypeError: 'module' object is not iterable in django 4 Hi Team, I am getting the above error, it has persisted long enough than at this point I really need help. I am using pickle to load an ML model, Django to get user input. Below is the error, my urls.py file and the views.py file. Any Help will be highly appreciated. All Code in my GitHub. ******* When starting the server I get this Error Message ******* (python10_env) D:\Online Drives\MDigital\CIT-Letures\python10_env\smart_health_consult>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\urls\resolvers.py", line 634, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\management\base.py", line 438, in check all_issues = checks.run_checks( File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces … -
Why does Environ not set the variable in a Django project root other than the main?
So I have a .env file in my Django project root containing several variables. When I use them within the same project root (e.g. in settings.py) it works, but once I try to access a variable within another root/module it fails: # other root than .env import environ # Initialise environment variables env = environ.Env() environ.Env.read_env() # Get the iCloud application password via env mail_password = env('MAIL_PW') # --> returns django.core.exceptions.ImproperlyConfigured: Set the MAIL_PW environment variable This however works: # same root as .env import os import environ # Initialise environment variables env = environ.Env() environ.Env.read_env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') -
Initiating a GET request to Django web api and send a list of ids as an array
I'm trying to call a rest API in django and send a list of Ids as a paremeter (I can't use query string). This works if I send only one, but how to specify it for an array of integers: path('details/<int:id>/', views.get_details), def get_details(request, id=0) What if I have a method that will take a list of Ids: def get_data(request, ids=[]) How should the url be defined so that the ids array is populated? -
Requests and requests_toolbelt not uploading file to django
I need to upload a file to a django app from a pyside2 desktop app, the upload code is running on a worker class using a QThread, it works when i upload the file using requests only. # Login login_url = 'http://127.0.0.1:8000/users/login' client = requests.session() client.get(login_url) csrftoken = client.cookies['csrftoken'] login_data = {'username': username, 'password': password, 'csrfmiddlewaretoken': csrftoken} response = client.post(login_url, data=login_data) # Upload upload_url = 'http://127.0.0.1:8000/upload' client.get(upload_url) csrftoken = client.cookies['csrftoken'] file = {'file': open(file[0], 'rb') response = client.post(upload_url, files=file, data={'csrfmiddlewaretoken': csrftoken}) but i'm trying to use requests_toolbelt to keep track of the upload progress. with the code below django says that the form is not receiving the file field. data = encoder.MultipartEncoder(fields={'file': open(file[0], 'rb'), 'csrfmiddlewaretoken': csrftoken}) monitor = encoder.MultipartEncoderMonitor(data, callback) response = client.post(upload_url, data=monitor, headers={'Content-Type': monitor.content_type}) but if i send the file in requests file attribute the QThread doesn't end. data = {'csrfmiddlewaretoken': csrftoken} file = encoder.MultipartEncoder(fields={'file': open(file[0], 'rb')}) monitor = encoder.MultipartEncoderMonitor(file, callback) response = client.post(upload_url, file=monitor, data=data, headers={'Content-Type': monitor.content_type}) -
I want to be able to check multiple users, and only choose a single option per user AND send all selected users in a list in template/html
So, I couldn't get a simple title, sorry for that. Basically, I want to send a message to X users. For this I need to select the users that I want to send this message to, and their type, if they are normal, CC or CCI. Every single type of option has a single name, meaning that in the end I get a list of normal recipients, of CC recipients and CCI recipients. All of this using check-boxes, needing me to create a javascript event to recreate a radio-type of behavior for the options of a single user. I was wondering if there was a better option than this, by using radios? Here is how it's looking: CCI aren't implanted yet since I started to ask myself this question when I was asked to make them... Here is the code for one user, with the onclick event being the function that recreate radio behavior... <label class="dropdown-item text-wrap labelname" style="overflow-wrap: break-word; padding-left: 5px; padding-right: 0px;"> <input class="green form-check-input me-1 checkboxes-recipients recipientsmessage " id="green2" onclick="syncUnCheck(green2, gray2)" type="checkbox" value="invite" name="recipients[]"> <input class="gray form-check-input me-1 checkboxes-recipients recipientsmessage" id="gray2" onclick="syncUnCheck(gray2, green2)" type="checkbox" value="invite" name="recipientsCC[]"> invité </label> The problem of this function is that It doesn't … -
Chart.js is not being load in my Django project
Hi im new in programming and im learning/working on a django project an my im trying to use chart.js to show the chart of my expenses and i got this error occured: Here is my code of my urls django And i wanna add here that this error is occuring after i added 'expense/' in the 1st urls.. i added that because i want my home page to load first.. i mean if i remove 'expense/' from that 2nd path then it seems to work fine.. i'm unable to figure out what i did wrong..i know i did some stupid mistakes but im not being able to identify it. Thanks urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('', include('homepage.urls')), path('expense/', include('expenses.urls')), path('authentication/', include('authentication.urls')), path('preferences/', include('userpreferences.urls')), path('income/', include('userincome.urls')), path('admin/', admin.site.urls), ] Then i have created an app for expenses aswell its urls.py from django.urls import path from . import views from django.views.decorators.csrf import csrf_exempt urlpatterns = [ path('',views.index,name="expenses"), path('add-expense', views.add_expense, name="add-expenses"), path('edit-expense/<int:id>', views.expense_edit, name="expense-edit"), path('expense-delete/<int:id>', views.delete_expense, name="expense-delete"), path('search-expenses', csrf_exempt(views.search_expenses), name="search_expenses"), path('expense_category_summary', views.expense_category_summary,name="expense_category_summary"), path('stats', views.stats_view,name="stats"), ] Its views.py from asyncore import write import string from tkinter.tix import COLUMN from unittest import result from urllib import response from … -
DJANGO CKEDITOR with placeholder plugin
I cant seem to get the PLACEHOLDER plugin to show in my django-ckeditor ... anyone else experience this? The latest version seems to be v4.11 (when clicking on the ? in the editor) though the pyp version says 6.2... and their release history says "ckeditor updated to 4.7" As the plugin for placeholder already exists in the ckeditor, i expected it to work str8 out of the box one i added it to the toolbar .... no luck If i cant get it to work, ill probably create my own [[ placeholder ]] and have a string replace function in python to merge db fields. Any suggestions would be appreciated. -
Django ORM - add rows to the result until the SUM('column') reaches to a given number
I have a model created using Django ORM - class Orders: units = models.IntegerField(null=False, blank=False) sell_price_per_unit = models.FloatField(null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.PROTECT, null=False, blank=False) order_status = models.ForeignKey(OrderStatus, on_delete=models.PROTECT, null=False, blank=False) property = models.ForeignKey(Property, on_delete=models.PROTECT, null=False, blank=False) order_type = models.ForeignKey(Property, on_delete=models.PROTECT, null=False, blank=False) ... ... I want to write a query to select_for_update() and the rows should be selected until the Sum('sell_price_per_unit') reaches a given number. Additionally I have to apply certain filter and exclude certain rows based on the condition. filter() & exclude() were pretty straight forward so I already took care of it but I have no idea of how to select rows until the Sum('sell_price_per_unit') reaches to a given number. queryset = ( Orders.objects.select_for_update() .exclude(created_by=created_by) .values( "id", "property", "units", "created_by", "sell_price_per_unit", "order_status", ) .filter( property=order_obj.property, order_type__name=SELL, order_status__in=[PARTIALLY_COMPLETED[1], OPEN[1]], sell_price_per_unit__lte=order_price, ) .order_by("sell_price_per_unit", "created_at") ) Is it possible to accomplish this? -
login issue for imported users in django
i have 2 django application and i want importing users with passwords to another application when i do this, i have problem for login imported users cant login Note : i have custom user model this 2 application have SAME SECRET_KEY and here is my login code GetDomain = Domains.objects.filter(domain=get_domain(HTTP_HOST=request.META['HTTP_HOST'])).first() Email = request.POST.get('mail', None) raw_password = request.POST.get('pass', None) recaptcha_response = request.POST.get('g-recaptcha-response', None) if Email is None: return HttpResponse(ajax_result(Code=200, message='ایمیل خالی است')) if raw_password is None: return HttpResponse(ajax_result(Code=200, message='پسورد خالی است')) if recaptcha_response is None: return HttpResponse(ajax_result(Code=200, message='کد امنیتی را وارد کنید')) GetUser = User.objects.filter(email=Email).first() if GetUser is not None and GetUser.is_active: if GetUser.aff != GetDomain.UseBy.username: return HttpResponse(ajax_result(Code=200, message='کاربر یافت نشد')) if RecaptchaValidator(recaptcha_response): if not GetUser.is_superuser and not GetUser.is_staff: DeleteLastSessions(GetUser) user = authenticate(username=GetUser.username, password=raw_password) try: login(request, user) except AttributeError: return HttpResponse(ajax_result(message='اطلاعات ورود اشتباه است')) GetUser.Browser = request.META['HTTP_USER_AGENT'] GetUser.IsLogin = True GetUser.LastLoginIP = GetIP(request) GetUser.save() if GetUser.is_superuser or GetUser.is_staff: SubmitLog(user=request.user, Part='ورود به پنل', Number=None, Information=None, IP=GetIP(request)) threading.Thread(target=WriteUserExtraInformation, args=(request, GetUser,), name='WI').start() if GetUser.NeedVerify: Context = '{"result" : "ok", "data": {"url":"/tickets/send?verify=1"}}' else: if 'next' in request.GET.keys(): Context = '{"result" : "ok", "data": {"url":"' + request.GET['next'] + '"}}' else: Context = '{"result" : "ok", "data": {"url":"/profile/"}}' response = HttpResponse(Context) response.set_cookie('app', 'True', secure=True) return response else: … -
Django ORM - Search Function Across Multiple Models
I am struggling to get my search function to pull in results from multiple models into a single table. I have a Person Model and a Dates Model: class Person(models.Model): personid = models.AutoField() name = models.CharField() etc.... class Dates(models.Model): datesid = models.AutoField() personid = models.ForeignKey(Person, models.DO_NOTHING) date_type = models.CharField() date = models.CharField() etc.... There will be multiple Dates per personid (many to one) what I am trying to do is return the newest date from Dates when a search is performed on the Person Model - View below: def search(request): if request.method == "POST": searched = request.POST.get('searched') stripsearched = searched.strip() results = Person.objects.filter( Q(searchterm1__icontains=stripsearched) | Q(searchterm12__icontains=stripsearched) | Q(searchterm3__contains=stripsearched) ).values('personid', 'name', 'address_1', 'address_2', 'address_3', 'code', 'number') How would I add in the Top 1 newest related Dates.date into this for each Person found in the "results" field ? View: {% for Person in results %} <tr> <td>{{ Person.name }}</a></td> <td >{{ Person.address_1 }}</td> <td >{{ Person.code }}</td> </tr> {% endfor %} -
django oscar send_email result in ValueError: EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive,
This function trigger an error that doesn't make sense to me: File "/venv/virtualenvs/ZHR-f7z/oscar/apps/communication/utils.py", line 128, in send_email_messages email.send() in the settings: EMAIL_USE_SSL = None #False doesn't change result EMAIL_USE_TLS = None Someting wrong is happening as both are None so these can't be True: File "/venv/virtualenvs/ZHR-f7z/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 31, in __init__ self.use_ssl = settings.EMAIL_USE_SSL if use_ssl is None else use_ssl self.timeout = settings.EMAIL_TIMEOUT if timeout is None else timeout self.ssl_keyfile = settings.EMAIL_SSL_KEYFILE if ssl_keyfile is None else ssl_keyfile self.ssl_certfile = settings.EMAIL_SSL_CERTFILE if ssl_certfile is None else ssl_certfile if self.use_ssl and self.use_tls: raise ValueError( "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set " "one of those settings to True.") self.connection = None self._lock = threading.RLock() [console ready] >>> use_ssl >>> self.use_ssl 'None' >>> self.use_tls 'None' >>> If I start a shell with: >>> from django.core import mail >>> mail.send_mail( ... 'Subject here', 'Here is the message.', ... 'mailfrom', ['mailto'], ... fail_silently=False, ... ) result in a success. Any advice as the settings are both false and the ValueError should be trigger if both are True? Thanks, BR -
Expected a list of items but got type queryset
I want to make a get api that returns a json containing 3 tables. These 3 arrays must contain a list of different objects. I want to get as a result: { "array_1": [{"id", "name"}, {"id2", "name2"}], "array_2": [{"id", "date"}, {"id2", "date2"}], "array_4": [{"id", "otherfield"}, {"id2", "otherfield2"}], } My serializers: class Object1Serializer(serializers.ModelSerializer): class Meta: model = Object1 fields = ['id', 'photo',] class Object2Serializer(serializers.ModelSerializer): class Meta: model = Object2 fields = ['id', 'name', 'date'] class Object3Serializer(serializers.ModelSerializer): class Meta: model = Object3 fields = ['id', 'file'] class ObjectsSerializer(serializers.Serializer): object_1 = Object1Serializer(many=True, required=False) object_2 = Object2Serializer(many=True, required=False) object_3 = Object3Serializer(many=True, required=False) My view: class getObjectAPIView(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = ObjectsSerializer def get(self, request, machine_pk): user = request.user if not machine_pk: return Response("Missing id machine field", status=status.HTTP_400_BAD_REQUEST) if not Machine.objects.filter(pk=machine_pk).exists(): return Response("Machine not found", status=status.HTTP_404_NOT_FOUND) if not user.is_staff and not user.groups.filter(name="frigo").exists(): return Response("You are not allowed to access this machine", status=status.HTTP_403_FORBIDDEN) machine = Machine.objects.get(pk=machine_pk) object1 = Object1.objects.filter(machine=machine) object2 = Object2.objects.filter(machines=machine) object3 = Object3.objects.filter(client=machine.client) json_response = { "object1": object1.values(), "object2": object2.values(), "object3": object3.values(), } serializer = ObjectsSerializer(data=json_response) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) But I got an error: { "object1": { "non_field_errors": [ "Expected a list of items but got type \"QuerySet\"." ] }, "object2": { … -
Strategy to apply a common filter to all my graphene queries in a django project
When a user is asked to be removed from the system, I'll delete all his personal info like name and address from the auth_user table, but I'll keep all his system actions for internal analytics purposes. These analytics however, should not show up in our frontend web. For example, there's a table 'training' and one of the queries related to that is to see how many users are currently enrolled in a training. If an user has been removed he should not show up in there. Unfortunately I did the mistake of not creating a custom user model in the beginning of my Django project and it seems quite a hassle to do that now. Instead what I'm doing is to have a related model that links to the default User model. I created the RemovedUser model that simply flags that a user has been deleted. I know there is the 'is_active' field in the default model, but I don't want to use that one as I want to keep a distinction of actual completely removed users and inactive ones. Here is the model class RemovedUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) date_removed = models.DateTimeField(editable=False, default=timezone.now, help_text='Date the user was removed') Nothing … -
Taking over products together with the relationship of the categories django
I made a relationships as follows on products and categories. class Category(models.Model): DoesNotExist = None id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(verbose_name='category name', max_length=50) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) product_name = models.CharField(verbose_name='product_name', null=False, max_length=200) product_description = models.TextField(verbose_name='product description', null=False, max_length=1000) stock = models.IntegerField(verbose_name='stock', null=False) expire_date = models.DateTimeField(verbose_name='expire date') company = models.ForeignKey(Company, on_delete=models.CASCADE) store = models.ForeignKey(Store, blank=True, null=True, on_delete=models.SET_NULL) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name def get_cat_list(self): k = self.category # for now ignore this instance method breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb) - 1): breadcrumb[i] = '/'.join(breadcrumb[-1:i - 1:-1]) return breadcrumb[-1:0:-1] But I would like an output like this when I take over the products It`s possible? [ { "name":Cars, "slug":"cars", "subcategories":{ "id":, "name":, } }, ] And the view class is this products = Product.objects.all() product_serializer = ProductSerializer(products, many=True) return Response({'data': products.data}, status=200) So is there a functionality in … -
How to export the date entered in one model to the other using django
#model 1 class Timesheet(models.Model): project=models.ManyToManyField(Project) Submitted_by=models.ForeignKey(default=None,related_name="SubmittedBy",to='User',on_delete=models.CASCADE) status=models.CharField(max_length=200) ApprovedBy=models.ForeignKey(default=None,related_name="ApprovedBy",to='User',on_delete=models.CASCADE) Date =models.DateField() Hours=models.TimeField(null=True) #model 2 class Monday(models.Model): Dates=models.Foreignkey(Timesheet,related name='Dates',on_delete=models.CASCADE) def str(self): return self.Dates this was throwing an error and couldn't able to view the date inputted in Timesheet model in the Monday Model. Please help on solving this logic. -
How to integrate django-unicorn with chart.js?
Can anyone show me an example on how to integrate Django-unicorn with chart.js? I'm just new to this django-unicorn framework and a bit confused about its documentation. I just want to creat a real time graph using this framework. thanks. -
django validator for USA phone number validation with regex
how do i write a python function that takes phone as argument to validate with below model attributes with regex models.py class MyModel(models.Model): phone = Phonefield(max_length = 255,blank = True) -
My Vue app is displaying images vertically
I am making a Vue / Django app but any image I add is displaying vertically but the tut I am following, his own is displaying horizontally. I have trace back my code but found nothing. I add a screenshot of the code and images the code screenshot for the page and the screenshot of my webapp -
Django Query is not ordering / Sorting Correctly in pagination model in rest framework
I have 705 Meta#Data of Instagram videos but I am unable to sort it by name | id | uploading date or any order query. My MetaData model is class MetaData(models.Model): # Info id = models.IntegerField(primary_key=True) tag = models.CharField(max_length=500) # User Info username = models.CharField(max_length=400) followers = models.IntegerField() verified = models.BooleanField() profile = models.URLField() # Video Info upload_date = models.DateField() upload_time = models.TimeField() views = models.IntegerField() duration = models.CharField(max_length=50) comments = models.IntegerField() likes = models.IntegerField() dimension = models.CharField(max_length=50) framerate = models.CharField( max_length=100, blank=True, default='Not Found') # Post link = models.URLField() codecs = models.CharField(max_length=200, blank=True, default='Not Found') caption = models.CharField(max_length=100, blank=True, default='Not Set') status = models.CharField(max_length=20, choices=( ('Pending', 'Pending'), ('Acquired', 'Acquired'), ('Rejected', 'Rejected')), default='Pending') I am using Django rest framework pagination and getting my filters fields in parameters def fetchVideosContentwithFilter(request, filters, directory=None): paginator = PageNumberPagination() paginator.page_size = 12 # Parameters flts = ['upload_date'] if filters: flts = json.loads(filters) if 'upload_date' in flts: flts.append('upload_time') if directory and directory != 'all': objs = MetaData.objects.filter(tag=directory) else: objs = MetaData.objects.all() pages = paginator.paginate_queryset(objs.order_by(*flts), request) query = s.MetaDataSerializer(pages, many=True) return paginator.get_paginated_response(query.data) I also try or replace *paginator.paginate_queryset(objs.order_by(flts), request) with paginator.paginate_queryset(objs.order_by('-id'), request) but in vain data is not ordering correctly