Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update multiple resource together in Django DRF
Lets say I have two models in Django: class Inventory(models.Model): created_at = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User, on_delete=models.SET("anonymous"), blank=True, null=True) name = models.CharField(max_length=100, unique=True) nickname = models.CharField(max_length=100, blank=True, null=True) class InventoryProperties(models.Model): key = models.CharField(max_length=100) value = models.CharField(max_length=100) order = models.IntegerField() item = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='properties') What if I would like to add an Inventory and some properties to it from the frontend on the same page (form). Then I would have to save the Inventory item first, then save the properties. As I read in REST this should not be done with one resource (because this is a different resource, so now I have /inventory/:id/properties/): How to handle updates in a REST API? What happens if something goes wrong during saving the properties? I can't rollback easily the saved Inventory item, so I end up with a half-saved object. Also this is really hard to manage on the frontend, because if some error occurs during property saving, the frontend should not save the inventory again. -
is the django application can be not working based on the country language or timezone?
I have developed a Django application and it works perfectly in my laptop but when I delivered it to my customer in germany (the application send him 504 Gateway timeout) and when he try with another laptop also it sends him another content of the application(Exist on the same server), Help please is this reliant to the country language or what exactly am stuck on. Thanks in advance -
How to get row value from table when delete button is clicked?
I am trying to delete row when delete button is clicked. <tbody> {% for dt in data %} <tr> <td> <i class="fa fa-external-link user-profile-icon"></i> <a href="{{dt.url}}" target="_blank">{{dt.url}}</a> </td> <td>{{dt.modified}}</td> <td> <button type="button" class="fa fa-trash-o btn btn-danger" data-toggle="modal" data-target="#exampleModal{{forloop.counter}}">Delete</button> </td> <div class="modal fade bd-example-modal-lg" id="exampleModal{{forloop.counter}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModal{{forloop.counter}}">DELETE</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p> Are you sure you want to delete this row </p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button> <button type="submit" class="btn btn-primary">Yes</button> </div> </div> </div> </div> </tr> {% endfor %} </tbody> When I click on delete button, modal appear for confirmation and when I click Yes then I have to send the {{dt.url}} for corresponding delete button. I could use the input tag with hidden type and set the input value with {{dt.url}} . I am not able to check which delete button is clicked. Please help. -
Django, remove the querystring from a url string
Good day all. I've to modify a string in a template that use Django. the string is a URL, but this can contain a querystring, so basically the url could be: "www.test.com/something" or "www.test.com/something?page=2" I'd like to remove the "?page=2" from the url, in javascript I'd do something like urlString.split("?")[0]; is there any similar solution in django? I can only access the "frontend" of this site, so I cannot define anything, I can only modify the "templates". Thanks in advance. -
add non existing field name to django query
I'm trying to add extra field name base on its sub domains, but i cant do that, here is my views.py def daily_vistors_detail_html(request): address = request.build_absolute_uri('/') host_name = address.partition('://')[2] sub_addr = host_name.partition('.')[0] hotel_name = 'hotel 1' if sub_addr == 'hotel 2': hotel_name = 'hotel 2' lists = MyModel.objects.annotate(hotel_name=hotel_name).order_by('-pk') context = { 'lists':lists } but it returns QuerySet.annotate() received non-expression(s): hotel 1. is there away to achieve that please? thank you -
does we use generic class view more often than function based view in django rest framework
As I am fan of function based view in django_rest because it lets you more control over the class based one. but we have seen most of the functionality of django_rest can be implemented with the generic class based views e.g. pagination, search, filter etc. Could you please advice me should i use generic views more often if not then why I shouldn't? Thanks in advance -
How to Host Emails in Django?
I want to know that how can I Host Emails in Django-Python. And Created Email able to receive and send email from any platform like GMAIL Thanks -
How to use JOIN Django ORM with Postgresql
i need help to build a queryset for the following problem: I have 2 different models: class parentElement(models.Model): name = models.CharField(max_length=50) date = models.DateField() .... other fields class childElement(models.Model): name = models.CharField(max_length=50) date = models.DateField() type = models.PositiveSmallIntegerField( choices=types.CHOICES, null=True, blank=True ) parent_id = models.ForeignKey( "parentElement", related_name="rel_parent", on_delete=models.CASCADE ) .... other fields And I want to have the following query realized with the Django ORM (not in a raw SQL query): SELECT m.*, t1.date as type1_date, t2.date as type2_date FROM parentElement m LEFT INNER JOIN childElement t1 ON t1.parent_id = m.id AND t1.type = 1 LEFT OUTER JOIN childElement t2 ON t2.parent_id = m.id AND t2.type = 2 I don't want to use the .raw(), is there a solution with .annotate() and .extra()? -
Django Channels Login Page
I have a site that uses Django and Vue, hosted in Docker containers, along with other containers like Celery, Redis, Nginx, Postgress etc. I'd like to use Django Channels but cant seem to figure out how a login page is meant to work. I'm not sure if I can do a whole website with Channels exclusively or must I use something like django.contrib.auth or Django REST framework together with Channels, I tried implamenting Django REST framework but got CORS errors. According to the Channels Autentication Docs there are login and logout methods, but they sit in the receive() Channels consumer, what am I meant to do with the connect() method? Am I meant to accept the websocket connection before authenticating? Or am I meant to use another meathod of authenticating my login page? I just need a bit of guidance, your help would be much appreciated. -
How to change the Django date time format in a string
Given a long string (serialized Django object) how can we search all the timestamps and replace them with the correct format (dd/mm/YYYY HH:MM) Example string given: [{"model": "app_name.files", "pk": 294, "fields": {"filename": "user_1/A.pdf", "user": 1, "uploaded": "2022-01-11T16:49:43.897", "updated": "2022-01-11T16:49:43.897"}}, {"model": "app_name.files", "pk": 296, "fields": {"filename": "user_1/Business_Flow.pdf", "user": 1, "uploaded": "2022-01-11T16:55:05.165", "updated": "2022-01-11T16:55:05.165"}}, {"model": "app_name.files", "pk": 297, "fields": {"filename": "user_1/Business_Flow_K1Wvyz6.pdf", "user": 1, "uploaded": "2022-01-11T17:00:26.649", "updated": "2022-01-11T17:00:26.649"}}, {"model": "app_name.files", "pk": 298, "fields": {"filename": "user_1/2021M4_RF.xls", "user": 1, "uploaded": "2022-01-11T17:01:03.644", "updated": "2022-01-11T17:01:03.644"}}] Example date (from the given example): 2022-01-11T16:49:43.897 Desired date time format: 11/01/2022 16:49 What I've tried so far: @login_required def my_view(request): response = dict() if request.method == 'GET': files = Files.objects.all().filter(user=request.user) for fhr in files: fhr.updated = fhr.updated.strftime("%d/%m/%Y %H:%M:%S") data = serialize("json", files) return HttpResponse(data, content_type="application/json") return HttpResponse('') Basically I tried to edit the queryset with the correct format strftime("%d/%m/%Y %H:%M:%S") so that when I serialize the QuerySet into JSON data data = serialize("json", files) the string (data) contains the date and time in the correct format but it did not work. So now I think that the only chance is to edit directly the string and replace those timestamps with the timestamps in the correct format. -
i just want to get single record when user passing unqid and after user passing id in input it display only that record [closed]
views.py from REMC import models from .models import addnewdata as dataall def fetchingdata(request): if 'getuid' in request.GET: getuid = request.GET['getuid'] multiple_fetch= dataall.objects.filter(unqid=getuid) print(multiple_fetch) else: data = dataall.objects.all() context = { 'data': data } return render(request, 'REMC/fetchuserwise.html', context) [description: what is wrong with this code ] model.py class addnewdata(models.Model): unqid = models.AutoField(primary_key=True) voltlevel = models.IntegerField() pssname = models.CharField(max_length=100) generatorname = models.CharField(max_length=100) turbineid = models.CharField(max_length=10) agreementtype = models.CharField(max_length=50) discomtype = models.CharField(max_length=50) validfrom = models.DateTimeField() validto = models.DateTimeField() contractname = models.CharField(max_length=50) sourcetype = models.CharField(max_length=50) capacity = models.DecimalField(max_digits=5,decimal_places=3) dateofcomm = models.DateTimeField() noofmachine = models.IntegerField() developername = models.CharField(max_length=100) fetchuserwise.html <section class="container"> <div class="container"> <div class="container border border-secondary"> <form class="requies-validation" action="/fetchuser" method="POST" novalidate> {% csrf_token %} <h4 class>Search Your Record</h4><br> <div class="container"> <input type="number" id="getuid" name="getuid" class="form-control" placeholder="Enter Unique ID"> <div class="valid-feedback">Enter your Unique ID is valid!</div> <div class="invalid-feedback">Unique ID cannot be blank!</div> </div> <div class="container"> <input type="submit" class="btn btn-primary" name="searchbyid" value="submit"> </div> </form> </div> </div> <div class="container"> <div class="form-control-sm"> <div class="row align-items-start"> <div class="col"> <h5 class="text-center">Your Records</h5> <!---h4 class="text-center"><em>Total: {{messages|length}}</em></h4---> <table class="table table-bordered table-striped table-hover"> <thead class="thead-dark"> {% for data in data %} <tr> <th scope="col">Unique ID</th> <th scope="colgroup">{{ data.unqid }}</th> </tr> <tr> <th scope="col">Voltage Level</th> <th scope="colgroup">{{ data.voltlevel }}</th> </tr> <tr> <th scope="col">Name of … -
Add manytomany field query in cet_or_create method
def create(self, validated_data): employer = User.objects.get(id=self.context.get('employer')) candidate = User.objects.get(id=self.context.get('candidate_id')) report_details_id = ReportDetails.objects.filter( id__in=self.context.get('report_details_id')) (report_candidate, created) = ReportCandidate.objects.get_or_create( reported_by=employer.id, candidate_id=candidate.id,report_details_id=report_details_id) return report_candidate Here the report_details_id is a manytomanyfield query. How will apply each of the data in it in the get_or_create method? The QuerySet value for an exact lookup must be limited to one result using slicing. I'm getting this error from the above code. Thanks in Advance. -
Django: How to download file generated by python script running in celery task after completion
I am building a Django web application, and I currently have the ability to upload a dataset (.csv file). When the 'upload' button is pressed, a celery task is started that manipulates the dataset. I want to display a page with a 'download result' button when the celery task is completed. There is currently a progress bar that displays the progress of the script using the celery-progress toolkit (it takes quite a while). I already have users built-in, if that helps. Question 1: Where should I store the output file generated by the python script running in the celery task so that the user can download it? Question 2: How do I display a page with the "download result" button when the celery task is complete? Question 3: How do I actually make this button download the file pertaining to the user's file? Here is my code so far: views.py from django.conf import settings from .models import Document from .forms import DocumentForm from django.views import View from .tasks import RunBlackLight import os from django.http import Http404, HttpResponse class RunView(View): form_class = DocumentForm initial = {'key': 'value'} template_name = 'runblacklight/progress.html' error_template_name = 'runblacklight/error.html' def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) … -
Django: How to return an inline formset with errors
I have created a form to sign up a user by having them create a User object and a UserProfile object as follows: class UserCreationForm(UserCreationForm): class Meta: model = User fields = ("email",) class UserProfileCreationForm(ModelForm): class Meta: model = UserProfile fields = ( "first_name", "last_name", ) RegisteredCustomerProfileCreationInlineFormset = inlineformset_factory( User, UserProfile, form=UserProfileCreationForm, extra=1, can_delete=False, can_order=False, ) In my view to display the sign up form, I do the following: class UserSignupView(CreateView): form_class = UserCreationForm template_name = "users/signup_form.html" def get_context_data(self, **kwargs): """Adds the inline formset to the context.""" context = super(UserSignupView, self).get_context_data(**kwargs) if self.request.POST: context[ "user_profile_inline" ] = UserProfileCreationInlineFormset( self.request.POST ) else: context[ "user_profile_inline" ] = UserProfileCreationInlineFormset() return context def form_invalid(self, request, form): # Note: I added request as an argument because I was getting an error that # says the method is expecting 2 arguments but got 3. return render(self.request, self.template_name, self.get_context_data( form=form ) ) def form_valid(self, form): context = self.get_context_data() user_profile_inline = context["user_profile_inline"] if ( form.is_valid() and user_profile_inline.is_valid() ): # Handle valid case ... else: self.form_invalid(self, form) My template is as simple as <form method="post"> {% csrf_token %} {{ form.as_p }} {{ user_profile_inline.as_p }} <button type="submit" value="Save">Sign Up</button> </form> When my form which is for creation of the User … -
geting user details in serializer djnago rest framework?
i am trying to get users details from django using rest framework. but there is error: module 'core.model' has no attribute 'Users' to do that i added this line in settings.py: REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER':'users.serializers.userSerializer' } because it is a model of django auth and in my models.py there is no model such Users it is from djnago auth model. and i dont know how to access the data from it. from rest_framework import serializers from core import models class userSerializer(serializers.ModelSerializer): class Meta: fields=( 'id', 'username') model=models.Users here is the screen shot of my django admin: [![you can see clearly Users table from djnago auth][1]][1] please help Thanks in advance<3 [1]: https://i.stack.imgur.com/EsGE8.png -
django rest frame work: model fields on Django Rest Frame write error
I have a django app with following sections models: class Report(models.Model): created_by_user=models.ForeignKey(User,on_delete=models.CASCADE) planet_name = models.CharField(max_length=100) outage_id = models.IntegerField(blank=True, default=0) unit_name = models.CharField(max_length=10, blank=True, null=True) responsible_group = models.CharField(max_length=50, blank=True) alarm_num = models.IntegerField(blank=True, default=0) raised_alarm = models.CharField(max_length=255, blank=True) start_time = models.DateTimeField(blank=True) end_time = models.DateTimeField(blank=True) event_desc = models.TextField(max_length=5000, blank=True) power_changes = models.FloatField(blank=True) rel_asset = models.CharField(max_length=255, blank=True) event_cause = models.TextField(max_length=1000, blank=True) maintenance_action = models.TextField(max_length=1000, blank=True) maintenance_cost = models.IntegerField(blank=True) maintenance_mh = models.IntegerField(blank=True) maintenance_dc = models.TextField(max_length=5000, blank=True) serializer: class ReportSerializer(serializers.ModelSerializer): created_by_user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model=Report fields='__all__' view: class ReportCreateView(APIView): def post(self,request, *args, **kwargs): received_data=ReportSerializer(data=request.data, context = {"request": request}) if received_data.is_valid(): received_data.save() return Response(received_data.data, status=status.HTTP_201_CREATED) return Response(received_data.errors,status.HTTP_400_BAD_REQUEST) but when I send a report by Post method this error rise: (1048, "Column 'start_time' cannot be null") How I can fix it?I set blank=True for all fields but why it raise errors? -
Cant send the data from the database to the client in real time without refreshing - DJANGO CHANNELS
I tried this approach stackoverflow but it didn't work consumer.py import json import asyncio from channels.consumer import AsyncConsumer from django.contrib.auth import get_user_model from channels.db import database_sync_to_async from .models import Analytics class AnalyticsConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) await self.send({ 'type': 'websocket.accept' }) analytics_obj = await self.getAnalytics() await self.send({ 'type': 'websocket.send', 'text': str(analytics_obj) }) async def websocket_receive(self, event): print('receive', event) async def websocket_disconnect(self, event): print('disconnected', event) @database_sync_to_async def getAnalytics(self): return list(Analytics.objects.all().values())[0]['number'] The console displays the message == analytics_obj but when I make changes in the database, it doesn't reflect in the console message. For that, I need to refresh the browser. What is the point in refreshing the browser when you are using WebSocket. -
Azure Virtual Machine (Ubuntu) how to deploy multiple Python websites
I am new to Python / Azure VM world. I have created Python/Django website using PyCharm IDE. Created Azure VM with Python/Django installed on Azure VM , I can run : Python manage.py runserver and i can access it using Azure URL from externally. Question: to run/deploy a python website on VM, do we have to run Python manage.py command or there is any other way ? in case I have to deploy multiple websites what i should do ? and python manage.py session also gets expired pretty soon and site is not accessible anymore , how to keep it running ? Regards Shakeel -
argument cannot be of 'NoneType' type, must be of text type in Django 3.0
When i am trying create a new cover letter i am getting this error Django = 3.0 Python = 3.7 Here is my cover_letters_list.django.html <tr> <td colspan="4"> <span class="form-tag {% if not name_form %} hidden {% endif %}"> <form class="form-inline" target="" method="POST" style="margin-top: 0px;"> {% csrf_token %} <input type="text" class="span6" name="name" value="{{name_form.name.value}}" placeholder="Cover letter name"> <button type="submit" class="btn btn-primary">Create</button> <button type="button" class="btn cancel-btn">Cancel</button> </form> </span> <span class="button-tag {% if name_form %} hidden {% endif %}"> {% trans "No data found." %} Click to <a class="new_cover" href="#"> add a new cover letter</a> </span> </td> </tr> here is my views.py class CoverLetterListView(View): def get(self, request): client = request.user.client cover_letters = CoverLetter.objects.filter(client=client, deleted=False, is_master=True) return render(request, 'quotes/covers/cover_letters_list.django.html', {'cover_letters': cover_letters}) def post(self, request): client = request.user.client name_form = forms.CoverLetterNameForm(request.POST) cover_letters = CoverLetter.objects.filter(client=client, deleted=False) if name_form.is_valid(): name_form.save_new(client=client) else: logger.warning(request, 'Invalid form') return render(request, 'quotes/covers/cover_letters_list.django.html', {'name_form': name_form, 'cover_letters': cover_letters}) here is my forms.py class CoverLetterNameForm(forms.ModelForm): class Meta: model = CoverLetter fields = ('name',) def save_new(self, client, master=True): instance = self.save(commit=False) instance.is_master = master instance.client = client return instance.save() How can i solve this error -
Should i run django commands outside a docker container or in the docker container cli
I just started dockerizing my Django apps so far all is going well but I need to know is it best practice to run the Django commands inside the container docker container exec -it con_name python manage.py startup app_name or I should just run it outside the container python manage.py startup app_name thank you -
count the null column in a row in django
I was interested to count the numbers of null culemns in a single row in django.can you please lead me on how to do it? example: model: Student fields: fname,lname, father_name Student("max",null,null) return lname and father_name or 2 -
Django fails to load javascript file but has no trouble server a css file in the same directory
I receive a Failed to load resource: the server responded with a status of 404 (Not Found) for the javascript file. The page loads fine but the javascript resource isn't obtained despite being in the same static folder as the css file which django has no trouble collecting. settings.py STATIC_URL = '/static/' BASE_DIR = os.path.dirname(os.path.dirname(__file__)) #STATIC_ROOT = os.path.abspath(os.path.join(os.path.dirname(BASE_DIR), 'static')) STATIC_ROOT = 'static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIR=[STATIC_DIR] html {% load static %} asdfs <link rel="stylesheet" type="text/css" href="{% static 'polls/styles.css' %}"> <body id='app'> <p>i'm testing again</p> <li><a href="www.google.com">google</a></li> <script type="text/javascript" src="{% static 'polls/reactfile.js' %}"></script> </body> </html> -
How to return jsonResponse for single object model filtered on Django?
I have single object filtered as below. backTest= BackTest.objects.first() I would like to return this object as jsonResponse. data = dumps(backTest) return JsonResponse(data) I got error message as below. Object of type BackTest is not JSON serializable Any advice or guidance on this would be greatly appreciated, Thanks. -
Django - Delete file associated with ImageField attribute of Model
So I have a model called User, which has an avatar field, which is just the user's avatar. I want to be able to delete the file whenever the user chooses to delete their avatar. As you can see below in my view.py I retrieve the current user object from the request(This is because I take the user uuid from the access token given to make the request then query the user object). Then I call delete on the avatar attribute, but I don't know if this actually deletes the file as well. My assumption is that it just deletes that attribute url. How do I delete the file associated with ImageField when I delete a ImageField attribute in a model? model.py class User(AbstractDatesModel): uuid = models.UUIDField(primary_key=True) username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[ MinLengthValidator(USERNAME_MIN_LEN)]) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) avatar = models.ImageField(upload_to=avatar_directory_path, blank=True, null=True) view.py @api_view(['POST', 'DELETE']) def multi_method_user_avatar(request): if request.method == 'POST': # Some POST code elif request.method == 'DELETE': try: request.user.avatar.delete() request.user.save() return Response(status=status.HTTP_204_NO_CONTENT) except Exception as e: return Response(dict(error=str(e), user_message=generic_error_user_msg), status=status.HTTP_400_BAD_REQUEST) -
Failed to load resources status: 404 javascript with django
i am running javascript frontend with django backend. Here is the structure -app --templates ---index.html --static ---index.js ---haarcascade_frontalface_alt.xml ---style.css --views.py --urls.py I can see css style in my index.html page. But the index.js file is unable to pick haarcascade_frontalface_alt.xml. The code is as follow const HAARCASCADE_URI = "haarcascade_frontalface_alt.xml" this.classifier = new cv.CascadeClassifier(); let faceCascadeFile = "haarcascade_frontalface_alt.xml"; if (!this.classifier.load(faceCascadeFile)) { await this.createFileFromUrl(faceCascadeFile, this.classifierPath); this.classifier.load(faceCascadeFile) } but it say Failed to load haarcascade_frontalface_alt.xml status: 404