Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
password_reset does not pick from_email
I have my email setup for entire django project and it works fine. When it comes to reset password in the following url: http://127.0.0.1:8000/rest-auth/password_reset/ and after submitting the email, it throws: SMTPDataError at /rest-auth/password_reset/ (550, b'The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. when I digged into the issue I noticed that this view doesn't catch from_email at all: If I manually enter the email here, everything works fine. I am wondering what is gone wrong that email is not read! -
Django IOT project
I am working in a Django project building a web application with a few features one of them is showing data from sensor connected to ESP8266 on a page on the project how can I POST these data showing on arduino to the project to use them in an app? (project includes creating users with API token if it's important) -
Django form does'nt render even if the code seems alright
I am beginner to Django. I have just started learning basic forms and here is the code which does'nt work. The method specified for the form in form_page.html is POST, so accordingly in views.py it must render me form_page.html but instead it prints thanks which means it does'nt recognize the method as post and run the else code snippet.Can you help me fix it!! Views.py from django.shortcuts import render from django.http import HttpResponse from .forms import formname def index(request): return render(request,'index.html') def form_name_view(request): if request.method == 'POST': form=formname(request.POST) if form.is_valid: print('NAME:',form.cleaned_data['name']) print('email:',form.cleaned_data['email']) print('text:',form.cleaned_data['text']) return render(request,'form_page.html',{'form':form}) else: form=formname() return HttpResponse('thanks') form_page.html <!doctype html> <html lang='en'> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <title> Basic forms </title> <head> <body> <h1>Fill out the form</h1> <div class="container"> <form method="POST"> {{form.as_p}} {% csrf_token %} <btn type="submit" class="btn btn-primary ">Submit</btn> </form> </div> </body> </html> forms.py from django import forms from django.core import validators class formname(forms.Form): name=forms.CharField() email=forms.EmailField() text=forms.CharField(widget=forms.Textarea) urls.py from django.contrib import admin from django.urls import path from basicformsapp import views from django.conf.urls import url urlpatterns = [ url(r'^$',views.index,name='index'), path('admin/', admin.site.urls), url(r'^formpage/',views.form_name_view,name='form_name_view') ] -
How can I bundle my JSON API data into one dictionary?
I'm trying to package my API data into one GET request simply using standard libraries python. class GetData(APIView): def get(self, request, *args, **kwargs): urls = [url_1, url_2, url_3, url_4 ] data_bundle = [] for x in urls: response = requests.get(x, headers={'Content-Type': 'application/json'}).json() data_bundle.append(response) return Response(data_bundle, status=status.HTTP_200_OK) The return response has to be JSON data, I'm trying to get it to work but it seems like the response data seems to be overiding eachother? How can I properly create a JSON dictionary of dictionaries. I've tried switching data_bundle to an empty dictionary instead of a list. However that just caused an error saying: ValueError: dictionary update sequence element #0 has length 8; 2 is required Is there a simple way to accomplish this that I'm missing? Thank you for the help. -
Django. How to design model so not to have vertical repetition for common name and family name?
In the below model there are fields like name and family name that will be repeated. For example Jhon or Jack would be common name which are bound to repeat themselves. Is there any better way to avoid this or this is ok by normalization standards of data models designs? class PropertyOwner(models.Model): name = models.CharField(max_length=200) family_name = models.CharField(max_length=200) contact_number = models.PositiveIntegerField() email = models.EmailField() def __str__(self): return self.name Is the fact that some names and family names will repeat themselves be a problem or better way to do this? -
'NoneType' object has no attribute 'id' in Django
I get the 'NoneType' object has no attribute 'id' error when opening a URL which view is this one: @login_required def order_checkout_view(request): product_id = request.session.get("product_id") or None if product_id == None: return redirect("/") product = None try: product = Product.objects.get(id=product_id) except: return redirect("/") user = request.user order_id = request.session.get("order_id") order_obj = None new_creation = False try: order_obj = Order.objects.get(id=order_id) except: order_id = None if order_id == None: new_creation = True order_obj = Order.objects.create(product=product, user=user) if order_obj != None and new_creation == False: if order_obj.product.id != product.id: order_obj = Order.objects.create(product=product, user=user) request.session['order_id'] = order_obj.id form = OrderForm(request.POST or None, product=product, instance=order_obj) if form.is_valid(): order_obj.shipping_address = form.cleaned_data.get("shipping_address") order_obj.billing_address = form.cleaned_data.get("billing_address") order_obj.mark_paid(save=False) order_obj.save() del request.session['order_id'] return redirect("/success") return render(request, 'orders/checkout.html', {"form": form, "object": order_obj}) The exception location is in this line if order_obj.product.id != product.id: There's an existing product in the database, however does this mean in this case the Product is 'None'? What could be the problem here? -
Flatpickr datetime field showing the wrong date in Edit form
I am working on an EDIT form to amend a specific record from a PGSQL table. The widget works well to select and save date, but when the EDIT page loads, the Start date of the record is incorrect. Below i call the actual date as it is saved in PG and the same exercise using the FlatPicker widget <label>Start Date</label> <div> {{ restricted_name_obj.Restriction_Start_Date }} <input type="hidden" name="Restriction_Start_Date" required="" id="Restriction_Start_Date" fp_config="{&quot;value&quot;: &quot;{{ restricted_name_obj.Restriction_Start_Date }}&quot;, &quot;id&quot;: &quot;fp_14&quot;, &quot;picker_type&quot;: &quot;DATETIME&quot;, &quot;linked_to&quot;: &quot;fp_13&quot;, &quot;options&quot;: {&quot;value&quot;: &quot;{{ restricted_name_obj.Restriction_Start_Date }}&quot;,&quot;mode&quot;: &quot;single&quot;, &quot;dateFormat&quot;: &quot;Y-m-d H:i:S&quot;, &quot;altInput&quot;: true, &quot;enableTime&quot;: true}}" class="flatpickr-input" value="{{ restricted_name_obj.Restriction_End_Date }}"> </div> But for some reason, the year is correct (always but day, month and hours/minutes are incorrect. I suspect there might be a formating to do while passing data to the field, but how ? Here is how it looks : -
wy in DB table is not creating and showing this errors invalid foreignKey in Django
wy in DB table is not creating and showing this errors invalid foreignKey .IntegrityError: The row in table 'myecomapp_toplist' with primary key '2' has an invalid foreign key: myecomapp_toplist.subcategory_id contains a value '1' that does not have a corresponding value in myecomapp_subcategory.id. models.py class TopList(models.Model): image = models.ImageField(upload_to='ProductImg') title = models.TextField(max_length=500) discountpercentage = models.IntegerField(blank=True,null=True) discountPrice = models.IntegerField(blank=True,null=True) brandName = models.TextField(max_length = 100 , default='',null=True,blank=True) desc = models.TextField(max_length=5000 ,null=True,blank=True) finalprice = models.IntegerField(blank=True,null=True) category = models.ForeignKey(ProductCategory , on_delete=models.CASCADE , default=1) subcategory = models.ForeignKey(subcategory , on_delete=models.CASCADE , default=1) class ProductCategory(models.Model): name = models.CharField(max_length=20) @staticmethod def get_all_categories(): return ProductCategory.objects.all() def __str__(self): representtion of this model object return self.name class subcategory(models.Model): name = models.CharField(max_length=20) MainCategory = models.ForeignKey(ProductCategory , on_delete=models.PROTECT) def __str__(self): return self.name admin.py @admin.register(subcategory) class SubcategoryAdmin(admin.ModelAdmin): list_display = ['name'] @admin.register(FirstSliderData) class FirstsliderModelAdmin(admin.ModelAdmin): list_display=['id','image','title' ,'category'] @admin.register(TopList) class TodoListModelAdmin(admin.ModelAdmin): list_display=['id','image','title' ,'category'] -
Django: values_list(flat=True) but for multiple fields
I have a model, TestModel As far as I know, if I were to implement TestModel.objects.values_list('FieldA', flat=True) This results in [A,B,C,(...)] (a list) And doing this TestModel.objects.values_list('FieldA','FieldB') results in [(A,1),(B,2),(C,3),(...)] (a list of querysets) But is it possible to get a similar result to Flat=True but for multiple fields? So, if I were to use something like testQS = TestModel.objects.values_list('FieldA','FieldB') and call testQS['FieldA'], this will return [A,B,C,(...)] Likewise, calling testQS['FieldB'] will return [1,2,3,(...)] Basically, I want to get all the data from a certain field in a values_list with multiple fields without resorting to for loop or creating values_list multiple times for each field. -
Cannot see my object models in Django admin view
I'm a relative Noobie at Django and have an issue with the admin interface. I am not able to see any of my custom object models, but I can see only the 'Groups' (under Authentication & Authorization), and 'Users' objects (under my 'CrushIt' app) (based on 'abstractuser') I used the startproject script to create my project (wedgeit) and app (CrushIt), and have gone through all the tips in the Django admin documentation, to try to troubleshoot the issue (see below). I also went through all the queries from other users I could find, but I'm still stuck. P.S. I can see my models from the shell and can create instances also, but they don't appear in the admin interface. Any hints would be appreciated. First time posting here so apologies if I've done something very stupid :D > Generated by 'django-admin startproject' using Django 3.0.8. Project settings file settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'CrushIt.apps.CrushItConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'wedgeit.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] apps.py … -
python-logstash and python-logstash-async not working with django
I tried two libraries to send some logs from our Django backend to our logging server: python-logstash python-logstash-async Here are the things I also tried/verified: Verify the Ec2 security group is accepting on port tcp/5000 (logstash) Monitor traffic from local machine and logging server to verify any network traffic. Using nc I was able to verify test logs being send and receive to our logging server. Re-create a bare minimum django project to see if there is an issue from versioning I'm sending logs after running the manage.py runserver class AppConfig(AppConfig): name = 'app' def ready(self): logger.info('info local django logging ') logger.error('debug local django logging ') logger.debug('debug local django logging ') print('logging init') This are the similar links that I've already checked: python-logstash not working? How to use python-logstash on Django settings.py (python-logstash-async) LOGGING = { 'formatters': { 'logstash': { '()': 'logstash_async.formatter.DjangoLogstashFormatter', 'message_type': 'python-logstash', 'fqdn': False, # Fully qualified domain name. Default value: false. 'extra_prefix': 'dev', # 'extra': { 'environment': 'local' } }, }, 'handlers': { 'logstash': { 'level': 'DEBUG', 'class': 'logstash_async.handler.AsynchronousLogstashHandler', 'transport': 'logstash_async.transport.TcpTransport', 'host': 'my.remote.host', 'port': 5000, 'ssl_enable': False, 'ssl_verify': False, 'database_path': 'memory', }, }, 'loggers': { 'django.request': { 'handlers': ['logstash'], 'level': 'DEBUG', 'propagate': True, }, }, } Logstash … -
Change file name upload image in Django
Im having a trouble on how can I rename my image file to prevent duplication of filename. Currently I have a list of photos which can upload the filename to the database and it will automatically create folder and save those selected photos to my media folder. All I want is every image filename must be unique. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance views.py @login_required(login_url='log_permission') def scanned_docs_add(request): if request.method == 'POST': gallery = folder_info.objects.create( title = request.POST.get('title'), date_upload = datetime.date.today() ) for file in request.FILES.getlist('photos[]'): #imagefile-------- oas = gallery_photos.objects.create( gallery_info_id = gallery.id, photos = file, ) return JsonResponse({'data': 'success'}) models.py class folder_info(models.Model): title = models.CharField(max_length=50,blank=True, null=True) date_upload = models.DateField(null=True, blank=True) class Meta: db_table = "folder_info" class gallery_photos(models.Model): gallery_info_id = models.IntegerField() photos = models.FileField(upload_to='Photos/', unique=True) class Meta: managed = False db_table = 'gallery_photos' html <form id="uploadevent" > {% csrf_token %} <input type="file" multiple data-bind="fileInput: multiFileData, customFileInput: { }" accept="image/*" name="photos[]" required=""> <button type="submit" class="btn btn-outline-primary">Save changes</button> </form> Script <script type="text/javascript"> $('#uploadevent').on('submit', function(e){ $.ajax({ data : new FormData(this), url : "{% url 'scanned_docs_add' %}", type : 'POST', cache : false, contentType : false, processData : false }) … -
Django error 'WSGIRequest' object has no attribute 'request'
i made function of delete a student, it works but messages.info(self.request, student.name + ' blah blah blah ', extra_tags='danger') in views.py makes an error, error is 'WSGIRequest' object has no attribute 'request' Thank you guys and Happy new year ! my views.py class StudentUpdate(UpdateView): model = Student template_name = 'student/list_edit.html' context_object_name = 'student' form_class = AddStudent def form_valid(self, form): student = form.save(commit=False) student.save() return super().form_valid(form) . . . . . def delete_student(self, pk, school_year): student = get_object_or_404(Student, school_year=school_year, pk=pk) messages.info(self.request, student.name + ' blah blah blah ', extra_tags='danger') student.delete() return reverse('student_detail', kwargs={'pk':pk,'school_year':school_year}) my html function deleteconfirm(){ $('.delete-message').dialog({ dialogClass:"confirm-modal", modal: true, buttons: { "delete": function() { $(location).attr("href"," {% url 'delete_student' student.school_year student.pk %} "); }, "cancel": function() { $(this).dialog('close'); }, }, . . . . my urls.py urlpatterns = [ . . . . . path('student/<school_year>/<pk>/delete/', views.StudentUpdate.delete_student, name='delete_student'), ] -
How to restrict FloatField dynamically in Django?
I want restriction of weight(FloatField in redirectLink), max_value will change dynamically. But can not understand how can I implement those codes in CreateView or in Models.py. Here is my code: models.py class MinMaxFloat(models.FloatField): def __init__(self, min_value=None, max_value=None, *args, **kwargs): self.min_value, self.max_value = min_value, max_value super(MinMaxFloat, self).__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = {'min_value': self.min_value, 'max_value' : self.max_value} defaults.update(kwargs) return super(MinMaxFloat, self).formfield(**defaults) class redirectLink(models.Model): parameter = models.ForeignKey(shortenUrl, on_delete=models.CASCADE) url = models.URLField() country = CountryField(multiple=False, blank=True, null=True) weight = MinMaxFloat(min_value=0.0, max_value=1.0) My question is how can I add max_value restriction as below in CreateView or in Models.py? max_value = redirectLink.objects.filter(parameter=Shortenurl).aggregate(Sum('weight')).weight__sum #Shortenurl is a specific parameter -
Websockets with Django Channels on Heroku
I am trying to deploy my app to heroku. The app has a simple chatting system that uses Websockets and django channels. When I test my app using python manage.py runserver the app behaves just as intended. I tried deploying the app and all features work except for the chatting system. Here is the error message I am getting in the Chrome Console: layout.js:108 Mixed Content: The page at 'https://desolate-lowlands-74512.herokuapp.com/index' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://desolate-lowlands-74512.herokuapp.com/ws/chat/19/'. This request has been blocked; this endpoint must be available over WSS. This is what I tried to fix it: I went from ws to wss I changed this: const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + friendship_id + '/' ); console.log(chatSocket) to this: const chatSocket = new WebSocket( 'wss://' + window.location.host + '/ws/chat/' + friendship_id + '/' ); console.log(chatSocket) with this change the websocket loads but the chatting system still doesn't work. The messages still don't get sent or received This is the error message I get when opening the Chatbox: layout.js:108 WebSocket connection to 'wss://desolate-lowlands-74512.herokuapp.com/ws/chat/19/' failed: Error during WebSocket handshake: Unexpected response code: 404 and this is the error message I … -
Django, Docker, postgreSQL Accepting TCP/IP connections on port 5432?
I I am using Docker and I got this message : Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Here is my docker-compose : version: '3.7' services: web: container_name: web build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/web/ ports: - 8000:8000 - 3000:3000 stdin_open: true depends_on: - db db: container_name: db image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_HOST_AUTH_METHOD=trust - POSTGRES_USER=admin - POSTGRES_PASSWORD=pass - POSTGRES_DB=mydb - POSTGRES_HOST=localhost volumes: postgres_data: I precise I change the value of the parameter 'HOST' in the settings.py to db but it does not work I still have this error. Could you help me please ? -
Is possible to implement this function with a single django ORM query?
I'm making an aggregate report of stores, categories and customers for an ecommerce. Basically, I'm trying to achieve what this function does: from django.db.models import ExpressionWrapper, DecimalField, F, Sum from .models import Order def get_report_data(stores, categories, customers): result = [] for store in stores: for category in categories: for customer in customers: total = Order.objects.filter( store=store, orderitem__product__category=category, customer=customer, ).aggregate( total=Sum( ExpressionWrapper( F("orderitem__product__price") * F("orderitem__quantity"), output_field=DecimalField(), ) ) )["total"] result.append([store, customer, category, total]) return result Obviously, this is efficiently poor and I'm trying to turn this function into a query. I've tried the following, but I know I'm missing the mark by A LOT. total = ( Order.objects.filter( store__in=stores, customer__in=customers, orderitem__product__category__in=categories, ) .values("store", "orderitem__product__category") .annotate( total=Sum( ExpressionWrapper( F("orderitem__product__price") * F("orderitem__quantity"), output_field=DecimalField(), ) ) ) ) How should I proceed? Thank you very much! -
Django chained/dependant dropdown
I'm making a project in which I need to implement a chained dropdown, the users select first their state, then their County, and then their Neighborhood, I've been looking into a lot of options and all of them are for either only two selects (like country then city), or for a function based view, and replicating this code in my class based view it isn't working. I'd very much appreciate any help. I'm new to Django. Here are my models for location.models.py: class Estado(models.Model): estado = models.CharField(max_length=100) def __str__(self): return self.estado class Municipio(models.Model): municipio = models.CharField(max_length=100) estado = models.ForeignKey(Estado, on_delete=models.CASCADE) def __str__(self): return self.municipio class CP(models.Model): cp = models.CharField(max_length=100) municipio = models.ForeignKey(Municipio, on_delete=models.CASCADE) estado = models.ForeignKey(Estado, on_delete=models.CASCADE) def __str__(self): return self.cp class Colonia(models.Model): colonia = models.CharField(max_length=100) cp = models.ForeignKey(CP, on_delete=models.CASCADE) municipio = models.ForeignKey(Municipio, on_delete=models.CASCADE) estado = models.ForeignKey(Estado, on_delete=models.CASCADE) def __str__(self): return self.colonia As for where I want to implement it, is in the Posts model, here are all the relevant codes, I think: models.py class PostRoom(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,default=1,related_name='room_author') colonia = models.ForeignKey(Colonia, on_delete=models.SET_NULL, blank=False, null=True) cp = models.ForeignKey(CP, on_delete=models.SET_NULL, blank=True, null=True) municipio = models.ForeignKey(Municipio, on_delete=models.SET_NULL, blank=False, null=True) estado = models.ForeignKey(Estado, on_delete=models.SET_NULL, blank=False, null=True) views.py: class RoomSubmitCreateView(LoginRequiredMixin, CreateView): model = PostRoom … -
type object 'datetime.timezone' has no attribute 'now'
This line of code is receiving an AttributeError: now = timezone.now() I can't figure out why. I am correctly importing the package as follows: from django.utils import timezone But it is still throwing: Attribute Error: type object 'datetime.timezone' has no attribute 'now' These are my settings.py if it helps you: LANGUAGE_CODE = 'es-ar' TIME_ZONE = 'America/Argentina/Buenos_Aires' USE_I18N = True USE_L10N = True USE_TZ = True -
Adding Different Theme modes in a Django Project
I am trying to add a themes for users in my Django project. Users can choose between dark mode and light mode. So in the base.html, I have set the links to be as following: <link id="mystylesheet" href="{% static 'css/app-light.css' %}" type="text/css" rel="stylesheet"> <!-- Mode --> <div id="mode" class="section" style="padding-top: 1rem; padding-bottom: 3rem;text-align: right"> <button onclick="swapStyles('app-light.css')" type="button" class="btn btn-secondary">Light Mode</button> <button onclick="swapStyles('app-dark.css')" type="button" class="btn btn-dark">Dark Mode</button> </div> <!-- Mode --> I have started a new app called mode with following models.py: class Setting(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="mode",null=True,blank=True) name = models.CharField(max_length=200, null=True) value = models.CharField(max_length=200) def __str__(self): return self.name here is the javascript <script type="text/javascript"> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); var cssFile = "{% static 'css' %}" function swapStyles(sheet){ document.getElementById('mystylesheet').href = cssFile + '/' + sheet localStorage.setItem('theme', sheet) updateTheme(sheet) } function loadSettings(){ //Call data and set … -
Bokeh rendering glitchy (long complex visualization), embedded in Django
I have a django app w/ a bokeh server embedded in it. The code is complex enough that I cannot possibly paste it here. But I've found that as I add more and more widgets, that updates to the various plots have grown glitchy; sometimes the plot I eventually render renders, sometimes it does not. The accompanying table sometimes only shows half the fields, and other fields appearing blank. I am unfortunately not able to provide minimum viable code here but what are the best options / things I should troubleshoot? -
Deploying a Django app to heroku. Debug False
I am trying to deploy my app to heroku. I successfully deployed to app after dealing with some bugs(the CSS wouldn't load, or images wouldn't load). Now when I deploy the app works fine, when DEBUG = True. When I change DEBUG = False all the images fail to load. Here is my code: settings.py """ Django settings for DBSF project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import django_heroku import os from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['SECRET_KEY'] AUTH_USER_MODEL = 'social.User' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['desolate-lowlands-74512.herokuapp.com', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'channels', 'social', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'DBSF.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
How to Reordering the position of objects in Django?
The code below is getting error NoneType' object is not iterable. I want to reorder the position of objects using JQuery sortable.js. when i drag and drop for changing the position of an object i'm getting the error NoneType' object is not iterable. Please can anybody tell me why i'm getting this error? thanks in advance. views.py @csrf_exempt def SortAble(request): if request.method == 'POST': pk = request.POST.get('pk') for b in pk: book = get_object_or_404(Article, pk=int(b['pk'])) book.position = b['order'] book.save() return JsonResponse({'succes': True}, status=200) else: return JsonResponse({'succes': False, 'errors': []}, status=400) <tbody> {% for object in articles %} <tr data-pk="{{ object.id }}"> <td>{{ object.title }}</td> </tr> {% endfor %} </tbody> <script> $(document).ready(function () { $("tbody").sortable({ update: function (event, ui) { sort = []; window.CSRF_TOKEN = "{{ csrf_token }}"; $("tbody").children().each(function () { sort.push({ 'pk': $(this).data('pk'), 'order': $(this).index() }) }); $.ajax({ url: "{% url 'rundown-sort' %}", type: "post", datatype: 'json', data: { 'sort': JSON.stringify(sort), 'csrfmiddlewaretoken': window.CSRF_TOKEN }, }); console.log(sort) }, }).disableSelection(); }); </script> -
Is there a way to retrieve Enum description instead of name in a GraphQL API made with Django Graphene
This question is more about what's the best practice than how to monkey-patch Graphene to accomplish what I want. Django Graphene turns model's choices automagically in enums. Lets say I have this model: class Car(models.Model): brand = models.PositiveSmallIntegerField( choices=( (1, "Audi"), (2, "Mercedes Benz"), (3, "BMW") ) ) with this node: class CarNode(DjangoObjectType): class Meta: model = Car filter_fields = [] interfaces = (relay.Node,) then, running the following query: query Cars { cars { edges { node { id brand } } } } results in this response: { "data": { "cars": { "edges": [ { "node": { "id": "Q2FyTm9kZTox", "brand": "A_1" } }, { "node": { "id": "Q2FyTm9kZToy", "brand": "A_2" } }, { "node": { "id": "Q2FyTm9kZToz", "brand": "A_3" } } ] } } } At this point I may want to make a custom enum to turn A_1, A_2 and A_3 into capitalized, snake cased values, to make them self-descriptive... class CarBrand(graphene.Enum): AUDI = 1 MERCEDES_BENZ = 2 BMW = 3 @property def description(self): if self == CarBrand.AUDI: return 'Audi' if self == CarBrand.MERCEDES_BENZ: return 'Mercedes Benz' if self == CarBrand.BMW: return 'BMW' return 'Other brand' class CarNode(DjangoObjectType): brand = CarBrand() ... Now, the response looks A LOT … -
unable to access private repos with oauth access token
i have created a Oauth github app and Oauth works fine. but i want to access the all repos(including private) with the access-token i get during Oauth. i have tried with personal access token and i am getting all the private reops. why its not working with Oauth access-token ? Scops SOCIALACCOUNT_PROVIDERS = { 'github': { 'SCOPE': [ 'user', 'repo' ], } } regarding the env. i am using dj-rest-auth to authenticate with Github and get the access-token.