Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create an object of a Model that has a foreign key to another Model in Django?
I am pretty new to Python and Django and I am kinda struggling with a project. I am trying to build a Etsy-like website, where people can sell their things (not really like a shop, people can post everything they want to sell). I am now trying to add the "Add Item" functionality for the User, where he can post its own sale. But the problem I have stummbled upon is the following: my model Product has a foreign key to the model Customer and I don't know how to create a new product in the database because it keeps saying NOT NULL constraint failed: app_product.added_by_id. I tried something like this, but it is not working and I have no idea what I should do. https://i.stack.imgur.com/MaykE.png My classes looks like this: https://i.stack.imgur.com/LF9R6.png https://i.stack.imgur.com/f5Te7.png Anoyone has any idea what I should try? Or if I can make it automatically in the HTML part or something -
UNIt Test- How to test Viewsets create Function in DRF
I want to test create function which is inside viewsets. I have tried I got 400 error. views.py class PersonalInfoAPI(viewsets.ViewSet): permission_classes = [IsOwnerPermission] def get_object(self, pk): obj = get_object_or_404(Employee.objects.all(), pk=pk) self.check_object_permissions(self.request, obj) return obj def create(self, request): print("im in create") personal_info = JSONParser().parse(request) data = personal_info['data']['personal_info'] data['appraisal_master_id'] = personal_info['data']['appraisal_master_id'] employee = self.get_object(pk=data['employee_id']) appraisal = get_object_or_404(Appraisal, pk=data['appraisal_master_id']) employee_appraisal = EmployeeAppraisal.objects.filter(appraisal=appraisal, employee=employee).first() if employee_appraisal: personal_info_serializer = PersonalInfoSerializer(employee_appraisal, data=data) if personal_info_serializer.is_valid(): personal_info_serializer.save() return Response(employee_appraisal.appraisal_info(user=self.request.user), status=status.HTTP_200_OK) else: personal_info_serializer = PersonalInfoSerializer(data=data) if personal_info_serializer.is_valid(): employee_appraisal = personal_info_serializer.save() return Response(employee_appraisal.appraisal_info(user=self.request.user), status=status.HTTP_201_CREATED) return Response(personal_info_serializer.errors, status=status.HTTP_400_BAD_REQUEST) test.py def test_personal_info_api(self): url = reverse('employee1-list') self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key) resp1 = self.client.post(url, data={'employee_id': 1, 'appraisal_master_id': 1}, format='json') print(resp1) self.assertEqual(resp1.status_code, 200) I am newbie for django and testing as well. Any help appreciable,. -
Not able to submit data from model form with multiple files django
I am trying to add multiple files through use of two models and forms. Have tried to update but not able to make it work. On submission of form, there are no errors, but nothing is posted to database. Please help. Also, how do I define users as full name in drop downs in forms? Tried formfields approach but not working. Also, form not showing empty label models.py class Case(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name= 'caseclients' ) statute = models.ForeignKey(Statute, on_delete=models.CASCADE) financial_year = models.ForeignKey(Financialyear, on_delete=models.CASCADE) proceeding = models.ForeignKey(Proceeding, on_delete=models.CASCADE) case_title = models.CharField(max_length=200) initiated_on = models.DateField(auto_now=False, auto_now_add=False) communication_received_on = models.DateField(auto_now=False, auto_now_add=False) first_date_of_hearing = models.DateField(auto_now=False, auto_now_add=False) limitation_period = models.CharField(max_length=500, blank=True) amount_involved = models.IntegerField(null=True,blank=True) person_responsible = models.ForeignKey(User, on_delete=CASCADE, related_name = 'person_responsible') assisted_by = models.ManyToManyField(User, related_name = 'assisted_by', blank=True) brief_of_case = models.TextField(max_length=1000) status = models.CharField(choices=[('Open','Open'),('Close','Close')],default='Open', max_length=100) def __str__(self): return self.case_title class CaseFiles(models.Model): attachment = models.FileField(upload_to='casefiles/') case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name= 'casefiles') forms.py class CaseFilesCreationForm(ModelForm): class Meta: model = CaseFiles fields = ['attachment'] attachment = forms.FileField, widgets= { 'attachment': forms.ClearableFileInput(attrs={'multiple': True, 'class': 'form-control form-control-light','type': 'file',}), } class CaseCreationForm(ModelForm): class Meta: model = Case fields = '__all__' client = forms.ModelChoiceField(queryset=Client.objects.all(), to_field_name="name_of_client", empty_label="Select Client",), statute = forms.ModelChoiceField(queryset=Statute.objects.all(), to_field_name="statute", empty_label="Select Statute",), financial_year = forms.ModelChoiceField(queryset=Financialyear.objects.all(), to_field_name="financialyear", empty_label="Select Financial Year",), … -
call the function response in another function in Django RestFramework
I tried calling the another function inside the function which will return the response.I have tried this approach but couldn't able to achieve it. I'm just getting error as AssertionError at /api/Data/CurrentRunningActivity2/54 Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` views.py: @api_view(['GET']) def CurrentRunningActivityView2(request, UserID): if request.method == 'GET': CurrentRunningActivity(UserID) def CurrentRunningActivity(UserID): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivity] @UserId=%s',(UserID,)) result_set = cursor.fetchall() for row in result_set: TaskId=row[0] Number=row[1] Opened=row[2] Contacttype=row[3] Category1=row[4] State=row[5] Assignmentgroup=row[6] CountryLocation=row[7] Openedfor=row[8] Employeenumber=row[9] Shortdescription=row[10] Internaldescription=row[11] Additionalcomments=row[12] TaskName = row[1] print("Number", Number) return Response({ "TaskId": TaskId, "Number":Number,"Opened":Opened, "Contacttype":Contacttype, "Category1":Category1, "State":State, "Assignmentgroup":Assignmentgroup, "CountryLocation":CountryLocation, "Openedfor":Openedfor, "Employeenumber":Employeenumber , "Shortdescription":Shortdescription, "Internaldescription":Internaldescription, "Additionalcomments":Additionalcomments,"TaskName":TaskName},status=status.HTTP_200_OK) -
How to launch Django project / run server, with an exe
I have written the following .bat file: start chrome http://127.0.0.1:8000/ venv\Scripts\activate python manage.py runserver 8000 When I perform these steps myself, one by one, in prompt, it runs the server and opens the site perfectly. However, when I use iexpress to convert this file to an .exe and run it, the site just displays the "unavailable" message, as if no server were running. I'm not sure, but I think this is because the exe closes as soon as it's executed the commands, instead of keeping the server running. How do I fix this? -
Django logger is not shown that runs on Docker
logger.debug() and print() are not shown on a Django project that runs on Docker. Any other operations are correct. Is my recognition correct that the logs show up on the terminal window that runs docker-compose up? I tried outputting resolution, but it not work for me. My settings are below. directory Project ├── Service_ID │ ├── root │ ├──settings.py | ├── docker-compose.yml └── docker ├── mysql │ ├── Dockerfile │ └── my.cnf ├── nginx │ ├── default.conf │ └── uwsgi_params └── python ├── Dockerfile └── requirements.txt docker-compose.yml version: "3.8" services: ... web: image: nginx:1.21.3-alpine ports: - 8000:8000 volumes: - ./Service_ID:/workspace - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf - ./docker/nginx/uwsgi_params:/etc/nginx/uwsgi_params working_dir: /workspace depends_on: - root root: build: ./docker/python command: uwsgi --socket :8001 --module root.wsgi --py-autoreload 1 --logto /tmp/tmp.log volumes: - ./Service_ID:/workspace expose: - "8001" depends_on: - db volumes: db-store: python/Dockerfile FROM python:3.8.3 ENV PYTHONUNBUFFERED 1 RUN mkdir /workspace WORKDIR /workspace ADD requirements.txt /workspace/ RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt ADD . /workspace/ Service_ID/root/settings.py IS_ON_LOG_FILE = True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'file': { 'format': '\t'.join([ "[%(levelname)s]", "%(message)s", ]) }, 'console': { 'format': '\t'.join([ "[%(levelname)s]", "%(message)s", ]) }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, … -
I get mime type error when I connect my react app(via vite.js) with django framework
recently I'm starting to make a web application with React and Django. I installed react with vite.js(because it seems so fast in the development environment). and I connected it to Django web framework and ran it. and I thought It would show basic react page(you know, dark page and favicon is revolving ) However, contrary to my expectations, It only shows blank and I checked the console.log. the error message was this : Refused to apply style from 'http://127.0.0.1:8000/assets/index.cd9c0392.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. so I googled it and figure out that is a problem with the path in most cases. but when I check the my index.html in build file, path seems fine. below is my build folder structure and index.html, can you tell me what is wrong with my code or logic or both? thx for reading , your help will be appreciated. frontend -dist => this is build folder --assets ---index.cd9c0392.css ---favicon.21sd12.js . . . --index.html -node_modules -src -index.html . . . index.html(in dist) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/assets/favicon.17e50649.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite App</title> … -
How to set up Docker image of Celery with Django using a separate container
I would like to separate my Celery Docker container from my backend (Django) Docker container. I would like the Celery container to be built without relying on the backend container. Currently, all the tutorials I am finding online are set up so that the Celery image is built using the Backend container's context like such: backend: build: context: ./backend celery: build: context: ./backend I feel that Celery relying on the backend context to build the image is not the proper way to do this as there are a lot of resources not needed from the backend context in the celery container. Currently my project docker-compose looks as such: backend: build: context: ./backend celery: build: context: ./backend dockerfile: Dockerfile.celery Project dir tree: ├── backend │ ├── Dockerfile │ ├── Dockerfile.celery │ ├── Dockerfile.prod │ ├── entrypoint.dev.sh │ ├── entrypoint.prod.sh │ ├── requirements.txt │ └── venv ├── docker-compose.ci.yml ├── docker-compose.prod.yml ├── docker-compose.yml ├── frontend │ ├── Dockerfile │ ├── Dockerfile.prod ├── nginx │ ├── Dockerfile │ ├── Dockerfile.prod │ ├── certbot │ └── conf The Dockerfile.celery: FROM python:3.9.5-alpine WORKDIR /backend ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add … -
How to use a value from a query into another query in django
I have the following code in my view: # default group view for group admins def adminGroupView(request): # get group id => group data and messages group_id = GroupUser.objects.get(username_id=request.user.id) groupdata = Group.objects.get(group_id=group_id) groupmessages = MessageBoard.objects.filter(group_id=group_id) groupmembers = GroupUser.objects.filter(group_id=group_id) form = SendMessageForm() context = { "groupdata":groupdata, "groupmessages":groupmessages, "groupmembers":groupmembers, "form":form } return render(request, 'base/group-admin.html', context) I keep getting a typeerror TypeError at /group/ Field 'group_id' expected a number but got <GroupUser: 9>. when i replace the group_id with a number, the code works just fine. How do i use the value from the other query. -
How to display django model column values horizontally on django template
my issue is displaying the model data on django template horizontally. I have a model named "Main" with 3 columns. When I display on the template it looks like this- I want to filter it by category that will look like this- Main.objects.filter(category='food') My goal is to show the category name on the template with the price horizontally on the side with plus signs. It should look something like this- food= 8+10+11 I tried for...in loop both on template and on views.py both failed. Tried something like this- print(f"{i.category}={i.price}+") with for loop. Didn't work. output+=f'{i.price}+' with a for loop, holding it in a variable and display that variable on template. Different combinations of those, all failed. Since += is mainly for integers, I tried with i.price without turning it into a string, failed. Most answers I found here on "displaying model data horizontally on Django template" are about using css to display form elements side by side,which I know how to do and not exactly my problem. Can anyone point me to the right direction? Here is my models.py class Main(models.Model): name = models.CharField(max_length = 60, blank = True) category = models.CharField(max_length = 60, blank = True) price = models.CharField(max_length … -
how to set up a docker with an existing database?
I have a project in Django, I want to configure my docker with an existing postgres database, but the tutorials I see are from a database without data. who could give me a guide, please It's my set up Docker-compose: services: web: build: . command: python3 manage.py migrate command: python3 manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" volumes: - .:/code depends_on: - db db: image: postgres Docker file FROM python:3.9 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code RUN pip install -r requirements.txt File setting in django project DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME':'postgres', 'USER': 'postgres', 'HOTS': 'db', 'PORT': 5432, } } -
I cannot understand why 3rd path is not activated
I am new to Django and I have no idea why this is not working. I am trying to add a new path to newyear/ but it looks as if it's just not accepting a new path. Heres the code: In setting.py you can see I added newyear app INSTALLED_APPS = [ 'hello', 'newyear', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] urls.py: (this is where the problem supposedly is) from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include("hello.urls")) path('newyear/', include("newyear.urls")) ] urls.py(for the newyear app): from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index") ] and finally views.py: import datetime from django.shortcuts import render # Create your views here. def index(request): now = datetime.datetime.now return render(request, "newyear/index.html", { "newyear": now.month == 1 and now.day == 1 }) This is the error its marking: path('hello/', include("hello.urls")) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: invalid syntax. Perhaps you forgot a comma? Sorry if I wasn't clear enough. I've been trying to solve this for hours, any help would be appreciated. Thanks! -
Getting my backend url in verification email instead of frontend url
Like the title says, I'm receiving the wrong link in an activation email and I'm not quite sure how to change it... So far I have been able to sign users up, but when they receive the account activation email, it includes the wrong url. Right now it currently includes my backend url that I used to make the post request. I am still very much new to redux and django so I'm still trying to figure out everything. I know it likely has something to do with my .env file and I believe my auth.js actions file, but I'm not a 100%. Email: You're receiving this email because you need to finish activation process on total-weather-backend.herokuapp.com. Please go to the following page to activate account: https://total-weather-backend.herokuapp.com/activate/:uid/:token However, the link is meant to go to the front end like so: https://total-weather-frontend.com/activate/:uid/:token I'm just not sure where the email is getting this url exactly. I figured it has to be from the .env and either the signup or verify action from the post request. If it is getting it from the post request, is there a way to redirect the user to the right url? I know I was using localhost:8000 … -
How to turn django into .exe that auto launches browser?
I have made a djangoproject with a venv folder. With cmd I can launch my project by: activating the environment with: venv\Scripts\activate then inside the environment: python manage.py runserver 8000 opening my browser and going to http://127.0.0.1:8000/ I am trying to turn my django project into something my client can run without having python. And that will auto start the server and open the browser link with just one click of a button. I used pyinstaller on manage.py to turn the whole thing into windows exe's, but the problem is that now when I click on that exe, it doesn't run the server. It just gives me the same output than if I'd run manage.py directly (without 'runserver'): Type 'djangoProject.exe help <subcommand>' for help on a specific subcommand. Available subcommands: [...] How do I make it so that I get an exe which does the 'runserver' command, and launches the browser? What I've tried: I thought maybe I could create another script that runs the exe, but doing djangoProject.exe runserver in cmd just gives me the error: RuntimeError: Script runserver does not exist. And I also tried doing something like writing a python script (shown below) that would do the … -
How to address "sqlite3.OperationalError: attempt to write a readonly database" In django migration when sqlite db file is writable
This is not the usual writable file problem. With a new database on django 3.2.7, sqlite 3.31.1: I can run the django shell, create an sqlite3 db directly using sqlite (using the settings DATABASE parameters). I can even stick tables in it etc. using a cursor in the shell without any problems. However, if I run django's migrate command it gives: Traceback (most recent call last): File "/tools/cliosoft/sos/7.10.p3/sos_7.10.p3_linux64/sosmgrweb/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/tools/cliosoft/sos/7.10.p3/sos_7.10.p3_linux64/sosmgrweb/venv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 381, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: attempt to write a readonly database If there is no initial sqlite3 file, the django migrate command creates a new file of zero bytes in size and gives the same error as above. The user is the same throughout and has write permission to the folder (and to the sqlite3 db file). The virtual environment is on a read only mounted volume (I'm thinking this must be somehow causing the problem) but everything else in the venv appears to be working. -
How to customize SocialAccount on django-allauth?
So, I'm integrating django-allauth on an django application. The Users table has not only email as a unique field. It has email + company, so the data might be like below: ID Email Company --------------------------------- 1 john@example.com Google 2 john@example.com Microsoft ... 9 john@example.com Apple Note that there are three accounts with the same email, but with different companies. Depending on the different interface (apple.my-app.com; google.my-app.com), John can log in to all these accounts. Now, we want to integrate SocialLogin to this app. In the current approach, django-allauth socialaccount keeps the accounts unique with unique_together = ("provider", "uid"). Each account is also linked with one single user account. See here My working approach would be unique_together = ("provider", "uid", "company"), so by that having the Social Accounts table like: User UID Provider Company --------------------------------- 1 abc GitHub Google 2 abc GitHub Microsoft 9 abc GitHub Apple Any idea how this can achieved WITHOUT FORKING THE REPO? -
django-filter: ModelMultipleChoiceFilter does not validate GET request parameter?: ValueError if not int
Problem I have a working django-filter based ModelMultipleChoiceFilter implementation (see below). A valid (and functional) request could be: http://fqdn/?authors_filter=9684 But if I get a "malicious" request, say: http://fqdn/?authors_filter=9xyz4 I get a ValueError: Field 'id' expected a number but got '9dyz4'., resulting in a ServerError with DEBUG = False. Questions Where am I missing some kind of validation/sanitizing for these kind of URL GET parameters? How can this filter validate the type (here: integer) before trying to build a queryset filter? And fail silently if the parameter is not an integer? Guesswork Perhaps the ModelMultipleChoiceFilter does not handle this validation, but another filter (eg. NumberFilter) must be used in conjunction with ModelMultipleChoiceFilter (mentioned in https://github.com/carltongibson/django-filter/issues/824#issuecomment-343942957)? But I did not manage to mix these two filters successfully... Implementation # models.py class Author(models.Model): last_name = models.CharField(max_length=255) first_name = models.CharField(max_length=255, blank=True) # filters.py class PublicationFilter(django_filters.FilterSet): authors_filter = django_filters.ModelMultipleChoiceFilter( field_name='authors__id', to_field_name='id', queryset=Author.public_objects.all(), ) class Meta: model = Publication strict = False fields = ( 'authors_filter', ) -
Ngnix Guniorn Django bare minimum site-available
My gunicorn server is running at: 123.123.123.123:8000 //my server ip and sth.sthmore.org:8000 // my domain name /etc/nginx/sites-available/mypro // mypro is a filename server { listen 80; server_name sth.sthmore.org; location / { proxy_pass http://127.0.0.1:8000; // 123.123.123.123:8000 doesn't work either proxy_set_header Host $host; // no idea what is this for proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; // no idea ... } } This comes from here : https://gunicorn.org/#deployment If i call 123.123.123.123 or sth.sthmore.org I get the default ngnix page and not the gunicorn page which runs on ...:8000. How does the right file should look like? -
tell me what it means this symbol ` ` and what programming language we can use and how we use it?
please tell me what it means for this symbol `` and what programming language we can use and how we use it? I tried a lot of documentations and I can't find answers. I'd like to know how to use it in my code. -
SMTPServerDisconnected at /auth/users/
I am currently working with Python 3.10.0 and Django 4.0 on the back end, and React/Redux on the front end. I have an app where after a user signs up, an activation email will be sent. However, the email never shows up and while visiting the backend, I see this error inside the network tab in devtools. I switched from gmail due to the work arounds that ended up not working for me so I went with SendGrid, but haven't gotten that to work yet either. From all of the posts I have seen so far, this looks right. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'api' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'email@gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True auth.js // sign up function export const signup = (email, password, re_password) => async (dispatch) => { const config = { headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, }; const body = JSON.stringify({ email, password, re_password }); try { const response = await axios.post( `${process.env.REACT_APP_API_URL}/auth/users/`, body, config ); dispatch({ type: SIGNUP_SUCCESS, payload: response.data, }); } catch (err) { dispatch({ type: SIGNUP_FAIL, }); } }; -
How to update a single column in MySQL using API from DRF
I want to auto-increment the value of the column upon URL hit using DRF class-based API. Proposed URL: /autoincrememt/<id>/ I have the functional API but it is returning 201 even the element to update is not present in the database. @api_view(['POST']) @permission_classes([permissions.IsAuthenticatedOrReadOnly]) def updateClick(request, uri_id): p = Url_data.objects.filter(uri_id=uri_id).update(clicks=F('clicks')+1) print("PPPP: ", p) url_obj = Url_data.objects.all() serializer = ClickSerializer(url_obj, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.status_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is what I wrote so far... class Increment(APIView): """ Update click count when hit. * Requires token authentication. """ permission_classes = [permissions.IsAuthenticatedOrReadOnly] def patch(self, request, uri_id, *args, **kwargs): if request.method == 'PATCH': patch_url = Url_data.objects.get(uri_id=uri_id) This is also my question asked earlier. -
How to get updates from the input field in Django
I have this code in template {% block content %} <script> function onChange(value) { console.log("log") } </script> <h3>List</h3> <input type="text" placeholder="Filter by..." onchange="onChange(this.value)" value={{ searching_value }} > But it doesn't seem to work.. -
how to bulk_create in DRF Serializer to seperate django instances
I get an array of urls and the goal is to write each url as separate model instance with other constant params that are same for all urls django model: class BlockedUrl(models.Model): url = models.URLField() date_add = models.DateField(auto_now_add=True) class Meta: app_label = 'main' db_table = 'blocked_url' ordering = ['-date_add'] django view: from main.models import BlockedUrl from api.serializers import BlockedUrlSerializer class BlockedUrlsViewSet(GenericViewSet, CreateModelMixin): queryset = BlockedUrl.objects.all() serializer_class = BlockedUrlSerializer permission_classes = (AllowAny,) django serializer: class BlockedUrlSerializer(Serializer): urls = ListField(child=URLField(), min_length=1, max_length=1024) # create - to do (iter the list of urls and insert separately into model with one transaction) def create(self, validated_data): crawler = validated_data['crawler'] blocked_urls = [BlockedUrl(url=url) for url in validated_data['urls']] return BlockedUrl.objects.bulk_create(blocked_urls) # update - raise not implemented error def update(self, instance, validated_data): raise NotImplementedError but it does not work as I get AttributeError: 'list' object has no attribute 'urls' -
Python Pillow load font file .ttf from server
I am using Pillow and I need to load a font from a server, lets say AWS, I bet its possible but I'm not sure how. font = ImageFont.truetype("https://criptolibertad.s3.us-west-2.amazonaws.com/img/fonts/Roboto-LightItalic.ttf", size=40) img_draw.multiline_text((20, 200), "Watevs", font=font, fill=(255, 0, 0)) It doesn't work. How do I load the font file from a server? OSError at /courses/certificate_preview/1 cannot open resource -
Problem in passing attribute to view section
In my settings.urls of main project, the url is as follows: path('announcements/', include('Post.urls'), {'url_type':'announcement'}) In my Post app the URL is as follows: path('all', PostList.as_view()) My view section is as follows: class PostList(generics.ListCreateAPIView): permission_classes=[permissions.IsAuthenticatedOrReadOnly] queryset = Post.objects.all() serializer_class = InstructorSupportSerializer def get_queryset(self): return self.queryset.filter(post_type = self.url_type) As per as the django documentation, url_type was supposed to be passed to view section. What am I doing wrong? Here is the error: AttributeError: 'PostList' object has no attribute 'url_type'