Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What parameters to give an image tag to display an Django image from image.url in database
What keywords should I pass in to an img tag to display an image? my current line is like this: <img src="{{ skill.image.url }}"> models.py: from django.db import models # Create your models here. class Skill(models.Model): name = models.CharField(max_length=100) class Type(models.IntegerChoices): WEBDEV = 1 SOFTWARE = 2 DATABASE = 3 type = models.IntegerField(choices=Type.choices) image = models.ImageField(upload_to='img', blank=True) def __str__(self): return self.name -
React: TypeError: Cannot read property 'match' of undefined
I am using simple React-Django app. I have Django models orders, customer and products. Orders model have many to one relationship with customer and products. I successfully connect my frontend React with Django and able to show the Orders data in React. I want display single customers order and the data looks like this image. In React I made router home and customer Details like this in my app <Router> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/customer/:id" component={PersonDetail} /> </Switch> </Router> After fetching the Order-list. I fetched customer's name and create one link and that link direct to Customer-detail page. From there I was trying fetch single user's product purchase detail but I am getting error: TypeError: Cannot read property 'match' of undefined and in my django backend I am getting this error : ValueError: Field 'id' expected a number but got 'undefined'. I don't what I am doing wrong This is my orderlist const [state, setstate] = useState([]) useEffect(() => { getData() }, []) const getData = async () => { const order = await fetch('http://127.0.0.1:8000/api/order-list/') const orderData = await order.json(); console.log(orderData); setstate(orderData) } return ( <> <div className="App"> { state.map((person: any, index: number) => { return … -
How to send notification to admin when data is stored
I (admin) want to create a way to be notified via email every time a user presses send with their question from the comment page. The site is not setup for a user to create a profile. I have been looking at django-signals but I can't find an example that fits my issue. -
Difficulty in implementing search feature for a django project
This is the path i've set to my urls.py file inside the encyclopedia directory: path("encyclopedia/search.html", views.search, name="search"), This is the view: def search(request): if request.method == 'GET': form = SearchForm(request.GET) if form.is_valid(): querry = form.cleaned_data['querry'] data = util.search_entry(querry) if data is None: return HttpResponse("No matches found!") else: return render(request, "encyclopedia/search.html", { "result":data }) search.html extends layout.html and {{ result }} is simply passed inside the body block. Added the util function search entry as follows: def search_entry(querry): _, filenames = default_storage.listdir("entries") if querry in entries: return querry else: results = [] for entry in filenames: if re.search( querry, entry ): results.append(entry) if not results: return None else: return results And finally, the form template in layout.html: <form action="encyclopedia/search.html" method="get"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> {{ form }} </form> But whenever i enter anything, i get the same error " The view encyclopedia.views.search didn't return an HttpResponse object. It returned None instead. " I am unable to figure this out... -
CSRF token in angular 2
I am coding a simple login,it is working with @csrf_exempt but when I remove it I get the forbidden error. I looked a lot but cant fix it, Please do explain and help me. Django code: @csrf_exempt # @api_view(['POST']) def login(request): if request.method == 'POST': print(request.COOKIES) sadmin_data = JSONParser().parse(request) print(sadmin_data) users = auth.authenticate(email = sadmin_data["email"],password = sadmin_data["password"]) if(users): auth_token = jwt.encode({'email':users.email}, settings.JWT_SECRET_KEY) serializer= LoginSerializer(users) data={ "user":serializer.data,"token":auth_token.decode('utf-8'),"type":users.usertype } return JsonResponse(data,status=status.HTTP_201_CREATED) else: content = {'message': 'Please Contact the developers'} return JsonResponse(content, status = status.HTTP_404_NOT_FOUND) Angular Code: <form (ngSubmit)="onSubmit()"> <div class="card-body"> <div class="example-container"> <mat-form-field appearance="standard"> <mat-label>Enter your email</mat-label> <input matInput placeholder="pat@example.com" [(ngModel)]="sadmin.email" name="email" required> <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error> </mat-form-field> </div> <div> <mat-form-field appearance="standard"> <mat-label>Enter your password</mat-label> <input matInput [type]="hide ? 'password' : 'text'" [(ngModel)]="sadmin.password" name="password" > <button mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide password'" [attr.aria-pressed]="hide"> <mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon> </button> </mat-form-field> </div> <button mat-raised-button class="login-btn" type="submit">Login</button> </div> </form> Also When I print the cookies I get {}. -
How to Get Last Inserted id in Django Slug?
I am trying to create a unique slug, on the basis of last inserted id in my Django Project, But I am unable to get last Inserted id in my Slug, Please elt me know Where I am mistaking. Here is my models.py file... class ProjectStatus(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE, default= None, related_name="ProjectStatusCity", help_text=f"Type: Int, Values: Select City Name.") name = models.CharField(max_length=190, default=None, help_text=f"Type: string, Default: None, Values: Enter Project Status.") slug = models.SlugField(max_length=190, unique=True, default='', editable=False, help_text=f"Type: String, Default: None, Values: Enter Slug.") meta_title = models.CharField(max_length=190, default=None, help_text=f"Type: string, Default: None, Values: Enter Project Status.") def __str__(self): return self.name def get_absolute_url(self): kwargs = { 'pk': self.id, 'slug': self.slug } return reverse('article-pk-slug-detail', kwargs=kwargs) def save(self, *args, **kwargs): value = self.name + "-" + "prsid" + "-" + "city" + "-" + "s" self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) I want the last inserted id after s in thsi line (value = self.name + "-" + "prsid" + "-" + "s"), And I have relation with city so I want city name also here, Please help me to solve this issue. -
How to turn a Django Rest Framework API View into an async one?
I am trying to build a REST API that will manage some machine learning classification tasks. I have written an API view, which when hit, will trigger the start of a classification task (such as: training an SVM classifier with the data the user provided previously). However, this is a long running task, so I would ideally not have the user wait once they have made a request to this view. Instead, I would like to start this task in the background and give them a response immediately. They can later view the results of the classification in a separate view (haven't implemented that yet.) I am using ASGI_APPLICATION = 'mlxplorebackend.asgi.application' in settings.py. Here's my API view in views.py import asyncio from concurrent.futures import ProcessPoolExecutor from django import setup as SetupDjango # ... other imports loop = asyncio.get_event_loop() def DummyClassification(): result = sum(i * i for i in range(10 ** 7)) print(result) return result # ... other API views class TaskExecuteView(APIView): """ Once an API call is made to this view, the classification algorithm will start being processed. Depends on: 1. Parser for the classification algorithm type and parameters 2. Classification algorithm implementation """ def get(self, request, taskId, *args, **kwargs): … -
Best way of using Django queryset where JSONField != {}
class JobAnalysis(Base, XYZ): env_vars = JSONField( default=dict ) job = models.ForeignKey( Job, related_name='jobanalyses' ) seller = models.ForeignKey( ABC, null=True ) class Usage(Base): job = models.ForeignKey( Job, null=True, blank=True ) I want all usages where env_vars has some key pair. usages_qs = Usage.objects.filter( job__jobanalyses__seller__isnull=True ).exclude( job__jobanalyses__env_vars__exact={} ) I am using above queryset to fetch all usage information where seller is null and env_vars is not equals {} usages_qs.query SELECT "Usage"."job", FROM "Usage" LEFT OUTER JOIN "Job" ON ("Usage"."job_id" = "Job"."id") LEFT OUTER JOIN "JobAnalysis" ON ("Job"."id" = "JobAnalysis"."job_id") WHERE ("JobAnalysis"."seller_id" IS NULL AND NOT ("Usage"."job_id" IN (SELECT U2."job_id" FROM "JobAnalysis" U2 WHERE U2."env_vars" = '{}') AND "Usage"."job_id" IS NOT NULL)) But I am seeing performance issue here because .exclude(job__jobanalyses__env_vars__exact={}) create inner query and because of that this select statement is timing out. Is there any better way of writing Django queryset for getting all usage record where seller is null and env_vars != {}? -
django each user needs to create and view data Issue
I have build a simple application for Creating User data, starting from user registration till the CRUD operation. now I want to extend the application to multiple users. i.e. A user can login and does CRUD likewise B user can login and does CRUD operation so on...C,D,E,F,G etc... Each individual user should able to see its own data .... for that i have used decorators/groups ...etc.. My problem is how to pass particular user data into view to see the particular user data like tasks = request.user.Task.objects.all() for this, I am getting error Internal Server Error: /query/ Traceback (most recent call last): File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\s5114509\PycharmProjects\todo Modified\tasks\decorators.py", line 21, in wrapper_function return view_func(request,*args,**kwargs) File "C:\Users\s5114509\PycharmProjects\todo Modified\tasks\views.py", line 107, in query tasks = request.user.Task.objects.all() File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\functional.py", line 225, in inner return func(self._wrapped, *args) AttributeError: 'User' object has no attribute 'Task' [15/Oct/2020 23:07:22] "GET /query/ HTTP/1.1" 500 83300 - Model from django.contrib.auth.models import User from django.db import models # Create your models here. from … -
Jumbotron and background images disappear when the window size changes from full screen to small
Have an issue with my homepage, the jumbotron/background images disappear when the window size changes from full screen to small screen, when it's resized the background/jumbotron images re-appear,how can the images be made responsive ? Below is the styling: <style type = "text/css"> .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; position:center; background-size:cover; background-attachment:fixed; } .jumbotron{ margin-top:20px; background-image:url("{% static '9.jpg'%}" ); background-repeat:no-repeat; background-size:cover; position:center; color:white; } body{ background-image:url("{% static '8.jpg' %}"); background-repeat:no-repeat; background-size:cover; background-position:center center; background-attachment:fixed; overflow:visible; } -
ValueError at / empty range for randrange() (0, 0, 0) Django Hosting
File "/root/payyannuronline/webapp/views.py", line 61, in indexrandom_ads=ads.objects.all()[randint(0,count - 1)]File "/usr/lib/python3.8/random.py", line 248, in randintreturn self.randrange(a, b+1)File "/usr/lib/python3.8/random.py", line 226, in randrangeraise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))ValueError: empty range for randrange() (0, 0, 0) Views.py def index(request): count=ads.objects.count() random_ads=ads.objects.all()[randint(0,count - 1)] return render(request,'index.html',{'nbar': 'index','random_ads':random_ads}) Tenmplate <div class="container"> {% load static %} <img class="mySlides" src="/media/{{ random_ads.cover }}" alt="{{ random_ads.title }}" style="width:100%"> Models.py class ads(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=260) owner = models.CharField(max_length=260) contact = models.IntegerField(null=False) email = models.EmailField(null=True) subject = models.CharField(max_length=360,null=False) description = models.TextField(max_length=2600) cover = models.ImageField(upload_to='images/ads/', default=None) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True,) validity = models.DateField(null =False) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title -
Python code execute through django shell but not through file
I recently installed the python library riskchanges. Now I created the test_lib.py file and try to use the library function as below, from RiskChanges.load_SHP import loadshp loadshp(r'F:\SDSS\1. code\data\Country_border.shp', connstr='postgresql://postgres:admin@localhost:5432/sdss', lyrName='layer', schema='try') And I tried to run this code from the terminal, (python test_lib.py), it shows the following error, Traceback (most recent call last): File "test_lib.py", line 2, in <module> loadshp(r'F:\SDSS\1. code\data\Country_border.shp', File "F:\SDSS\1. code\django\venv\lib\site-packages\RiskChanges\load_SHP.py", line 39, in loadshp geodataframe = geopandas.read_file(shpInput) File "F:\SDSS\1. code\django\venv\lib\site-packages\geopandas\io\file.py", line 139, in _read_file return GeoDataFrame.from_features( File "F:\SDSS\1. code\django\venv\lib\site-packages\geopandas\geodataframe.py", line 427, in from_features "geometry": shape(feature["geometry"]) if feature["geometry"] else None File "F:\SDSS\1. code\django\venv\lib\site-packages\shapely\geometry\geo.py", line 105, in shape return Polygon(ob["coordinates"][0], ob["coordinates"][1:]) File "F:\SDSS\1. code\django\venv\lib\site-packages\shapely\geometry\polygon.py", line 243, in __init__ ret = geos_polygon_from_py(shell, holes) File "F:\SDSS\1. code\django\venv\lib\site-packages\shapely\geometry\polygon.py", line 509, in geos_polygon_from_py ret = geos_linearring_from_py(shell) File "shapely\speedups\_speedups.pyx", line 408, in shapely.speedups._speedups.geos_linearring_from_py ValueError: GEOSGeom_createLinearRing_r returned a NULL pointer If I tried to run the same thing through django shell, it worked fine without any error message, >>> python manage.py shell >>> from RiskChanges.load_SHP import loadshp >>> loadshp(r'F:\SDSS\1. code\data\Country_border.shp', connstr='postgresql://postgres:admin@localhost:5432/sdss', lyrName='layer', schema='try') Please help me to find out the actual error. -
Adding an `if` statement to send an Email when the count of Likes reaches a certain No
I am trying to add an IF statement so that when the Like Count reaches 2 an email is sent. I have written the codes but it is not working, I am trying with the below but it is not working. My question is how to add an if statement so that when any item with likes more the 2 an email is sent a specific email. Here is the models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) likes = models.ManyToManyField( User, related_name='liked', blank=True) def __str__(self): return self.title def total_likes(self): return self.likes.count() Here is the views.py class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post, reply=None).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') reply_id = self.request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create( post=post, user=self.request.user, content=content, reply=comment_qs) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res def LikeView(request): # … -
Django variable creation issue
I have an custom template tag with something like this: @register.simple_tag def getLikesByUser(likedFilter, loggedInUserID): likedPeople = likedFilter personLoggedIn = loggedInUserID for personLiked in likedPeople: if personLoggedIn == personLiked.id: return True return False this will return true or false in my template, is there an option to set this return to an variable in my template? this is how a call this: {% getLikesByUser Post.likes.filter request.user.id %} I would like to have this in a variable so I can further check if is true show button if false don't. I tried this, from suggestion from my previews post: {% with likes_by_user=Post.likes.filter|getLikesByUser:request.user.id %}{% endwith %} and no luck. thanks -
Html Form does not make post request on submit
My html form won't make post request unless I comment out div with id="empty_form". This div is used to create new empty form when add more is clicked. I found that solution here. It seems like that div is marked as required field when I submit form, because when I click add more after trying to submit, new form is highlighted as red indicating required field. I am not sure why this div (id="empty_form") is required when I have not even clicked add more button. Here is my html code: <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {% for form in recipeform %} <div class="row spacer"> <div class="col-2"> <label>{{form.label}}</label> </div> <div class="col-4"> <div class="input-group"> {{ form }} </div> </div> </div> {% endfor %} {{ formset.management_form }} <div> <fieldset id="form_set"> {{ formset.management_form }} <div> <a href="#" class="remove_form">Remove</a> <fieldset> {% for form in formset.forms %} <table class='no_error'> {{ form.as_table }} </table> {% endfor %} </fieldset> </div> <div id="empty_form" style="display:none"> <div> <a href="#" class="remove_form">Remove</a> <fieldset> <table class='no_error'> {{ formset.empty_form.as_table }} </table> </fieldset> </div> </div> <input type="button" value="Add More" id="add_more"> </fieldset> </div> <div class="row spacer"> <div class="col-4 offset-2"> <button type="submit" class="btn btn-block btn-primary">Create</button> </div> </div> </form> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script type="text/javascript"> $('#add_more').click(function() { … -
django models improve query
I want get query in model def Currently, 5 queries occur when entering into the template. {{ comment.get_all_children }} Currently I want to have fewer than 5 queries. plz... My model class Comment(models.Model): post = models.ForeignKey( Post, related_name='comment_set', related_query_name='comment', on_delete=models.CASCADE ) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) comment = models.ForeignKey('self', related_name='reply', on_delete=models.SET_NULL, null=True) content = models.TextField() def get_children_filters(self, include_self=True): filters = Q(pk=0) if include_self: filters |= Q(pk=self.pk) for c in Comment.objects.filter(comment=self): _r = c.get_children_filters(include_self=True) if _r: filters |= _r def get_all_children(self, include_self=True): table_name = Comment.objects.model._meta.db_table query = ( "WITH RECURSIVE reply (id) AS (" f" SELECT {table_name}.id FROM {table_name} WHERE id = {self.pk}" " UNION ALL" f" SELECT {table_name}.id FROM reply, {table_name}" f" WHERE {table_name}.comment_id = reply.id" ")" f" SELECT {table_name}.id" f" FROM {table_name}, reply WHERE reply.id = {table_name}.id" ) if not include_self: query += f" AND {table_name}.id != {self.pk}" return Comment.objects.filter( pk__in=[comment.id for comment in Comment.objects.raw(query)] ).select_related('author', 'comment', 'post').prefetch_related('author') class Meta: ordering = ['-id'] -
ImportError while running a unit test in Django
I am inheriting an existing project and since I want to implement unit testing for the future modules, I have tried to run a very simple test like: class CalcTests(TestCase): def test_add_numbers(self): """ Test that two numbers are added together """ self.assertEqual(add(3, 8), 11) However, it shows the Import Error ImportError: cannot import name 'ConfigSerializer' from partially initialized module 'api.serializers' (most likely due to a circular import) (/Users/nick/work/shiftwork_backend/api/serializers/__init__.py) so I looked at the init.py in the serializers file and it looked like this: from .default import * from .backup import * from what I understood, it's a not-so-good practice to use asterisks so instead, I imported all the serializer classes manually by naming every single one of them. However, I still get the same error. If you want a better reference, below is the whole error message: ====================================================================== ERROR: api.serializers (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: api.serializers Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/Users/nick/work/shiftwork_backend/api/serializers/__init__.py", line 1, in <module> from .default import * File "/Users/nick/work/shiftwork_backend/api/serializers/default.py", line 10, in <module> from api import views File "/Users/nick/work/shiftwork_backend/api/views/__init__.py", line 1, in <module> from .base import * … -
"<Order: Order None>" needs to have a value for field "id" before this many-to-many relationship can be used
I am trying to fix an error related to my e-commerce project to show the context in Admin through PDF.html so I am trying to fix it but I got this error and I don't know how to solve it. "<Order: Order None>" needs to have a value for field "id" before this many-to-many relationship can be used. here is the views.py @staff_member_required def admin_order_pdf(request, order_id): html = render_to_string('pdf.html', {'order': Order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) class Order(models.Model): items = models.ManyToManyField(OrderItem) here is the url path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') -
my images are appearing as a broken file in django
im trying to build a webdite that allows the users to post product image and description for products they want to sell. but i am getting a broken image thumpnail. this is my settings.py file """ Django settings for mum 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/ """ import os from pathlib import Path # 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 = 'tbe4^5o02%t@$e4n551llb@_5d_!l+8j2+je_a5gl6610zmfu)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'products.apps.ProductsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'mum.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', ], }, }, ] WSGI_APPLICATION = 'mum.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } … -
Azure Active Directory Authentication from Django-REST-Framework and ReactJS App
Seems like something pretty basic to implement, but I've been struggling for several days with it now. Trust me, I've asked enough questions here and on GitHub developer repos regarding it. Essentially: User navigates to domain.com/admin This URI is for internal company users only Thus, the user needs to be verified against the organizations Azure AD If they are a user, it takes them to the dashboard; If not, they are rejected from entering Simple, right? I'm finding not so much. I've been trying to do it server-side with DRF. Mind you, my Django backend, does not serve any static assets. It is strictly and API that consumes and provides data. It at no point uses Django Templates. I'm finding most of the libraries are out dated, have poorly written documentation, or just don't work for my use case (DRF). I've tried a handful and can't get any of them working. The ones I've tried: python-social-auth python-social-auth-django drf-social-oauth2 django-rest-framework-social-oauth2 I understand that this can also be done client-side with ReactJS libraries and supposedly it is secure. I haven't tried yet. I have no preference for either server-side or client-side just as long as user's information can be put in the … -
Django Annotate - Can I used the fields created in annotate for another field created in annotate?
I am calculating the sum of scores by dept and the number of users in each department in annotate like this: queryset = Depts.objects.annotate(total_pts=Sum('userprofiles__user__activity_user__activity_category__pts'), total_users=Count('userprofiles', distinct=True)).order_by('-total_pts') I also want to send back as part of the return data avg_score = total_pts / total_users. Is there a way to add this into the annotate, or chain them together, or otherwise add this to the return queryset? Thank you. -
Postgres db FATAL: password authentication failed for user
I need help. So I am hitting a wall and have been looking around for solutions but nothing seems to be working for me. I am trying to get the backend to connect to the DB but it keeps returning the error below: django.db.utils.OperationalError: FATAL: password authentication failed for user "app". If I try changing the db_host to localhost or 127.0.0.1 it just throws back an error saying it can't find anything on port 5432. but unless I'm missing something the user and password match and have been added in the correct locations. I would appreciate any help that can be offered. I've tried wiping the containers and images and restarting and nothing seems to be working. does anyone have ideas as to what the issue may be? error Traceback (most recent call last): api_1 | File "manage.py", line 10, in <module> api_1 | execute_from_command_line(sys.argv) api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line api_1 | utility.execute() api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute api_1 | self.fetch_command(subcommand).run_from_argv(self.argv) api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv api_1 | self.execute(*args, **cmd_options) api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute api_1 | output = self.handle(*args, **options) api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 83, in … -
Django+Axios: Multiple Files upload (foreignkeys) [READ FIRST]
Greeting! (feel free to edit this post, i am exhausted ...) I have a form in ReactJs that allows multiple files upload for a single post. ISSUE i can't save these files(images) when they hit Django ( django setup is good, the issue is coming from axios). Code Sample updatePost = (data) => { let formData; const hasFile = Boolean(data.images.length); if (hasFile) { formData = new FormData(document.getElementById('postForm')) // for (let dataKey in data) { // if (dataKey === 'details') { // formData.append("details", [...data["details"]]); // } // else if (dataKey === 'images') { // formData.append("images", [...data["images"]]); // } // else { // formData.append(dataKey, data[dataKey]); // } // } for (let val of formData.entries()) { console.log(val[0] + ', ' + val[1]); } } else { formData = data; } if (!Boolean(data.id)) { return this.createPost(formData, this.axiosConfig({ 'hasFile': hasFile })) }; return axios.put( `${data.path}`, formData, this.axiosConfig({ 'hasFile': hasFile }) ); } axiosConfig = (param = {}) => ({ headers: { 'Authorization': `Token ${this.fetchToken()}`, 'content-type': param.hasFile ? 'multipart/form-data' : 'application/json' } }) return of console.log(...) name, sfdfsd Service.js:57 description, Et animi inventore et. Placeat sit laudantium voluptas et nihil architecto nemo aperiam. Adipisci voluptatem accusamus atque molestias qui. Service.js:57 category, 7 Service.js:57 subcategory, 39 Service.js:57 … -
How to set a table to UTF-8 in Django?
I am trying to update 2 tables with the SQL command like so: ALTER TABLE sessions MODIFY username VARCHAR(50) CHARACTER SET utf8; ALTER TABLE users MODIFY username VARCHAR(50) CHARACTER SET utf8; However, I need to do this in Django. Is there a way to set these table columns to utf8 through Django and then apply to the database via migration? -
I am trying to consume a method that I have in django but it generates an error of is not JSON serializable
@action(detail=False, methods=['post']) ## etiqueta que define el metodo def generateGuia(self, request): contrasenaEncriptada = 'contra' client = Client('url/soap') header_value = header arrayGuias = [ '' ] envios2 = [{ 'box':{ 'objEnvios': [{ 'EnviosExterno': { 'idePaisDestino': 1 . . . 'objEnviosUnidadEmpaqueCargue': { 'EnviosUnidadEmpaqueCargue':{ . . . } } } }] } }] data3 = client.service.CargueMasivoExterno(envios = envios2, arrayGuias = arrayGuias, _soapheaders=[header_value]) print(data3) ## respuesta sin necesidad de serializer return response.Response({ 'token': data3 }) response : Object of type boxResponse is not JSON serializable