Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
drf- discord like role permissions checking
relevant discussion is here. So I am building an api with architecture inspired by discord. I have objects called Boxes and these boxes have their own set of Roles. The role object looks like this. class Role(CoreModel): class Meta: ordering = ('position', 'box') permission_flags = ( 'ADD_STARS', 'DOWNLOAD_FILES', 'SEND_UPLOADS', 'MANAGE_UPLOADS', 'MANAGE_ROLES', 'MANAGE_BOX', 'MANAGE_INVITES', 'KICK_MEMBERS', 'BAN_MEMBERS' ) default_flags = ( 'ADD_STARS', 'DOWNLOAD_FILES', 'SEND_UPLOADS', ) color = ColorField( verbose_name=_('color'), help_text=_("role's hex color code"), default='#969696' ) hoist = models.BooleanField( verbose_name=_('hoist'), help_text=_("whether the role can be pinned"), default=False ) is_default = models.BooleanField( verbose_name=_('default'), help_text=_("whether the role is default"), default=False ) position = PositionField( verbose_name=_('position'), help_text=_("position for the role"), collection=('box', 'is_default') ) box = models.ForeignKey( to='uploads.Box', verbose_name=_('box'), on_delete=models.CASCADE ) name = models.CharField( verbose_name=_('name'), help_text=_("role name"), default='new role', max_length=100, validators=[ MinLengthValidator(2) ] ) permissions = BitField( verbose_name=_('permissions'), help_text=_("permission bit set"), flags=permission_flags, default=default_flags ) REQUIRED_FIELDS = (name, box) I am using the bitfield extension provided by disqus here. Roles have a set of predefined permissions which can be allowed or denied for a specific role, like MANAGE_ROLES # allows to manage box roles MANAGE_BOX # allows to manage and edit the box Now, users can be a part of the box, through a model called member, and … -
how to use inlineformset with js to add extra fields
i want to use inlineformset factory for my project ! i have write my own js to add more fields , but it only save the last form in child form ! i dont want to use jquery.formset.js this is my models.py class Main(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) company = models.ForeignKey(Companies,on_delete=models.CASCADE) items = models.ManyToManyField(Item,through='Child') invoice_number = models.IntegerField() class Child(models.Model): main = models.ForeignKey(Main,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField() and this is my views.py , i have used class based view class CreateMainInlineFormset(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = Main form_class = MainForm template_name = 'main/create.html' def get_context_data(self, *args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['items'] = ChildInlineFormSet(self.request.POST) data['items'].full_clean() else: data['items'] = ChildInlineFormSet() return data def form_valid(self, form): context = self.get_context_data() items = context['items'] with transaction.atomic(): self.object = form.save(commit=False) form.instance.admin = self.request.user if items.is_valid() and form.is_valid() and items.cleaned_data!={}: items.instance = self.object form.save(commit=True) items.save() else: return render(self.request,self.template_name,context) return super().form_valid(form) def get_success_url(self): return reverse_lazy('maininfo:list-item') and this is my template html + js script ,i think the problem is here , i dont know how increase child forms in a right way ! $("#addRow").click(function () { var html = $("#relInputs").clone(); $('#relatiedInput').append(html); }); $(document).on('click', '#removeRow', function () { if ($("#relatiedInput> #relInputs").length != 1) $(this).closest('#relInputs').remove(); }); <div class="mt-1 text-right mx-auto" style="direction: rtl;"> … -
Django Channels - Mark user as online and offline
How can we use django channels to mark user as online and offline? Means using websocket is it possible to mark user as offline or online? If not, what all are the other possible ways to mark user as online and offline, like how it is done in facebook, instagram and all? In frontend, I want to show green ball in case user is online and red ball in case user is offline. -
Django to modify value in body and return it
class LocationRetrieveSerializer(serializers.ModelSerializer): class Meta: model = UserAttributes fields = '__all__' def create(self, validated_data): logger.info(self.context["request"].user.aerosimple_user) if UserAttributes.objects.filter(user_id=self.context["request"].data['user']).exists(): raise serializers.ValidationError("User Already exists.") user_attributes = UserAttributes.objects.create(**validated_data) return user_attributes i want to change the value in the body and should return it with the changed value in the body -
What is the difference between the types of CORS settings?
I searched to solve the cross domain that occurs when deploying django to the google cloud app engine and found three solutions. The cross domain problem has not been solved yet, but I have a question. GCP storage CORS setting https://cloud.google.com/storage/docs/cross-origin?hl=en GCP app.yaml setting https://cloud.google.com/appengine/docs/standard/python3/config/appref?hl=en django-cors-headers https://pypi.org/project/django-cors-headers/ Are there any differences between the three? -
Chartjs not parsing JsonResponse (Django and Chartjs)
I'm trying to get a pie chart (Chart.js) rendered from my django model; however, instead I'm getting my Json data rendered to my localhost (see picture). here's my code for reference (also, the JsonReponse is a class because I'm using Django 1.6.11 and JsonReponse was only formally added to django >= 1.7) views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from django.contrib import messages from django.utils import simplejson from django.middleware.csrf import get_token from django.db.models import Count from .models import Member, Driver, Order, Distance import json class JsonResponse(HttpResponse): # Code for JSONResponse - not in Django 1.6.11 def __init__(self, content, mimetype='application/json', status=None, content_type=None): super(JsonResponse, self).__init__( content=simplejson.dumps(content), mimetype=mimetype, status=status, content_type=content_type, ) def homepage(request): # pie chart for payment type queryset = Order.objects.order_by('payment').values('payment').annotate(payment_type=Count('payment')) data = list(queryset.values_list('payment_type', flat=True)) labels = list(queryset.values_list('payment', flat=True)) return JsonResponse({ 'labels' : labels, 'data' : data, }) urls.py from django.conf.urls import patterns, include, url from django.contrib import admin from mysite import views urlpatterns = patterns('', url(r'^$', 'mysite.views.homepage', name='payment-chart'), ) base.html <div class="payment_chart"> <canvas id="payment_chart" data-url="{% url 'payment-chart' %}"> </canvas> </div> <script> $(function () { var $paymentChart = $("#payment-chart"); $.ajax({ url: $paymentChart.data("url"), success: function(data) { var ctx = $paymentChart.getContext("2d"); new Chart(ctx, { type: 'pie', data: { labels: labels, … -
How to Router Redirect After Login in Django
from django.urls import reverse from django.http import HttpResponseRedirect from django.shortcuts import redirect def auth_middleware(get_response): def middleware(request): #print(request.session.get('customer')) returnUrl = request.META.get('PATH_INFO') #print(request.build_absolute_uri()) if not request.session.get('customer'): return HttpResponseRedirect(reverse(f'store:login?return_url={returnUrl}')) print('middleware') response = get_response(request) return response return middleware -
Django Query results null queryset
In my models I have an Allotment model: class AllotmentFlow(models.Model): flow = models.ForeignKey(Flow, on_delete=models.CASCADE) kit = models.ForeignKey(Kit, on_delete=models.CASCADE) asked_quantity = models.IntegerField(default=0) alloted_quantity = models.IntegerField(default=0) class Allotment(models.Model): transaction_no = models.IntegerField(default=0) dispatch_date = models.DateTimeField(default=datetime.now) send_from_warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) sales_order = models.ForeignKey(MaterialRequest, on_delete=models.CASCADE) flows = models.ManyToManyField(AllotmentFlow) I am querying this model like following: for k in d_o.demand_flows.all(): print("k", k.kit.kit_name) items = Allotment.objects.filter(dispatch_date__year = m.year, dispatch_date__month = m.month, flows__kit=k.kit.pk).aggregate(Sum('flows__alloted_quantity')) print("items", items) While running this query I can see in the terminal that k.kit.pk, m.year and m.month are being passed correctly and it still return the empty queryset m 1 y 2020 k KIT1182D items <QuerySet []> Whereas, I can see from other module that the ORM contains the data: Is there a problem with the query? -
Refused to execute script from 'bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled
I have an application with CRA with frontend and django backend. I use react-app-rewired to override webpack configuration on frontend so that to save output from webpack-dev-server for django to use. But I hit the issue as shown in below screenshot. Below is my override-config.js which used to override out-of-box CRA webpack config Weird thing is that there is no such issue for frontend product build(run yarn build and then open localhost:8000 in browser and I can get frontend correctly). Above Refuse to execute ... issue only happen when I run yarn start for development mode. Here is my package.json And django frontend.html Relative part in django settings.py Thanks in advance for any help! -
Django form instance value not displayed in Pop-up form
I'm working on task where I want to update data with bootstrap Modal(Pop-Up) form. I can able to update the data but I couldn't see the previous data(instance not displayed in the pop-up form). Example. If I have data with the name apple and I want to update it to banana that apple value instance was not displayed in the pop-up form. models.py class Todo(models.Model): date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) title = models.CharField(max_length=200) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title class Task(models.Model): heading = models.CharField(max_length=100) todo = models.ForeignKey(Todo, on_delete=models.CASCADE, related_name='tasks') date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.heading views.py from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse, Http404, HttpResponseNotFound, JsonResponse, HttpResponseRedirect from .models import Todo, Task from .forms import * from django.utils import timezone from django.contrib.auth.forms import UserCreationForm from django.views.decorators.csrf import csrf_protect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.generic import View from django.contrib.auth.models import User from django.core.paginator import Paginator from django.views.decorators.http import require_POST def register(request): form = userRegisterForm() if request.method == 'POST': form = userRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password2') return redirect('login') else: form = userRegisterForm() context = {'form': form} return … -
How to provide a console connection to a kubernetes pod on a django app
I have a Kubernetes cluster with pods in it. I want to provide a console connection to a pod on a HTML page in a Django app. -
Cookie only set on login page
I'm trying to set a cookie application wide but it only gets set on the path /login. Here's my code axios .post("api/auth-token"/, {username, password}) .then(response => { const { token } = response.data; document.cookie = "authtoken=" + token; // Registering cookie window.location.replace("/app/dashboard"); }); But when I visit other pages, this cookie is not present. When I check the Applications section in the developer tools, I noticed the cookie has a path of /login so I guess this is why other pages can't see it. But when I try to add a path using this document.cookie = `authtoken=${token}; path=/;max-age=120`; My token still gets set to /login only. The max-age is just for development purposes. I've even tried to use a library like https://github.com/js-cookie/js-cookie and set my cookie using Cookies.set('authtoken', token, { path: '/' }); but my cookie still only gets set for that page. What could the be the cause of my cookie getting registered only on the login page. Not sure if this is useful information but my backend is in Django and my pages are django templates. But I get data from the server using REST. -
How to direct a page from a form Django
I am working on a dictionary app, i am allowing a user to enter a word through a form. When the word is entered in the form and a submit button is pressed i want the form to be maintained on the same page however when the user enter the word and presses submit the form disappears leaving only the submit button and the search results Here is the dictionary/form code class NameForm(forms.Form): your_name = forms.CharField(max_length=100, label=False) the dictionary/view code def index(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): word = form.cleaned_data['your_name'] print(word) if Dictionary.get_verb(word): verb = Dictionary.get_verb(word) else: verb = False print(verb) if Dictionary.get_noun(word): noun = Dictionary.get_noun(word) else: noun = False print(noun) synonyms = Dictionary.get_synonyms(word) print(synonyms) form = NameForm() context = { 'verb':verb, 'noun':noun, 'synonyms':synonyms, } return render(request,'index.html' ,context) else: form = NameForm() context = { 'form': form, } return render(request, 'index.html', context) and the index.html form action="" method="post"> {% csrf_token %} {{form}} <br> <input type="submit" value="Submit"> </form> <hr> {% if noun %} <h2>Noun</h2> {% for noun_word in noun %} <p>{{noun_word}}</p> {% endfor %} {% else %} <!-- print nothing--> {% endif %} <br> <hr> {% if verb %} <h2>Verb</h2> {% for verb_info in verb %} <p>{{verb_info}}</p> … -
Django dropdown select get data from database
I have a table : Cars with field carID,CarName PaymentType field paymentTypeID, PaymentTypeName Carprice field priceID,CarID,paymentTypeID, amountPrice I already show Cars and paymentType to dropdown select. how i can show Carprice after user selectCar and selectPayment? best regards, Capah Maga -
Django service worker deletes cache when offline
thanks for your time. I'm trying to get a a django PWA to work offline. I'm able to install the app, save the cache but when i try to load it offline, the cache that had created desapear. note: i'm passing the sw.js and manifest.json files trough urls with TemplateView class. sw.js: { const cacheName = 'cache-v1'; const resourcesToPrecache = [ "{% url 'sw.js' %}", "{% url 'home' %}", "{% url 'install_sw' %}" ]; self.addEventListener('install', function (event) { console.log('sw install event!'); event.waitUntil( caches.open(cacheName) .then(function (cache) { console.log('cache added') return cache.addAll(resourcesToPrecache); } ) ); }); self.addEventListener('fetch', function (event) { console.log(event.request.url); event.respondWith( caches.match(event.request).then(function (response) { return response || fetch(event.request); }) ); }); }; console.log('ok') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('config/', include('config.urls')), path('products/', include('products.urls')), path('cart/', include('cart.urls')), path('accounts/', include('allauth.urls')), path('home/', home_view, name='home'), path('sw.js/', (TemplateView.as_view(template_name="admin/sw.js", content_type='application/javascript', )), name='sw.js'), path('manifest.json/', (TemplateView.as_view(template_name="admin/manifest.json", content_type='application/json', )), name='manifestjson'), path('install_sw/', (TemplateView.as_view(template_name="admin/install_sw.html", content_type='text/html', )), name='install_sw'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) manifest.json { "short_name": "Mega", "name": "MegaMagazine", "scope": "/", "icons": [ { "src": "/static/m1.png", "type": "image/png", "sizes": "144x144" } ], "start_url": "/", "background_color": "#3367D6", "display": "standalone", "theme_color": "#3367D6", "prefer_related_applications": false } install_sw.html <!doctype html> <head> <link rel="manifest" href="{% url 'manifestjson' %}"> </head> <title>installing service worker</title> <body> <img src="/static/m1.png" … -
Django Rest Framework and Channels, You cannot call this from an async context
What i am trying to do is to nest a DRF model serializer into another model serialiser's field like so class username_serial(ModelSerializer): class Meta: model = User fields = ['username','email'] class game_serial(ModelSerializer): user_01 = username_serial() class Meta: model = game fields = ['id','user_01','user_02','is_private','is_accepted'] Error : Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "C:\Users\baza\Desktop\production\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 173, in get rel_obj = self.field.get_cached_value(instance) File "C:\Users\baza\Desktop\production\venv\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'user_01' This works normally without Django Chennels because channels is async and i can't use sync code with, works fine by using: os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" In the settings file but it's not a safe approach when it comes to production. i tried using channel's database_sync_to_async as a decorator and as well as a function with a SerializerMethodField like so: class game_serial(ModelSerializer): user_01 = SerializerMethodField(read_only=True) @database_sync_to_async def get_user_01(self, obj): username = obj.user_01.username return str(username) class Meta: model = game fields = ['id','user_01','user_02','is_private','is_accepted'] but i get back: [OrderedDict([('id', 23), ('user_01', <coroutine object SyncToAsync.__call__ at 0x0000000005DF6678>), ('user_02', None), ('is_private', False), ('is_accepted', False)]), OrderedDict([('id', 24), ('user_01', <coroutine object SyncToAsync.__call__ at 0 x0000000005DF6D58>), ('user_02', None), ('is_private', False), ('is_accepted', False)])] with … -
Django Form Wizard Skip Multiple Steps with Conditional Logic
Is there some way to skip multiple steps in Django's Form Wizard (i.e. SessionWizardView)? I know it is possible to use condition_dict to produce the following form display logic: Page 1 -> Page 3 #urls.py path('main/', MyWizard.as_view(set_of_forms, condition_dict={'1': view_condition} )) What I would like to do is the following: Page 1 --> Page 4 Presumably, adding a condition_dict based on the content of Page 1 should work to skip Page 3, but it doesn't work. For example: #urls.py path('main/', MyWizard.as_view(set_of_forms, condition_dict={'1': view_condition, '2': view_condition2,} )) I am truly stumped on how to crack this nut. Any guidance that you can provide would be GREATLY appreciated. -
DRF API limit&offset list index out of range
I'm writing a simple API to get data from models and with LimitOffsetPagination the API show count the total number of record is 7127 But when I try to move to next page, it will show list index out of range error here is my Pagination setting: class LimitOffsetPagination(LimitOffsetPagination): default_limit = 10 default_offset = 10 offset_query_param = "offset" limit_query_param = "limit" it run correctly when limit=10&offset=60, however when click on next (limit=10&offset=70) it will show the out of range error. Whats going on? -
Not able to load multiple blocks in base template in Django
I am having a problem in my templates. I am trying to add two blocks in the base template, it works when I include them but when I try to extend the base template it won't work and won't even throw an error. -
django save a new instance of object
I am trying to update a user "karma points" whenever a user posts something. For this, i first created a new model called Myuser that allows for points property: class Myuser(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) points=models.IntegerField(default=1) And then in my view.py post_new() function, I tried to update the score: u=User.objects.get(username=request.user.username) u.myuser.points=u.myuser.points+5 u.save() but then i notice that rather than update the points field, it just saves a new instance with the same user id but updated score. I thought .save() is supposed to update exisiting copy. -
Pls help me, File "C:\Python39\lib\os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'DJANGO_ENV'
mau ngejalanin program Python Framework django. pas mau runserver app saya terdapat error seperti ini File "C:\Python39\lib\os.py", line 679, in getitem raise KeyError(key) from None KeyError: 'DJANGO_ENV' enter image description here mohon d bantu -
Django 3.1 - "OperationalError: no such table" when using an ORM Class Model before making or applying a migration
The Problem Whenever I create a new model class inside products/models.py (products is the name of my Django app), I cannot reference such model (e.g. Product model) in any method or class before having made and run the migrations. Otherwise, if I reference the new model in the code and then I run any of the following commands/procedures, I receive the OperationalError: no such table error: python manage.py runserver python manage.py makemigrations [appname] python manage.py migrate python manage.py showmigrations Delete all existing migrations and try to regenerate them with python manage.py makemigrations [appname] Delete current db.sqlite3 file; delete all existing migrations and try to regenerate them with python manage.py makemigrations [appname] The error looks like this: ... File "/Users/my_user/Work/django_proj_1/config/urls.py", line 21, in <module> path('', include('products.urls')), ... File "/Users/my_user/Work/django_proj_1/products/urls.py", line 1, in <module> from products.api_views import ProductList3 File "/Users/my_user/Work/django_proj_1/products/api_views.py", line 7, in <module> class ProductList3(ListAPIView): File "/Users/my_user/Work/django_proj_1/products/api_views.py", line 8, in ProductList3 queryset = get_products() File "/Users/my_user/Work/django_proj_1/products/data_layer/product_data_layer.py", line 4, in get_products all_prods = list(Product.objects.values()) ... File "/Users/my_user/.local/share/virtualenvs/django_proj_1-a2O6RBaf/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: products_product ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The Real Question This behavior may seem normal, but if you think about it, how would a developer make a release … -
How to filter the objects related to foreign key model in django Views.py
I have models.py as like this: class Subject(models.Model): sub = models.CharField(max_length=200) slug = models.SlugField(unique=True) created_on = models.DateTimeField(auto_now_add=True) class Post(models.Model): sub = models.ForeignKey(Subject, on_delete=models.CASCADE) file_name = models.CharField(max_length=50,blank=True) url = models.CharField(max_length=800, unique=True) urls.py path('view/<subj>/', views.PostDetail, name='post_detail'), views.py def PostDetail(request, subj): content = Post.objects.get(sub=subj) But I'm getting this error when i pass subj as sig from url, invalid literal for int() with base 10: 'sig' How to get all the objects related to the query subj i.e "sub" in Post model? -
how to use Authentication in django with prodection
I am using django JWT for permission and rest_framwork. there is one question. if one user uploads one post and wants to modify/delete post OR wants to change own's profile, definitely user requests restAPI. and in the http(s) request maybe there is some information about user, like "localhost:8000/data/change/userid/" OR exists in post body. point is i think if someone(like hackers) catch others id(or ID number) and pretending them server doesn't know that who is real owner does it? how can i protect or encrpt? -
How to upload file image to server using multipart/form-data [flutter to django server]
I have an api using django python and I am using camera package of flutter to take a picture and I would like to send the file picture to server using api post request, so far I have been trying using dio and http package to send it, but the image file is not recognise in server, here is the code for dio package String fileName = file.path.split('/').last; FormData formData = FormData.fromMap({ "file": await MultipartFile.fromFile(file.path, filename: fileName), }); var response = await dio.post( "http://xxx/xxx/", data: formData); print(response); and here is the code when using http package sending(List<int> myFile){ Map<String, String> headers = { "Content-Type": "multipart/form-data" }; var url = Uri.parse("http:xxx/xxx"); var request = new http.MultipartRequest("POST", url); request.headers.addAll(headers); request.files.add(new http.MultipartFile.fromBytes('file', myFile, contentType: new MediaType('application', 'octet-stream'), filename: name)); var response = await request.send(); final respStr = await response.stream.bytesToString(); print(respStr); } this question is a duplicate from this How to upload images and file to a server in Flutter? is there a way to upload file image to server ?