Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework has_object_permission not returning specified "message"
I have created a permission class for Detail View in DRF as below class IsDealOwner(permissions.BasePermission): message = "You are Not Authorized to Access the Deal" def has_object_permission(self, request, view, obj): user_roles = view.request.STRATA_USER_ROLES user_id = view.request.STRATA_USER_ID company_id = view.request.STRATA_COMPANY_ID if settings.CRM_ROLE in user_roles: return True if obj.investor_id == user_id: return True if obj.distributor_id: if obj.distributor_id == user_id: return True if obj.partner_id: if (obj.partner_id == company_id) and (settings.PARTNER_ROLE in user_roles): return True return False But when the object level permission is not specified, I am getting the error "Authentication Credentials were not provided". Why is it not returning the message specified in message attribute (As per DRF docs)? -
Need help designing a permissions system in Django and DRF
I'm trying to design a seemingly simple permissions system in Django and DRF. Right now, I have a user model, User, a custom group model, CustomGroup, an article model, Article, and finally a source model, Source. Just for reference, I'm using Django Rest Framework and Django Guardian. The article model contains a field source. I'd like a system built such that when a user makes a query request for articles, depending on their assigned custom group, return articles that omit articles that belong to a specific source. What I was thinking of implementing was something along the lines of class Source(models.Model): name = models.CharField(max_length=255) class Article: sources = models.ManyToManyField(Source) ... class Meta: permissions = ( 'can_view_source_1', 'Can View Source 1', 'can_view_source_2', 'Can View Source 2', ... 'can_view_source_n', 'Can View Source n' ) From there I can then assign these specific permissions to my custom group model. So, when a user makes a request for a queryset containing n sources, I can then iterate over all the sources by name and check if the user's custom group has permission to view that group. Something like (pseudocode warning!) the code below in my view or serializer. for source in sources_from_queryset: if not … -
Django: Analyse Website to make it quicker
I was wondering what can we use to analyse our code in django. My website seems to show some timeout and some webpage take 2 seconds to open. I`ve attached a screenshot but I would like to know if using bootstrap could be the reason and if I should move to react. -
django elasticsearch-dsl 7.1 check connection before send data to elastic
i have some problem with integration of elasticsearch-dsl to django app this is my documents.py from django_elasticsearch_dsl import Document, fields, Index from django_elasticsearch_dsl.registries import registry from .models import CustomerTransaction, CustomUser # from django.conf import settings customerTransaction = Index('core_custrans') customerTransaction.settings( number_of_shards=1, number_of_replicas=0 ) @registry.register_document class CustomerTransactionDocument(Document): user_emet = fields.ObjectField(properties={ 'slug': fields.TextField(), 'num_cni': fields.TextField(), }) user_recep = fields.ObjectField(properties={ 'slug': fields.TextField(), 'num_cni': fields.TextField(), }) class Index: name = 'custrans' class Django: model = CustomerTransaction fields = [ 'type_trans', 'montant', 'solde_pass', 'solde_actual', 'date_trans' ] def get_instances_from_related(self, related_instance): return related_instance.customertransaction_set.all() @registry.register_document class CustomUserDocument(Document): class Django: model = CustomUser index = 'core_customUsers' fields = [ 'slug', 'num_cni', ] ignore_signals = True class Index: name = "customuser" i want to know how can i check the availability of elastic before saving data in elasticseach to avoid this exception elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7ff6a6890a60>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7ff6a6890a60>: Failed to establish a new connection: [Errno 111] Connection refused) i want to check availability of elastic before saving regards! -:) -
Want to create a non primary key auto field
Is it possible to create a non primary key auto-field? When the format of such order is 01010, 01011, 01012, and so on How will this look on my models.py -
to add dynamic images in django as using background-image (HTML) tag?
My template is this . you can see clickin this [enter link description here][1][1]: https://colorlib.com/wp/template/eatery/ if i show you the html code which is behind <div class="slider-item" style="background-image: url('img/hero_2.jpg');"> <div class="container"> <div class="row slider-text align-items-center justify-content-center"> <div class="col-md-8 text-center col-sm-12 element-animate"> <h1>Delecious Food</h1> <p class="mb-5">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi unde impedit, necessitatibus, soluta sit quam minima expedita atque corrupti reiciendis.</p> <p><a href="#" class="btn btn-white btn-outline-white">Get Started</a></p> </div> </div> </div> </div> Not working like these ways <div class="slider-item" style="background-image: url({%static'/img/hero_1.jpg'%});"> or <div class="slider-item" style="background-image: url{%static'/img/hero_1.jpg'%}"> I don't want to add like an img tag like this way. it is not coming how i am expecting .when i am trying with <img> images are loading well.." <img src="{% static '/img/hero_2.jpg' %}" />" please help me with this thank you -
How is a Django app on Google App Engine structured?
I have read through all of Google's documentation on App Engine and various other blog posts but I still do not have a clear idea on the structure of a Django app running on App engine. As I see things, App engine instances are attached to one SQL database and Google provides auto-scaling and auto load balancing that will replicate your SQL database according to current load. What does this mean in terms of Django python code? All it seems to take to deploy a Django app is to run glcoud app deploy. If an App Engine instance's SQL database is scaled and replicated automatically in real time, is the Django app replicated along side them? Or will all HTTPS requests go through a single Django app no matter the replications? In addition, is the Django backend code physically hugging the database it is connected to? -
why do I receive an error when I want to start my django app?
When I start my dajngo app with the "manage.py runserver" command, I receive the mistake : `Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?` However, I've just verify the installation of all requirements, and my virtual environment is well activated. So I don't know why it's not working. Thank for all of your answers ! -
Django prefetch_related for M2M with through relationship
I'm try to decreasing queries to single query but queryset returns 2 queries. I tried some method but nothing changed Models.py class Match(models.Model): ... participant = models.ManyToManyField(TournamentTeam, through='MatchParticipant') ... class MatchParticipant(models.Model): match = models.ForeignKey(Match, on_delete=models.SET_NULL, null=True, blank=True) team = models.ForeignKey(TournamentTeam, on_delete=models.SET_NULL, null=True, blank=True) views.py queryset = Match.objects.prefetch_related( Prefetch( 'participant', queryset=MatchParticipant.objects.select_related( 'match','team' ), ), ).select_related('some_foreignkey',).get(slug=slug) -
Why are my Django importations no longer working properly
I've been using Django with pycharm and it's been working fine, but suddenly I couldn't use Django without opening a virtual environment and installing it, then I noticed I could no longer import path, include, views, generic etc even on my old project where they used to work, they're no longer responsive. I've spent a lot of time trying to resolve this but to no avail. This happens both in pycharm and vscode. thanks -
Object of type JpegImageFile is not JSON serializable
I'm trying to use celery in my web app, but I don't know exactly how. I take out the image update in task, and he complains about the serializer constantly tasks.py from celery import shared_task @shared_task def update_image(image, width, heigth): output_size = (width, heigth) image.thumbnail(output_size) image.save() models.py: def save(self): img = Image.open(self.image.path) task = update_image.delay(img, self.width, self.heigth) views.py: def put(self, request, pk): saved_content = get_object_or_404(Content.objects.all(), pk=pk) data = request.data.get('content') serializer = ContentSerializer( instance=saved_content, data=data, partial=True) if serializer.is_valid(raise_exception=True): content_saved = serializer.save() return Response({ "success": "Picture '{}' updated successfully".format(content_saved.id) }) Error: Object of type JpegImageFile is not JSON serializable Request Method: PUT -
Django changing model booleanfield not working
model public = models.BooleanField(default=False) view @login_required def topic_visibility(request, topic_id, visibility): """Change topic visibility, then redirect to topics page""" topic = Topic.objects.get(id=topic_id) check_instance_ownership(request, topic) if visibility == 0: topic.public = False elif visibility == 1: topic.public = True return redirect('learning_logs:topic', topic_id = topic_id) url pattern path('topic_visibility/<int:topic_id>/<int:visibility>', views.topic_visibility, name="topic_visibility"), A button dropdown allows the user to select whether they with for the model to be public (True) or private (False). When the user visits the respective url that interacts with the view, nothing is changed. I suspect it may have something to do with the topic model not being saved? -
what does " python manage.py migrate " in django do exactly?
I am new to django, and the tutorial directly applied this command without explaining. After searching, I found out something call migrations in django, but didnt understand it either as I am a complete newbie in this What does the python manage.py migrate command do exactly? What are migrations? -
Use format in query parameter for ViewSet in Django Rest Framework
I have a ViewSet which returns JSON object. Now I need to return CSV file for download, using the existing ViewSet. If I will add "format" as a query parameter, like "site.com/api/answers?format=csv" django will return me "Not Found", before reaching the ViewSet: { "error": { "message": "Not found." }, "result": false } My ViewSet: class AnswerViewSet(ViewSet): def list(self, request: Request) -> Response: request_serializer = AnswerRequestSerializer(data=request.query_params) response_serializer.is_valid() return Response(response_serializer.data) Where should I change this behavior to return CSV file, if I add format=csv to a query? -
Django website is displaying "It works! Python 3.6.8"
I recently deployed a Django website on namecheap and it has been running properly not until yesterday when I started seeing: It works! Python 3.6.8 Please what can I do rectify this issue. -
Django model fields don't show up in Admin page
I am a beginner to Django and am having trouble seeing all the Model Fields when I try to load them on the Django Admin page. I add the app correctly in the settings page, do a relative import to the admin page and successfully get the model to show up in the Admin page, but the problem is that most of the time, Fields that I have entered are missing. I usually just displays the last one or two and only if they are TextFields. This is all the Fields I enter into the text editor But this is all I end up seeing -
Django Model save() retains mutable reference for JSONFields()
# Model contains only one JSON field class TestModel(models.Model): field = JSONField(default=dict) # Dictionary, assigned to model.field field_json = {"test": 5} model = TestModel(field = field_json) model.save() # Returns true. WHY??? print(id(model.field) == id(field_json)) After saving a model, shouldn't the model refresh from db? Why is the model field retaining a mutable reference to the original dictionary object? -
Pass a file to xlrd.open_workbook()
I am trying to open a file with xlrd.open_workbook() but am getting an error: expected str, bytes or os.PathLike object, not InMemoryUploadedFile Here's my code: def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_file(request.FILES['file']) def handle_file(f): book = xlrd.open_workbook(f) What's the correct way to pass a file? -
Exception happened during processing of request from ('127.0.0.1', 59369)
I am getting this error in the command line, but it isn't affecting the website in anyway now, but I want to know what can be the cause of this error. Does anyone know? Exception happened during processing of request from ('127.0.0.1', 59369) Traceback (most recent call last): File "C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() File "C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
Parsing error: Expected corresponding JSX closing tag for <Route>?
Am trying to link my car page so when clicked on it could go to that page but this error keeps on popping up saying jsx closing tag for route and don't know why it could be popping up as my tags are closed? import React from 'react'; import logo from './logo.svg'; import './App.css'; import Header from './components/header'; import Footer from './components/footer'; import Home from './components/home'; import About from './components/about'; import Car from './components/car'; import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'; function App() { return ( <Router> <Switch> <Route exact path="/"> {create_page(<Home />)} </Route> <Route path="/home"> {create_page(<Home />)} </Route> <Route path="/about"> {create_page(<About />)} <Route path="/home"> {create_page(<Home />)} </Route> <Route path="/car"> {create_page(<Car />)} </Route> </Switch> **Here is where I keep on trying to fix the code but it keeps on saying close tag for route yet route is already closed?** ); } function create_page(page) { return ( <div className="App"> <div className="header"> <Header /> </div> <div class = "page"> {page} </div> <footer> <Footer /> </footer> </div>) } export default App; This is the error that pops up Parsing error: Expected corresponding JSX closing tag for </Route> </Switch> ^ -
Django - edit uploaded file Before final saving
i want to make a site for uploading and processing of images. sometimes, some files need some editing before saving. i want edit the uploaded file before saving it to media dir (mostly to avoid IO interaction and only keep original file in memory and discard after saving edit version). edit: so i thought i have to run the edit function in POST, and change information in request.FILES. but i failed, and don't know what to do anymore. NOTE: im mostly looking for a way to do it via class views. here's some code for refrence: The model: class FilePatient(models.Model): file_imag = models.FileField(upload_to='') The View: class FileAddView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, CreateView): model = FilePatient fields = ['file_imag'] def post(self, request, *args, **kwargs): if request.FILES['file_imag'].name.endswith('.png'): newFile=editFile(request.FILES['image_imag']) # what to do, what not to do return super().post(request, *args, **kwargs) -
Django in Heroku throws error column does not exist
I'm trying to deploy my django project to heroku, however it's not working particularly well. When I try to make an account, everything works fine, and logging in is fine. Locally, everything works as intended. However, when I try to create a new model instance on heroku, it throws the following error: ProgrammingError at /contracts/new/ column "completed" of relation "contracts_clientcontract" does not exist LINE 1: INSERT INTO "contracts_clientcontract" ("UUID", "completed",... ^ I tried the advice given at Django Programming error column does not exist even after running migrations but it didn't work. So I tried removing migration history, and that didn't work. So I made a version of the project that had no migrations at all and sent that to heroku, and then ran both makemigrations and migrate using heroku run bash, and I still get the same error. I'm not sure what's going on here... Is it possible that because heroku uses postgres that I need to change the projects settings to reflect that, since it's using sqlite3? If so, I'll feel dumb but validated. Can anyone point me in the right direction? -
Can't install Django 2.1.6
I used pip install Django==2.1.6 There is error ERROR: No matching distribution found for Django==2.1.6 How to install Django 2.1.6? Don't want to install it from git because need to validate hashes. -
django with jquery select values
Hello I need some help with intergrating django to jquery am not sure of how to go about it but I have given it an attempt.. I need when someone clicks the award placeholder depending on the value they have chosen the nominee placeholder displays the nominees nominated under that award from the database table called Nominee Here is the form code: <form class="form-group" method="post" id="formsubmit"> {% csrf_token %} <div class="row"> <div class="col-md-6"> <label>FOR AWARD</label> <select name="award" class="form-control" id="award" required> {% for name in award%} <option>{{ name.award_name }}</option> {% endfor %} </select> </div> <div class="col-md-12"> <label>NOMINEE NAME</label> <select class="form-control" name="nominee" id="nominee" required> <option value=""></option> </select> </div> </form> here is the jquery code <script> $("#award").change(function () {// get the url of the `load_cities` view var award = $("#award"); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: {% url 'submit' %}; // set the url of the request (= localhost:8000/hr/ajax/load-cities/) data: { 'award': award// add the country id to the GET parameters }, success: function (data) { // `data` is the return of the `load_cities` view function $("#nominee").html(data); // replace the contents of the city input with the data that came from the … -
Invalid salt when logging in via django admin panel
I'm having some trouble hosting a django API on a separate server. When using localhost everything works, however when I log in to the server admin panel I get an "invalid salt" error. Originally, I had my own login method that used bcrypt, but I decided to scrap that in favor of using facebook authentication. I've removed all references to bcrypt from my views. The problem lies with the built in admin interface. I haven't modified the code for that at all, but I am unable to log in. I can share my code, but I'm not even sure what files would be relevant to share, so I'm happy to update as needed.