Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Template does not exist in django, but I have template?
I have a problem. I use django 3.1.1 and python 3.8.5/ I try to create a site in python + django (back-end) and html, css, bootstrap (front-end). I created two applications 1. blog (in one subpage I will have blog) and 2. Pages other subpages like homepage. This is my whole program https://github.com/Charnel2500/blog_ai_py385_django311 My blog works perfectly (I create this application from a tutorial) Now I try to create another application by my own - "pages". I created a new application. I add this application in settings.py (and in DIR) """ Django settings for ai_blog project. Generated by 'django-admin startproject' using Django 3.1.1. 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 os # 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 = '-%60+qrw+)3c&_tchqlyt8=%k$@b331pw1se*=lsr#21ux7g=$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'pages', … -
ModuleNotFoundError: No module named 'sorl'
I'm getting following error during installing django-oscar from https://django-oscar.readthedocs.io/en/2.0.4/internals/getting_started.html settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'oscar', 'oscar.apps.analytics', 'oscar.apps.checkout', 'oscar.apps.address', 'oscar.apps.shipping', 'oscar.apps.catalogue', 'oscar.apps.catalogue.reviews', 'oscar.apps.partner', 'oscar.apps.basket', 'oscar.apps.payment', 'oscar.apps.offer', 'oscar.apps.order', 'oscar.apps.customer', 'oscar.apps.search', 'oscar.apps.voucher', 'oscar.apps.wishlists', 'oscar.apps.dashboard', 'oscar.apps.dashboard.reports', 'oscar.apps.dashboard.users', 'oscar.apps.dashboard.orders', 'oscar.apps.dashboard.catalogue', 'oscar.apps.dashboard.offers', 'oscar.apps.dashboard.partners', 'oscar.apps.dashboard.pages', 'oscar.apps.dashboard.ranges', 'oscar.apps.dashboard.reviews', 'oscar.apps.dashboard.vouchers', 'oscar.apps.dashboard.communications', 'oscar.apps.dashboard.shipping', # 3rd-party apps that oscar depends on 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', ] HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', 'URL': 'http://127.0.0.1:8983/solr', 'INCLUDE_SPELLING': True, }, } After running py .\manage.py migrate or py .\manage.py makemigrations I got following error Traceback (most recent call last): File ".\manage.py", line 21, in main() File ".\manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\projects\ecommerce\django-oscar-env\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "D:\projects\ecommerce\django-oscar-env\lib\site-packages\django\core\management_init_.py", line 377, in execute django.setup() File "D:\projects\ecommerce\django-oscar-env\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\projects\ecommerce\django-oscar-env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "D:\projects\ecommerce\django-oscar-env\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "c:\program files\python37\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'sorl' I have also found that solr-thumbanil or solr is not install. If I install solr-thumbnail then I get following error … -
Is it possible to lock the database for editing , and edit only through the django app?
i need to lock postgres sql database for editing from anywhere even with direct admin access and just edit with the Django app, I mean the app itself, not the user and the database password -
Name Error in Django - Nested Views Function - Saving to Database
Using Django, While trying to save the answers from the User to the Database, it is showing me a Name Error. I have used a nested function inside the views function, it works correctly when i do not attempt to save the data to the database. But once i try to put in code inside the views function to save the data, it produces this name error. Below are the files with the code, models.py file from django.db import models from django.utils import timezone from django.contrib.auth.models import User class ansquestions(models.Model): m_invested = models.CharField(max_length=100) p_return = models.CharField(max_length=100) years = models.CharField(max_length=100) inflation_yes_no = models.CharField(max_length=100) r_output = models.TextField(default=True) date_answered = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) form.py file from django import forms from .models import ansquestions class ansquestionsForm(forms.ModelForm): class Meta: model = ansquestions fields = ['m_invested', 'p_return', 'years', 'inflation_yes_no', 'r_output', 'date_answered', 'author' ] views.py file from django.shortcuts import render #from django.http import HttpResponse from .models import ansquestions from .forms import ansquestionsForm def investmentfv(request): idata = { 'tmi':tmi, 'pry':pry, 'ys':ys, 'qinf':qinf } return render(request, 'fvalueapp/investmentfv.html', idata) def investmentfvcalc(request): total_i = request.POST["m_invested"] perc_r = request.POST["p_return"] years_i = request.POST["years"] makeup_infl = request.POST["inflation_yes_no"] def fvinvestment(): global fv_i_value global r_output #global makeup_infl ( global variable might be needed for … -
ModuleNotFoundError: No module named 'tinymce' while trying to deploy on pythonanywhere
I think I have all the necessary libraries installed pip freeze gives this output asgiref==3.2.10 astroid==2.4.2 Django==3.1.2 django-appconf==1.0.4 django-tinymce==3.1.0 django-tinymce-lite==0.0.2 lazy-object-proxy==1.4.3 Pillow==7.2.0 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 wrapt==1.12.1 I've tried importing tinymce in python console and it gets imported but still I am getting this error. I know this question is repetitive but solutions to other threads ain't working. Also, collectstatic gives the following error ImportError: cannot import name 'HTMLField' from 'tinymce' -
403 error from Vuejs axios.post logout to DjangoAPI
I have a project uses Django API and VueJS project. I need help about logging out an User. I can login and register user succesfully but while trying to logout; I click button and nothing happens and in the network I get 403 error.But when I re-enter page, user is logged out. This is how I try to logout. User clicks button: <b-link @click.prevent="logout"> Çıkış Yap </b-link> async logout() { // call loginUSer action await this.$store.dispatch('user/logout', {}) .then(() => { this.wrongCred = true this.$router.push('/') }) .catch(err => { console.log(err) this.wrongCred = true // if the credentials were wrong set wrongCred to true }) }, In vuex module: async logout(context) { try { const response = await DjangoAPI.logout(); context.commit('reset'); return Promise.resolve(response); } catch(err) { console.log('err in store.user/logout', err); return Promise.reject(err); } } and in DjangoUserService.js: import axios from "axios"; import Cookies from 'js-cookie'; const apiCall = process.env.NODE_ENV === 'test' ? axios : HTTP; var csrftoken = Cookies.get('csrftoken'); async logout(payload) { try { console.log(payload); const response = await apiCall.post(`/api/rest-auth/logout/`,{}, { headers: {"X-CSRFToken": csrftoken } }); return Promise.resolve(response); } catch(err) { console.log('err in DjangoService/logout', err); return Promise.reject(err); } } and I have an interceptor which I think is not good but I am … -
Django 3.1 - annotation, ExpressionWrapper and division - SQL error
I am building a query, that filters on a frequency field. Now the frequency is not a model field, but an annotated value, derived from a duration and a count. This is based on the very basic idea that frequency = duration / number of times stuff happened. (Very) simplified models are below: import uuid class Actor(AbstractBaseUser): uuid = models.UUIDField(_('UUID'), default=uuid.uuid4, primary_key=True) class Event(models.Model): actor = models.ForeignKey(Actor, null=True, blank=True, on_delete=models.CASCADE) foo = models.CharField(_('Foo'), max_length=10, blank=True, null=True) bar = models.CharField(_('Bar'), max_length=10, blank=True, null=True) when = models.DateTimeField(_('When'), null=True, blank=True) The idea behind the query is this: each actor gets annotated with event_count: the number of Event objects it is the parent of each actor gets annotated with first_event_datetime: the datetime of its earliest child Event object each actor gets annotated with the duration_over: the duration between Now() (database function) and first_event_datetime each actor gets annotated with the "event_frequency" of events over the considered period event_frequency: duration_over / event_count With that in mind, the query is built like this: from django.db import models from django.db.models import Q, Sum, Avg, F, Count, OuterRef, Subquery, Exists, Value, ExpressionWrapper from django.db.models.functions import Coalesce, Now, Mod, Cast actors = Actor.objects.annotate( event_count=Coalesce(Subquery( Event.objects.filter(Q()).values( 'actor__pk' ).order_by( 'actor__pk' ).annotate( count=Count('pk', … -
Getting 403 Forbidden Error in Django Ajax even after passing CSRF_TOKEN
I am using modal pop up box to create instances of Modal in Django. Here is the form inside the modal body: <form action="{% url 'projects:techs_create' %}" method="post" id="tech-form" > {% csrf_token %} <input type="text" name="name" id="tech-name" /> <input type="submit" value="Save" class="button button-main" /> </form> and this is the Ajax request I used $(document).on("submit", "#tech-form", function (e) { e.preventDefault(); $.ajax({ type: "POST", url: $(this).attr("action"), dataType: "json", contentType: "application/json", // data: $(this).serialize(), data: { name: $("#tech-name").val(), csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(), }, success: function (response) { console.log('done') }, error: function (xhr, status, error) { console.log(error.msg); }, }); }); I get this error: POST http://localhost:8000/techs/new/ 403 (Forbidden) I saw some similar questions here in SO and majority of the answers were talking about a missing csrf token. Now that I added it as data of request. I am still getting the error. What am I doing wrong here? this is the view I am using to handle the request: @login_required def techs_create_view(request): if not request.user.is_superuser: raise PermissionDenied if request.method == 'POST': form = ProjectTechnologieForm(request.POST) if form.is_valid(): name = form.cleaned_data.get('name') form.save() messages.success(request, f'{name} created successfully.') return HttpResponseRedirect('projects:statistics') form = ProjectTechnologieForm() context = { 'tech_form': form } if request.is_ajax(): html = render_to_string('projects/statistics.html', context, request=request) return JsonResponse({'form': html}) … -
how to get connected clients in flask
hi i need to display total number of connected clients on my flask app i write this code for checking connected and disconnected connections. app = Flask(__name__) socketio = SocketIO(app) clients = [] @socketio.on('connect', namespace='/') def connect(): clients.append(request.namespace) @socketio.on('disconnect', namespace='/') def disconnect(): clients.remove(request.namespace) then i render template like this return render_template_string(TABLE_TEMPLATE, data=data, clients=len(clients)) In html part i call like this <h1>{{ clients }} </h1> but on webpage it keep showing 0 even client is connect i get output from client and it is connected it should print 1 2 depends how many clients are connected. even if i print this print(len(clients)) it return 0. even my client is connect and i get output. this is my full code from flask import Flask, request, render_template_string from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app) clients = [] @socketio.on('connect', namespace='/') def connect(): clients.append(request.namespace) @socketio.on('disconnect', namespace='/') def disconnect(): clients.remove(request.namespace) TABLE_TEMPLATE = """ <h1>{{ clients }} </h1> <style> table, th, td { border: 1px solid black; } </style> <table style="width: 100%"> <thead> <th>Client</th> <th>IP</th> <th>Status</th> </thead> <tbody> {% for row in data %} <tr> <td><center>{{ row.client }}</td></center> <td><center>{{ row.ip }}</td></center> <td><center>{{ row.status }}</td></center> </tr> {% endfor %} </tbody> </table> """ @app.route("/device_add", methods=['POST']) def … -
Django Rest Framework gets 'NoneType' from JS fetch
This is my JS fetch data var requestOptions = { mode:'cors', method: 'POST', redirect: 'follow', headers:new Headers({ "Accept":"application/json,*/*", "Content-Type": "application/json" }), body:JSON.stringify({"username":username_to_test}) }; views.py @api_view(['POST']) #Response will be in JSON format @renderer_classes([JSONRenderer]) def username_check(request): try: isAvailable=db_handle.username_check(request.POST.get("username").lower()) return Response(isAvailable,status=status.HTTP_200_OK) except Exception as e: print("Username check errors",e) return Response(status=status.HTTP_400_BAD_REQUEST) But django-rest-framework never gets the 'username'.It always gets 'NoneType' But the follwoing fetch works var formdata = new FormData(); formdata.append("username",username_to_test); var requestOptions = { mode:'cors', method: 'POST', redirect: 'follow', body:formdata, }; I included JSON parser in Default parsers.But no change.What to do? -
Not able to send messages over sockets Django Channels
I'm unable to send messages to other members of the group when a participant sends a message over the socket. Here's my code. def process_message_and_send_to_other_users(data): # Do some processing and send data to other users of the group. func = get_channel_layer().group_send kwargs = { 'group': str(group_id), 'message': {"type":"push_to_client_socket", "a":1} } # Function not getting called. return func(**kwargs) class Consumer(AsyncJsonWebsocketConsumer): """Consumer.""" async def connect(self): # Accept the connection await self.accept() # Adding current to group. await self.channel_layer.group_add(group=user_id, channel=current) async def disconnect(self, close_code): # Dropping from group. await self.channel_layer.group_discard( group=user.user_id, channel=connection_id, ) async def receive_json(self, data, **kwargs): """Receive messages over socket.""" ######## DO SOME PROCESSING. ##### a = process_message_and_send_to_other_users(data) await self.send_json(resp) async def push_to_client_socket(self, event): """Push the message over the client socket.""" event.pop('type', '') await self.send_json(json.dumps(event, default=str)) Where exactly I'm going wrong? Pls, don't recommend processing the message inside receive_json itself. The above snippet is just a barebone. -
how to verify a coupon using django framework and sqlite?
so, my basic idea is when a student enter a coupon provided by his educational institute the system should check if the coupon exists in the database or not and display a message saying the coupon is verified if it is in the data base, but what actually happens is an "errorList" message appears saying that the coupon already exits in the database and my customized message never appears this is my views function def apply_coupon(request): if request.method == 'POST': form = ApplyCouponForm(request.POST) if form.is_valid(): # code_entered = request.POST.get('code') code_entered = form.cleaned_data['code'] is_available = Coupon.objects.get(code=code_entered).exists() is_active = Coupon.objects.get(active=True).exists() if is_available & is_active: messages.info(request, 'Your coupon is verified!') else: messages.info(request, 'Your coupon is not verified!') else: form = ApplyCouponForm() return render(request, 'app/applyCoupon.html', {'form': form}) is_available = Coupon.objects.get(code=code_entered).exists() this line checks if the coupon exists in the databese is_active = Coupon.objects.get(active=True).exists() this one checks if it is active or not if is_available & is_active: i think this condition is never true but i don't know why this is coupon model in models.py # coupons model class Coupon(models.Model): code = models.CharField(primary_key=True, max_length=50, unique=True) active = models.BooleanField() def __str__(self): return self.code this is my html template {% extends 'base_layout.html' %} {% block content %} … -
How to call a function from another py file to a model class in django
I have created a seprated py file that includes multiple functions that i want to use inside a model class in django, the file: a.py contains functions eg. """ code""" def cra_2(lower_threshold, upper_thershold, maximum_cra_payment, market_rent, weekly_income, maintenance): rent_component = weekly_income * .25 weekly_maintenance = (maintenance / 365) * 7 * .25 family_rent = rent_component + weekly_maintenance if family_rent > market_rent and market_rent > upper_thershold: rent_charged = market_rent elif family_rent <= lower_threshold: rent_charged = min(market_rent, family_rent) elif family_rent <= (lower_threshold + 0.25 * (upper_thershold - lower_threshold)): rent_charged = min(market_rent, 4 * (family_rent - 0.75 * lower_threshold)) elif family_rent <= upper_thershold and market_rent > upper_thershold: rent_charged = min(market_rent, (family_rent + maximum_cra_payment)) elif family_rent <= upper_thershold and market_rent < upper_thershold: rent_charged = min(market_rent, 4 * (family_rent - 0.75 * lower_threshold)) else: rent_charged = min(market_rent, (family_rent + maximum_cra_payment)) #Calculate CRA if rent_charged <= lower_threshold: cra_rate = 0.0 elif rent_charged >= upper_thershold: cra_rate = maximum_cra_payment else: cra_rate = (rent_charged - lower_threshold) * .75 import json report = { "rent charged": rent_charged, "cra rate: ": cra_rate, "family rent": family_rent, "given values ":[{"rent_component":rent_component}, {"weekly_maintenance ":float(weekly_maintenance) } ] } return json.dumps(report, indent=2) i want to use this function in a model class, and the input parameter values are … -
Django Error while saving avatar : expected str, bytes or os.PathLike object, not NoneType
there is an error on cleaned_data['avatar'] (in forms.py) : expected str, bytes or os.PathLike object, not NoneType this error appears when I sign in with an image for avatar. I m using Django-allauth but not used to it.... So I add an avatar field which appears in sign_in form but I've the error when submitting. this is my code: models.py from django.db import models from django.contrib.auth.models import AbstractUser def get_path_name(instance, filename): path = 'media/avatar/' name = instance.user.id + "-" + instance.user.email path = path + name return path # custom User model class CustomUser(AbstractUser): avatar = models.ImageField(upload_to= get_path_name, blank=True, null=True) my form: from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.core.files.images import get_image_dimensions from django import forms class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'username', 'avatar') def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) # validate dimensions max_width = max_height = 100 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) # validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, … -
how can i check django user groups in forms
I have a form defined from a model class. Depending from the user group of the logged in user, some fields should be remove if logged in user is not belong from certain group.i have a producer group, if logged in user is not belong form producer group then i want to remove the time_pool field from the forms. my code is showing this error 'NoneType' object has no attribute 'groups' . how can i solve this issue? class ArticleForm(forms.ModelForm): class Meta: model = Article fields = [ 'title', 'content', 'time_pool', ] def __init__(self, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) self.user = kwargs.pop('user', None) if not self.user.groups.filter(name__iexact='producer').exists(): del self.fields['time_pool'] -
send reset password template to gmail, outlook and anothers in django
I am able to send the password reset page and reset the password normally, but only by gmail, if you put EMAIL_HOST = 'smtp-mail.outlook.com' I can send to outlook, but how can I send to all valid emails? (outlook, gmail ...) because like '' smtp-mail.outlook.com '' and 'smtp.gmail.com', I can only send to one or the other, never both EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'emailHere' EMAIL_HOST_PASSWORD = 'passwordHere' EMAIL_USE_TLS = True -
Django model fields get realigned after writing wrong data
in my Django admin panel, whenever I leave a field blank and save it the fields are realigned left to right and vice versa. Can anyone tell me what is the problem and how to fix this. In the below pics 1st pic is when there is no data in the fields. 2nd pic is when i leave a field blank and save it the field has realigned from left to right [ -
how i resolv this error python django project while deploye on heroku
Build failed -- check your build output , when i run command heroku logs then one error come multiple time "Build failed -- check your build output" -
how to count number of connected clients in flask
i need to display the number of connected clients on web page i am using flask-socketio and i write this code for checking connected and disconnected connections. app = Flask(__name__) socketio = SocketIO(app) clients = [] @socketio.on('connect', namespace='/') def connect(): clients.append(request.namespace) @socketio.on('disconnect', namespace='/') def disconnect(): clients.remove(request.namespace) then i render template like this return render_template_string(TABLE_TEMPLATE, data=data, clients=len(clients)) In html part i call like this <h1>{{ clients }} </h1> but on webpage it keep showing 0 even client is connect i get output from client and it is connected it should print 1 2 depends how many clients are connected. even if i print this print(len(clients)) it return 0. this is my full app code. from flask import Flask, request, render_template_string from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app) clients = [] @socketio.on('connect', namespace='/') def connect(): clients.append(request.namespace) @socketio.on('disconnect', namespace='/') def disconnect(): clients.remove(request.namespace) TABLE_TEMPLATE = """ <h1>{{ clients }} </h1> <style> table, th, td { border: 1px solid black; } </style> <table style="width: 100%"> <thead> <th>Client</th> <th>IP</th> <th>Status</th> </thead> <tbody> {% for row in data %} <tr> <td><center>{{ row.client }}</td></center> <td><center>{{ row.ip }}</td></center> <td><center>{{ row.status }}</td></center> </tr> {% endfor %} </tbody> </table> """ @app.route("/device_add", methods=['POST']) def device_add(): name = request.args.get('name') with … -
Pass javascript variables into a {% static "..." %} pathway text
I am trying to create the following array for my server, which serves to preloading the images with given paths: var i = 0; while (face_cursor < faces_gone_through.length) { for(j=0; j<=100; j+=10) { load_images_array.push('{% static "/img/' + faces_gone_through[face_cursor] + '/' + faces_gone_through[face_cursor+1] + '/' + faces_gone_through[face_cursor] + '_' + j + 'P_' + faces_gone_through[face_cursor+1] + '.jpg" %}'); } i++; face_cursor+=3; } face_cursor=1; The code may seem weird, but what i am basically doing is trying to concatenate the given strings and try to create an array of paths. But the concatenation doesn't work and the stirng is parsed as: /static/img/&#x27;%20%2B%20faces_gone_through%5Bface_cursor%5D%20%2B%20&#x27;/&#x27;%20%2B%20faces_gone_through%5Bface_cursor%2B1%5D%20%2B%20&#x27;/&#x27;%20%2B%20faces_gone_through%5Bface_cursor%5D%20%2B%20&#x27;_&#x27;%20%2B%20j%20%2B%20&#x27;P_&#x27;%20%2B%20faces_gone_through%5Bface_cursor%2B1%5D%20%2B%20&#x27;.jpg How can one successfully concatenate this string? -
How to aggregate, that is to get querysets based on a property of a query
My model: class ClinicPermissions(models.Model): id = models.AutoField(primary_key=True, unique=True) clinicid = models.ForeignKey(Clinic, on_delete=models.CASCADE) doctorid = models.ForeignKey(doctor, on_delete=models.CASCADE) viewperm_choices = ( (0, 'Cannot view clinic details'), (1, 'Can view clinic details') ) viewperms = models.IntegerField( choices=viewperm_choices, default=0) editperms_choices = ( (0, 'Cannot edit clinic details'), (1, 'Can edit clinic details') ) editperms = models.IntegerField( choices=editperms_choices, default=0) editdocs_choices = ( (0, 'Cannot edit doctor details'), (1, 'Can edit doctor details') ) editdocs = models.IntegerField( choices=editdocs_choices, default=0) class Meta: unique_together = ["clinicid", "doctorid"] The above model describes permissions of each doctor in a clinic. I need to get a list of doctor objects associated with a Clinic object, which is stored in ClinicPermissions model, as a queryset and pass it to a form. i.e I want to get a specific Clinic. cl = Clinic.objects.get(id=10) Then, I want to get a queryset of doctors from the ClinicPermissions, where clinicid = cl: i.e Something more elegant than the following: perms = ClinicPermissions.objects.filter(clinicid = cl) docs = [] for perm in perms: docs.append(perm.doctorid) return docs Here, docs is a list, but I need a queryset, to pass to a form. -
Deal with django ImageField current value displayed in forms
I'm trying to remove the clear checkbox in Django's ImageField and remove the displayed current value of the file. Tha approach I tried is to replace the widget as proposed here How to not render django image field currently and clear stuff? but the result is that I get ValidationError : "Upload a valid image. The file you uploaded was either not an image or a corrupted image.". Though the validation error the image get's uploaded, but I do not get redirected to the success page and an error is being rendered in the form. What's the recommended way to remove the current value in the ImageField? -
API Resources Collections in Django Rest Framework
I'm wondering how to create laravel-like resources and collections for API in Django using the Django Rest Framework. <?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; use App\Http\Resources\User as UserResource; class Post extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'body' => $this->body, 'user' => new UserResource($this->user), 'some-hard-coded-text' => 'Hello World', ]; } } -
Django - How to tertermine content_type in if statement?
I want to find out what content_type I'm about in my function but I'm Unable to reach the "got me" print statement no matter how I design my if statement. I also tried to use pprint to get the naming of the content_type but with no effect till now. def mark_refunded(modeladmin, request, queryset): queryset.update(status=2) transactions = queryset.all() for transaction in queryset.all(): print(transaction) transaction.sender.acc_usd_balance += float(transaction.amount) transaction.sender.save() transaction.receiver.acc_usd_balance -= float(transaction.amount) transaction.receiver.save() print(transaction.content_type) if transaction.content_type == "App | Sell Type A": print("got me") It seems that I'm unable to compare the output of print(transaction.content_type) with the if statement, why that? I would expect that the output is the same value that I ask for at the if statement. -
How to make a list with a comma separated strings?
Here I have string like this. Size:20,color:red,Size:20,color: pink,Size: 90,color:red,Size: 90,color: pink, Now I want to convert into this format [{'Size': '20','color':'red'}, {'Size': '20','color': 'pink'}, {'Size': '90','color':'red'}, {'Size': ' 90','color': 'pink'}] Can we make a list like this ?