Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
text area show in one line in django template
I use Django. My text field was created by RichTextField. In the browser, the text does not break to multiline and exceed from container class like below: References References References References References References References References References References References References References References References References References References References References References References References References References References References I want to show text like this in HTML format: References References References References References References References References References References References References References References References References References References References References References References References References References References References -
delhivery api integration in django python
i'm trying to integrate delhivery api with django. i have the using the test api key its returning 200 with format key missing in POST. i'm not sure what i'm getting wrong import requests shipping_api_token = "api_token" shipping_api_base_url = "https://staging-express.delhivery.com/api/" warehouse_name = "Primary" headers = { "Authorization": f"Token {shipping_api_token}", "Content-Type": "application/json" } def createOrder(orderID="", orderDate="yyyy-mm-dd", billing_name="", billing_address1="", billing_address2="", billing_city="", billing_state="", billing_pincode="", billing_country="", billing_email="", billing_phone="", shipping_is_billing=True, shipping_name="", shipping_address1="", shipping_address2="", shipping_city="", shipping_state="", shipping_pincode="", shipping_country="", shipping_email="", shipping_phone="", Items=[], paymentMethod="Prepaid", subTotal=0, length=0, breadth=0, height=0, weight=0, pickupLocation="Primary"): payload = { "shipment":[{ "add": "M25,NelsonMarg", "phone": 1234567890, "payment_mode": "COD", "name": "anita", "pin": 325007, "order": "847"} ], "pickup_location": { "name": "THE0045874-B2C", "city": "delhi", "pin": 12859, "country": "india", "phone": 7418529638, "add": "address" } } try: url = f"{shipping_api_base_url}/cmu/create.json" response = requests.post(url, json=payload, headers=headers) return response.status_code, response.json() except: return 500, {"message": "Error", "status": "fail"} i'm getting this response: { "cash_pickups_count": 0, "package_count": 0, "upload_wbn": null, "replacement_count": 0, "rmk": "format key missing in POST", "pickups_count": 0, "packages": [], "cash_pickups": 0, "cod_count": 0, "success": false, "prepaid_count": 0, "error": true, "cod_amount": 0 } As i can see from doc it also same error: -
Python + How to merge two dictionaries with same key and value
Sample dictionaries skus = ( {'sku': '53009', 'qtyonhand': '50'}, {'sku': '53004', 'qtyonhand': '20'}, {'sku': '53006', 'qtyonhand': '4'}, {'sku': '53007', 'qtyonhand': '500'}, {'sku': '53010', 'qtyonhand': '20'}, {'sku': '53013', 'qtyonhand': '40'}, {'sku': '53014', 'qtyonhand': '20'}, ) product_skus = [ {'sku': '53009', 'line_id': 75128133}, {'sku': '53004', 'line_id': 75453798}, {'sku': '53006', 'line_id': 75504454}, {'sku': '53007', 'line_id': 75504455}, {'sku': '53010', 'line_id': 75504457}, {'sku': '53013', 'line_id': 75504658}, {'sku': '53014', 'line_id': 75504659}, ] Trying to merge both dictionaries on the basis of the key-value pair. Expected Output: merged_skus = ( {'sku': '53009', 'qtyonhand': '50', 'line_id': 75128133}, {'sku': '53004', 'qtyonhand': '20', 'line_id': 75453798}, {'sku': '53006', 'qtyonhand': '4', 'line_id': 75504454}, {'sku': '53007', 'qtyonhand': '500', 'line_id': 75504455}, {'sku': '53010', 'qtyonhand': '20', 'line_id': 75504457}, {'sku': '53014', 'qtyonhand': '20', 'line_id': 75504659}, {'sku': '53013', 'qtyonhand': '40', 'line_id': 75504658}, ) -
How can I POST a new item if "Author" hasn't been created yet?
I'm creating an app to catalog records using React for the Front End and Django+REST Frameworks for the Backend. I'm using HyperlinkedModelSerializer, and it seems I can't create a new record unless the artist has already been created (I'll get an error letting me know ID field can't be null). I then have to include the artist and artist ID if I want to create a new record. I'll copy some of my code below for reference. Thanks in advance for your help! models.py from django.db import models # Create your models here. class Artist(models.Model): name = models.CharField(max_length=100) notes = models.TextField(blank=True, null=True) photo_url = models.TextField(blank=True, null=True) def __str__(self): return self.name class Album(models.Model): title = models.CharField(max_length=100) artist = models.ForeignKey( Artist, on_delete=models.CASCADE, related_name='albums') release_date = models.DateField(blank=True, null=True) acquired_date = models.DateField(blank=True, null=True) genre = models.CharField(max_length=100, blank=True, null=True) label = models.CharField(max_length=100, blank=True, null=True) # songs = models.ForeignKey( # Song, on_delete=models.CASCADE, related_name='songs') notes = models.TextField(blank=True, null=True) photo_url = models.TextField(blank=True, null=True) def __str__(self): return self.title class Song(models.Model): title = models.CharField(max_length=100, default='Song title') track = models.CharField(max_length=100, blank=True, null=True) artist = models.ForeignKey( Artist, on_delete=models.CASCADE, related_name='songs') album = models.ForeignKey( Album, on_delete=models.CASCADE, related_name='songs') song_url = models.TextField(blank=True, null=True) class Meta: unique_together = ['album', 'track'] ordering = ['track'] def __str__(self): return f'{self.track} … -
Why is my SIGNAL not working in Django - what I'm doing wrong?
first of all, I'm not a developer. Trying to build an Application with Django (Version 3.1.2) but facing some issues with signals. I have this Models in my models.py: class PhoneNumbers(models.Model): number = models.CharField(_('Category'), max_length=255) created = models.DateTimeField(_('Created'), auto_now_add=True, blank=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) and a Model Persons class Persons(models.Model): name = models.CharField(_('Name'), max_length=255) number = models.CharField(_(Number), max_length=255) ... The code in my signals.py: from django.db.models.signals import pre_save, post_delete, post_save from django.dispatch import receiver from .models import PhoneNumbers, Persons @receiver(post_save, sender=Persons) def save_contract(instance, sender, created, **kwargs): print("Request finished!") When I save a Person I expect to get a PRINT in the console output, but get nothing. What is wrong? I also add in __init__.py: default_app_config = 'myapp.apps.MyAppConfig' My apps.py looks like: from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' -
How to Add, delete, friend request in django?
#Forms.py ( I have added the form for edit the user profile ) How to Add friend , Delete friend, Send friend request, delete friend in django ? -
DRF "Unauthorized: <route>" when Authorization header is present from React FE
I'm working on integration with Azure AD. I have my ReactJS FE getting the accessToken and now I need to send it to the Django/DRF BE to authenticate it there as well. At any rate, I'm sending the token as a Authorization: "Bearer <token>" and I'm getting a Unauthorized: <route> response. If I comment it out, the request goes through. I'm just trying to understand a couple things: The presence of the Authorization header is obviously telling DRF it needs to do something with it. Does something need to be enabled in DRF settings to handle it? Should I be sending this accessToken to my API in the headers, or the body, of the POST request? // Authentication.js ... const testApiAuthentication = async () => { let accessToken = await authProvider.getAccessToken(); setAccessToken(accessToken.accessToken); if (accessToken) { setAuthenticatingToken(true); axios({ method: 'post', url: '/api/users/', headers: { Authorization: 'Bearer ' + accessToken, }, }) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); } }; ... # views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import AllowAny # Create your views here. class TestView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): print(request) return Response('Hello World') -
Using default with foreignkey model in django
I'm working on a django project where I have 3 models -category -subcategory -product The subcategory is a foreignkey to the category while the product is a foreignkey to both the category and products When I run migrations, I get the error: django.db.utils.IntegrityError: The row in table 'shop_product' with primary key '5' has an invalid foreign key: shop_product.subcategory_id contains a value '1' that does not have a corresponding value in shop_subcategory.id. Models.py from django.db import models from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = "categories" def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) class Subcategory(models.Model): category = models.ForeignKey(Category, related_name='subcategories', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) class Meta: ordering = ('name',) verbose_name = 'subcategory' verbose_name_plural = 'subcategories' def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) description = RichTextField(blank=True, null=True) subcategory = models.ForeignKey(Subcategory, related_name='product', on_delete=models.CASCADE, null=True, default=1) category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', … -
django if statement has an error. What should I fix?
a.html <div> {%for r in rank%} {%if r.nickname==nickname%} <div style="color: aqua;">{{r.nickname}}</div> {%else%} <div>{{r.nickname}}</div> {%endif%} <hr> {%endfor%} </div> views.py def ranking(request): user = request.user rank = Profile.objects.all().order_by('-user_test_point') profile_obj = Profile.objects.get(user=user) nickname = profile_obj.nickname context = {"rank": rank, "nickname": nickname} return render(request, "a.html", context) I want to change the color if the nicknames of the current user and the ones in the context are the same. Context contains the nicknames of users. But error is "Could not parse the remainder: '==nickname' from 'r.nickname==nickname'" -
How to solve this error ERROR: Command errored out with exit status 1: command: 'c:\users\sanid\appdata\local\pr
**This happened when i tried to install mysqlclient via typing pip install mysqlclient ** earlier also i had an error which i solved by installing Visual studio c++ , But what should i do ???? I also saw some solutions but they don't seem to work so if anyone can tell what to do, Please explain in detail as i am new to programming Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz (87 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\sanid\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\sanid\\AppData\\Local\\Temp\\pip-install-koqe6sxg\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\sanid\\AppData\\Local\\Temp\\pip-install-koqe6sxg\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sanid\AppData\Local\Temp\pip-wheel-j4e3bxnr' cwd: C:\Users\sanid\AppData\Local\Temp\pip-install-koqe6sxg\mysqlclient\ Complete output (29 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.8 creating build\temp.win32-3.8\Release creating build\temp.win32-3.8\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\bin\HostX86\x86\cl.exe … -
Django Model designing with M2M
I need some help regarding models designing. I have two models like this (with M2M Field) class Control(models.Model): id = models.CharField(max_length=25, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) status = models.CharField(max_length=255, choices=STATUS_CHOICES, default=NOT_PLANNED, blank=True, null=True) class Vulnerability(models.Model): id = models.CharField(max_length=25, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) level = models.PositiveSmallIntegerField() controls = models.ManyToManyField("Control", verbose_name="control",) What I want to do : When I create a vulnerability with several controls, each control have a weight for the vulnerability. So I can't create a weight field in my control, since it'll be a weight for each vulnerability. The only thing I found is to create a new "linking" class : class VulnerabilityControl(models.Model) vulnerability = models.ForeignKey(....) control = models.ForeignKey(...) weight = models.PositiveSmallIntegerField() But it create a new table etc.. Is there a better way to do this ? Thanks ! -
Django download files
I'm working in a project which I want display many images in a website, so the user can download them. I can display the name of the images, but the download isn't working. I think it's something on my views, because I'm using Django, and getting the error the current path ... didn't match any of this. The name of the directory with the images is Images, and has others sub directories inside, and inside those sub directories, there are the images. My views page, I think the problem is here, in the download function: from django.shortcuts import render import os from django.http import HttpResponse, Http404 from django.http import FileResponse def index(request): flPath = os.listdir('Images/') fl4 = [] for root, dirs, files in os.walk("Images/", topdown=False): for name in files: fl4.append(os.path.join(root, name)) for name in dirs: fl4.append(os.path.join(root, name)) return render(request, 'catalog/index.html', {'path': fl4}) def downloadImage(request, path): imagePath = 'Images/' file_path = os.path.join(imagePath, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type='text/csv') response['Content-Disposition'] = 'inline; filename=' + file_path return response raise Http404 My app urls, catalog.urls: from django.urls import path, include from .views import * urlpatterns = [ path('', index, name='index'), path('Images/<str:path>', downloadImage, name='download'), ] My project urls, SiteSmu4Img: … -
How to integrate any payment gateway for website?
Can someone tell me how to build a website that allows only paid users? I have searched in several sites, I need some sample to create a website, I have a beautiful concept but I couldn't find anything related to mine! waiting for your explanation techies! -
How to manage manytomany field on admin page in Django?
I have two class, class Activity(LTIModel, Position): name = models.CharField(max_length=255, null=False) parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True) student = models.ManyToManyField(User, related_name="learn", blank=True) @admin.register(Activity) class ActivityAdmin(admin.ModelAdmin): list_display = ('name',) I want to manage (add, delete , modify ...) the student field of an activity on the admin page. manytomany student list When i click on a student nothing is happening. Thank you for your help. -
Django base64 TypeError __str__ returned non-string (type bytes)
i got this error: TypeError at /productos/productos/ str returned non-string (type bytes) i think is a problem from convert from base64bits to str, but i dont know how to fix it, im using Procedures on oracle but its dont seem to be an issue. Im ussing django 3.1, oracle database 18c. all works perfectly since i implement the image blob, its a requeriment so i have to use it. At line 56: return render(request, "productos/productos.html", data) views.py def product(request): data = { 'product':() } if request.method == 'POST': id_producto = request.POST.get('id_producto') nombre = request.POST.get('nombre') tipo = request.POST.get('tipo') descripcion = request.POST.get('descripcion') stock = request.POST.get('stock') precio = request.POST.get('precio') catalogo = request.POST.get('catalogo') imagen = request.FILES['imagen'].read() salida = agregar_producto(id_producto,nombre,tipo,descripcion,stock,precio,catalogo,imagen) if salida == 1: data['mensaje'] = 'added sucessfully' data['productos'] = product_list() else: data['mensaje'] = 'cannot save' return render(request, "productos/productos.html", data) def product_list(): django_cursor = connection.cursor() cursor = django_cursor.connection.cursor() out_cur = django_cursor.connection.cursor() cursor.callproc("sp_product_list", [out_cur]) row = [] for row in out_cur: data = { 'data':row, 'imagen':str(base64.b64encode(row[7].read()), 'utf-8') } lista.append(data) return row productos.html Error during template rendering In template C:\Users\galli\desarrollo-web-36sk8mafia\trisix\plantillas\plantilla.html, error at line 0 str returned non-string (type bytes) {% extends "plantilla.html" %} {% load static %} <title>{% block title %}Productos {% endblock %}</title> {% block content … -
Converting Django BooleanField to NullBooleanField and changing default
I need to change a field from my_boolean = models.BooleanField(verbose_name="Safe Visiting Space", default=False) to my_boolean = models.NullBooleanField(verbose_name="Safe Visiting Space", default=None, blank=True, null=True) So I've made the above change within the model and run makemigrations to create from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('my_app', '0164_auto_20201027_0820'), ] operations = [ migrations.AlterField( model_name='mymodel', name='my_boolean', field=models.NullBooleanField(default=None, verbose_name='Safe Visiting Space'), ), ] But this will not set the default of the current 70k records to None but will leave them as False, so I amended the migrations file to from django.db import migrations, models from my_app.models import MyModel def set_my_boolean_default(apps, schema_editor): objects= MyModel.objects.active().filter(my_boolean=False) for object in objectss: object.my_boolean = None object.save() class Migration(migrations.Migration): dependencies = [ ('providers', '0164_auto_20201027_0820'), ] operations = [ migrations.AlterField( model_name='organisation', name='infection_control_safe_visiting_space', field=models.NullBooleanField(default=None, verbose_name='Safe Visiting Space'), ), migrations.RunPython(set_my_boolean_default), ] This will take hours to run. Also, a random check of the database and it doesn't seem to be updating any of the records. What is the right / better way to do this? -
How can I order a DRF queryset by a column computed by multiple relations?
My data model is based on the following relationships: Every Person belongs to an Organization. People can have multiple Addresses. An Organization can have multiple Addresses. Here is the model definition: from django.db.models import ( Model, ForeignKey, CASCADE, CharField, FloatField, ) class Organization(Model): name = CharField(max_length=100) class Person(Model): organization = ForeignKey(Organization, on_delete=models.SET_NULL, related_name='people') class Address(Model): street_number = models.CharField(max_length=20) route = models.CharField(max_length=100) locality = models.ForeignKey(Locality, on_delete=models.CASCADE, related_name='addresses') geometry = PointField(geography=True) class PersonAddress(Model): subject = ForeignKey(Person, on_delete=CASCADE, related_name='person_addresses') value = ForeignKey(Address, on_delete=CASCADE, related_name='person_addresses') class OrganizationAddress(Model): subject = ForeignKey(Organization, on_delete=CASCADE, related_name='organization_addresses') value = ForeignKey(Address, on_delete=CASCADE, related_name='organization_addresses') In a DRF ListCreateAPIView I want to generate a queryset with the following logic: Given a target location (say, lon=10.3, lat= 50.6), list people ordered by distance to either their closest address or their organization's closest address (whichever is closer). So, something along the lines of this SQL query: select distinct round(ST_Distance(ST_GeogFromText('SRID=4326;POINT(10.3 50.6)'), a.geometry))/1000 as "distance", p.id, p.first_name, p.last_name, o.name, a.id, a.route, a.street_number from person p, organization o, personaddress pa, organizationaddress oa, address a where p.organization_id = o.id and p.id = pa.subject_id and o.id = oa.subject_id and ( pa.value_id = a.id or oa.value_id = a.id) order by distance, p.id I think this can be achieved using annotations. … -
How to Calculate days between two dates using Python?
I want to calculate Number of days Between Two Dates using Python Django. Here is my code In my Html, <form method='post' action="something"> <input type="date" name="firstdate"> <input type="date" " name="lastdate"> <input type="submit"> </form> i am sending this form data to view function,i am getting date overthere in dd-mm-yy formet. and if i print overthere, i am getting firstdate and lastdate in below formet, 2020-01-01 2020-02-01 i want to calculate number of days between these two dates.How to Do that? i will be thankfull if anyone can help me with this issue. -
How to create uuid4 file names for uploaded file?
I want to create file names with uuid4 but after saving file and i checked file name, i found it not correct: lets say uuid.uuid4() = 49b9301e-d479-480b-bd41-3054a32d1cf0 so filename should be 49b9301e-d479-480b-bd41-3054a32d1cf0.jpg for example, but if found file name 49b9301e-d479-480b-bd41-30_qJw5Wee.jpg file name ex my model class Attachment(models.Model): file = models.FileField(upload_to=get_upload_path) get_upload_path function:- def get_upload_path(instance, filename): file_extension = filename.split('.') file_extension = file_extension[-1] filename = "%s.%s" % (uuid.uuid4(), file_extension) date = arrow.get(instance.date_created).date() return os.path.join("%s/%s/%s" % (str(date.year), str(date.month), filename)) -
I want to send weekly emails in my Django app. Where should the code that pulls the data from the database and sends the email message live?
The title contains the question - I want to send weekly emails in my Django app. Where should the code that pulls the data from the database and sends the email message live? I have seen examples of code that sends emails, such as this and this, but it is not specified in which file it resides and what's its relationship to the rest of the Django elements. -
Django Cache can I partially clear the cache for specific object view?
I use Django and Redis for caching. from django.views.decorators.cache import cache_page @cache_page(60 * 3) def user_detail(request, id): ... some data return and example url path('users/<int:pk>/', user_detail, name='user-detail') How do I clear the cache for a specific user (for ID = 10 for example) ? http://localhost:8000/users/10/ -
If and or operator django admin models
Im trying to make some kind of logic function " sufficient_information_provided " which returns boolean. As for now im new to python syntax.. i would appreciate if anyone could help figure this out, here is the model in django app class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) relationship = models.ForeignKey(Relationship, on_delete=models.PROTECT) dependant_child_age_range = models.ForeignKey(DependantChildAgeRange, null=True, blank=True, on_delete=models.PROTECT) care_percentage = models.PositiveSmallIntegerField( null=True, blank=True, validators=[ MaxValueValidator(100), ]) income = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) and here is the function in same .py folder @property def sufficient_information_provided(self): b = ('Tenant', 'Partner') if ( self.name and self.date_of_birth and self.relationship and( ( self.relationship.name not in b and self.dependant_child_age_range ) or ( self.relationship.name in b and self.income ) ) ): return True return False what im trying to do is when relationship.name not in the tuple and dependant_age_range is not null and when relationship.name is in the tuple and self.income is not null returns true else returns false here is the admin looks returns true when it should return false. -
Django Rest Framework: Unable to see view or individual files
I am trying to upload file and then trying to see the files in the list view. For example, I would like my uploaded files to show at /files/upload/ and I would like to see each individual item at files/upload/1 or files/upload/file-name. I have created a model and view but I cant seem to find the url to access it. For instance, the pattern Django gives is api/v1/files ^upload/$ [name='lessonpdfmodel-list'] api/v1/files ^upload/(?P<pk>[^/.]+)/$ [name='lessonpdfmodel-detail' The only thing I saved is a file called pokemon.pdf what is that url? is it localhost:8000/files/upload/pokemon.pdf? My Model is: class LessonPDFModel(models.Model): title = models.CharField(max_length=80) description = models.CharField(max_length=225) upload_date = models.DateTimeField(auto_now_add=True) pdf = models.FileField(blank=False, null=False, upload_to='pdfs/') icon = models.ImageField(blank=False, null=False, upload_to='images/') class Meta: ordering = ['upload_date'] def __str__(self): return f"{self.title}" My View is: class LessonPDFViewSet(ModelViewSet): queryset = LessonPDFModel.objects.all() serializer_class = LessonPDFModelSerializer My serializers is: class LessonPDFModelSerializer(serializers.ModelSerializer): # file_uploaded = FileField() class Meta: model = LessonPDFModel fields = ('pdf', 'description', 'upload_date') def create(self, validated_data): return LessonPDFModel.object, create(**validated_data) my urls is: router = routers.SimpleRouter() router.register('upload', LessonPDFViewSet) urlpatterns = [ path('', include(router.urls)), ] -
Django two separate project under one domain as sub directories
I am trying to config Two separate Django project under one domain name as subdirectories, So I can open project1 as https://mycompany.example.com/project1 and project 2 as https://mycompany.example.com/project2 here is my Nginx configuration server { server_name mycompany.example.com; location /static { alias /home/username/project1/static; } location /media { alias /home/username/project1/media; } location /project1/ { rewrite ^/project1/(.*)$ /$1 break; proxy_set_header X-Script-Name /project1; proxy_pass http://unix:/run/project1.sock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /project2/ { rewrite ^/project2/(.*)$ /$1 break; proxy_set_header X-Script-Name /project2; proxy_pass http://unix:/run/project2.sock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mycompany.example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mycompany.example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } This configuration works and I can open it as I mentioned it above, here the problem is static and media location. Only one project's static and media location can be defined here. I need to config static and media location for both the projects, is there any workaround to make … -
how to fix ModuleNotFoundError in django?
I have one project called mysite and two apps (projects, search). I want to import the models from my projects app to my search app views. search.views.py from django.db import models from django.db.models import Q from django.shortcuts import render from projects.models import Project projects.models.py from django.db import models class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path="/img") def __str__(self): return (f"{self.title}, {self.description}, {self.technology}") error Traceback (most recent call last): File "d:/firstwebapp/mysite/search/views.py", line 9, in <module> from projects.models import Project ModuleNotFoundError: No module named 'projects'