Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Django + IIS) Get current LAN account
I am currently running an app locally which has a huge dependency on pulling the LAN account for the current user. I have tried... (1) getpass.getuser() which returns the server name where the site is running via IIS. (pulls LAN account locally) (2) os.getlogin() which seems to return the name of the site configured in IIS (pulls LAN account locally) Any ideas on this would be EXTREMELY helpful, as I am very stuck with where I currently am. -
I want to project data from mongodb to a website in Django via html. How can i do that?
Here is what i am doing in settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'jobs_db', 'HOST': 'localhost', 'PORT': '27017', 'username': '', 'password': '', } } in models.py from mongoengine import * connect('jobs_tbl') class jobs_tbl(models.Model): job_company = models.CharField(max_length=200,null=True) job_location = models.CharField(max_length=200,null=True) job_title = models.CharField(max_length=200,null=True) Views.py content from mongoengine import * connect('jobs_tbl') def home(request): job=jobs_tbl.objects.all() context={ 'jobs':job, } return render(request,'Jobseeker.html',context) html content <div class="container card"> <h1>Available openings</h1> <div class="card-body"> <table class="table table-hover"> <tr> <th>Name</th> <th>Position</th> <th>Description</th> </tr> {% for c in jobs %} <tr> <td>{{c.job_company}}</td> <td>{{c.job_location}}</td> <td>{{c.job_title}}</td> <td><a href="{% url 'apply' %}" class="btn btn-info btn-sm" type="submit">Apply</a></td> </tr> {% endfor %} </table> </div> </div> I'm pretty new to web development, mongodb, html. I have been trying in the net for days but couldn't find solution for this. Any help is greatly appreciated. -
How would I create a button that submits a form and downloads a pdf simultaneously
Right now my download button has two separate areas, you can click the button and it will increase the download count but not download the pdf, but if you click on the Download text it will download but not increase the download count. I want to be able to click the button and it increase the download count and download the pdf simultaneously. I cant seem to figure out how to get this working any help would be appreciated. empowerment_card.html <form action="{% url 'download_count' empowerment.pk %}" method="post"> {% csrf_token %} {% if empowerment.empowerment_pdf_slick %} <button name="empowerment_id" value="{{ empowerment.id }}" class="download-button"> <a href="/media/{{ empowerment.empowerment_pdf_slick }}" download> download </a> </button> {% endif %} </form> views.py def download_add_count(request, pk): empowerment = get_object_or_404(Empowerment, id=request.POST.get('empowerment_id')) empowerment.download.add(request.user) return HttpResponseRedirect(request.META['HTTP_REFERER']) -
Is it possible to reduce/eliminate MyPy errors for system level code with a command line option?
Running MyPy over my code, These errors seem impossible to disable with a command line option. I don't want to mark the code to be ignored so that when they do get type hints things get better. I just want to eliminate this from files in the site-packages folders, not in any of my code. from django.db import connection from django.conf import settings from django.test import TestCase, TransactionTestCase from django.utils import timezone All of these suffer from this "error" error: Skipping analyzing 'django.conf': found module but no type hints or library stubs I should be clear that I don't want to ignore the non-existence of this code, just the non-existence of the type hints. -
Django cookies not working on Minikube at .local domain
I have a web app on Django with simple authentication as follows: # in a request handler username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') The app works fine running on localhost and on real servers through HTTPS at my-app.com (no a real domain of course). Now I'm trying to make it running on Kubernetes and Minikube. I've set up a Deployment, Service, NginX-Ingress, also I specified minikube ip in my /etc/hosts file as my-app.local, and I can access it using Chrome browser, but the authentication doesn't work! Browser saves no cookies, and I always get redirected to the log in page. And I cannot find any reason: I've checked server logs and browser network traces, they look fine, I also used curl to compare authentication method results of real .com version of the app and my minikube/.local version, they are pretty same, I see correct Set-Cookie: ... everywhere, but the cookies don't get saved in the browser. What can be the cause of this problem?? -
How to update form field text to show converted time
So I have a form that uses flatpickr to let the end user select a time using the local date/time. After the enduser selects this, I want the text in the form field to show the converted UTC time. I'm not able to get this working as the date field keeps showing the local time that was initially selected, and is not updating with the UTC time. I assume its just a simple jquery typo or not using the correct id's. <div id="create-modal" class="modal {{ form.is_bound|yesno:'show,fade' }}" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="{% trans 'Close' %}"><span aria-hidden="true">×</span></button> {% trans "New Program" %} </div> <div class="modal-body"> <form id="create-form" action="{% url 'app:create' application.id %}" method="POST"> {% csrf_token %} {% next_url request %} {% bootstrap_field form.application %} <div class="form-group"> {% bootstrap_field form.title %} </div> <div class="form-group"> <!-- <span id="schedule-value-display"> --> {% bootstrap_field form.scheduled_at %} <!-- </span> --> <script type="text/javascript"> $(document).ready(function() { {% if form.is_bound %} $("#create-modal").modal("show"); {% else %} $("#create-modal").modal("hide"); {% endif %} $("#create-modal").on("hide.bs.modal", function() { $("#create-modal").addClass("fade").removeClass("show"); $("#create-form").trigger("reset"); }); var defaultDate = new Date("{% now 'c' %}"); //var $scheduleSelector = $("#schedule-selector", $form); // var $scheduleBtn = $("#schedule-btn", $form); //var $scheduleValueDisplay = $("#schedule-value-display", $form); $("#create-form #id_scheduled_at").flatpickr({ enableTime: … -
Exclude list in django cannot update
Im having a trouble where I cannot filter and update exclude items in Django. I just want to update those item exclude from my list variable but it seems it's not working. Below is everything I got for now, thanks in advance I appreciate any help and suggestions lets say for example I have list ['1', '2', '5'] and I want to update all of my data in database exclude from 1,2,5 list and update all value into "3" views.py def update(request): if request.method=="POST": product_ids=request.POST.getlist('id[]') for id in product_ids: result = Person.objects.filter(province="DATA_1",municipality="Data_2").exclude(pk = id).update(paid=3) return render(request, 'dashboard.html') -
What smtp should I use to send email to other email providers in django?
I am not able to send email verification to other email providers using django. I am currently using Gmail smtp. What EMAIL_HOST I should use to send email verification to all email providers? enter image description here -
Django Login working, but Register not working
I having the landing page that the user is presented with the when they navigate to the home page. This page have both the login form and the register form, the login for works as expected, however when I try to register a user nothing happens. I don't get any errors or warnings. views.py def login_page(request): form = CreateUserForm() context = {'form': form} if request.user.is_authenticated: return redirect('dashboard:dashboard') elif request.method == 'POST': if 'login-submit' in request.POST: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('dashboard:dashboard') else: messages.info(request, 'Username OR password is incorrect') elif 'register-submit' in request.POST: if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + user) return redirect('dashboard:login') return render(request, 'main/login.html', context) login.html <form id="register-form" action="" method="POST" role="form" style="display: none;"> {% csrf_token %} <div class="form-group"> {{form.username}} </div> <div class="form-group"> {{form.email}} </div> <div class="form-group"> {{form.password1}} </div> <div class="form-group"> {{form.password2}} </div> <div class="form-group"> <div class="row"> <div class="col-sm-6 center"> <button type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register">Register</button> </div> </div> </div> </form> forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username': forms.fields.TextInput(attrs={'class': 'form-control', … -
Make boolean values editable in list_display Wagtail?
I want to edit boolean values from the list page in Wagtail Admin. I cant seam to get this functionality working in Wagtail as its built upon Django i believe it can work on Wagtail as well but i cant figure it out. Django way of doing it: class TaskAdmin(models.ModelAdmin): list_display = (..., 'boolean_field') list_editable = ('boolean_field',) Thank you -
TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block
I have a large number of instances that I want removed from DB and ES on a daily basis. Also when I remove that instance from the ads table I want a version of it to be created in the expiredads table. For this I have a cron job that runs once a day every day at the same time. During the execution of this cron job in different places in the code begin to generate errors of the type: TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. I've been researching for weeks and haven't found a solution for this problem. As I have seen it is due to the use of transaction.atomic() but I don't know how to fix it. I'm using django 2.2.3 and python 3.7 def archive_ad(ad_id, **kwargs): """Archive an ad""" try: ad_instance = Ad.objects.get(id=ad_id) AdDocument().update(ad_instance, action="delete", raise_on_error=True) try: with transaction.atomic(): expired = ExpiredAd() fields = [field.name for field in ExpiredAd._meta.get_fields(include_parents=False) if not field.auto_created] fields.append('id') for field in fields: setattr(expired, field, getattr(ad_instance, field, None)) expired.status = AbstractAd.StatusChoices.expired expired.last_status = ad_instance.status expired.save() ad_instance.delete() except Exception as exception: AdDocument().update(ad_instance) raise exception except Ad.DoesNotExist: return -
How to optimise Images and Videos while Uploading with Django to Amazon S3?
I have a Django Project where my users can upload images/videos. I am using Amazon S3 storage for static and media files via boto to upload images and videos directly to Amazon S3. I want to optimise the image and videos both either on the fly or before uploading them. I mean if there is a static file it should be optimised and then uploaded(optimised in my django app) or optimised on fly? Which is the best way also how should I go about doing that? -
Best way to serialize a boolean representing a reverse lookup
I have some models that look like the following, where I would like to serialize Parent with a boolean field representing whether an associated Child reverse lookup exists. class Parent(models.Model): ... some fields class Child(models.Model): parent_fk = models.OneToOneField( "Parent", on_delete=models.CASCADE, related_name="child", ) ... some other fields class ParentSerializer(serializers.ModelSerializer): has_child = serializers.BooleanField() class Meta: model = Parent fields = ["has_child", ... some fields] These are the solutions I've tried and what I understand to be the problems with them just add "child" to fields - this inserts the value of the foreign key? use SerializerMethodField - triggers a DB lookup for each row? Is there a clean way to implement this feature? -
How can i perform 'row in' condition in django
I am using django, i want to implement a condition evaluating specific fields in a subquery, for instance: select a, b, c from letters where row(a,b) in( select a, b from other_letters can i do a row filter in django? -
How to have Django model fields with possibility of multiple entry/input?
I am using Django models fields and i want one of the fields with multiple entry or input. is it possible using *args? Below is my models and the "cc" fields is the one that I want to have multiple input and using def save function, but no avail. thank you in advance for possible advise. models.py: class Rtana(models.Model): rsc_name = models.CharField(max_length=128,unique=True) rsc = models.PositiveIntegerField(unique=True) cc = models.CharField(max_length=32,unique=True) def save(self,*args): super(Rtana,self).save(*args) def __str__(self): return '%s %s' % (self.rsc_name , self.rsc) def get_absolute_url(self): return reverse("app7_cbv:details",kwargs={'pk':self.pk}) -
How send message to groups on AsyncJsonWebsocketConsumer.disconnect()?
Please suggest to me a workaround on how to send message to groups on AsyncJsonWebsocketConsumer.disconnect()? class UserConsumer(AsyncJsonWebsocketConsumer): ... // some code async def disconnect(self, close_code: str) -> None: channel_layer = get_channel_layer() await channel_layer.group_send( "some_group", {"type": "send_message", "message": "some test message"}, ) This is a simple example of my code. When I do this, I've got error: File "/home/user/.pyenv/versions/3.8.6/envs/venv38/lib/python3.8/site-packages/channels_redis/core.py", line 666, in group_send await connection.zremrangebyscore( aioredis.errors.ConnectionForcedCloseError I think, disconnect() method is not the best place to send messages. If yes, what is a good place for this? Some useful links: https://channels.readthedocs.io/en/latest/topics/consumers.html?#asyncwebsocketconsumer https://aioredis.readthedocs.io/en/v1.3.0/api_reference.html#aioredis.ConnectionForcedCloseError - my error that raised by aioredis -
django project that collects data in local database installed on cloud system and sync that data in cloud database when internet is available
i want to add a feature to my django project that if the internet is not available the website will use the local database that will be installed on the client system to store data like sales, purchases, etc but as soon as internet is connected it will take all data from local database and store all that data in the cloud database (main database) deleting the data from local database. as i am new to django, i was wondering if someone can point me towards the right direction. -
django ValueError Cannot query "abcd@gmail.com": Must be "object" instance
i am trying to make an app for student but i'm getting this error, as you can see for convenient i wanted to use like that one i showed bellow but it doesn't work, should i keep using like before? or i could use like that ? what would be best way ? ValueError at /student/program_structure/ Cannot query "abcd@gmail.com": Must be "Student" instance. thank you so much :) models.py class Student(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) status = models.CharField(max_length=10, choices=STATUS, default='active') class Program(models.Model): #everything was fine when used user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) #this one #but when using this one i started getting this error from views.py user = models.ForeignKey( Student, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, unique=True) prefix = models.CharField(max_length=20) views.py class Program_structure(generic.View): def get(self, *args, **kwargs): profile = Student.objects.all() program_structure = Course.objects.filter(user=self.request.user) context = { 'test':program_structure, 'profile':profile, } return render(self.request, 'program_structure.html', context) -
How to set password for social login signup after changing email django-allauth
I am trying to come up with a solution to this problem that I am facing however, I cannot seem to find it. Assume a scenario where the user logs into the django website using their Google Gmail account. After logging in the user decided to change the default email from test@gmail.com to one of their other email at test@test.com. The user goes to accounts/emails/ and adds a new account, verifies the account set's it at primary and deletes the old email test@gmail . I have written an adapter that would link users to their social login if a user already exists so if they login using the Google account test@gamil.com they will still be redirected to the same user. However, I want to give the user a page to set a password for test@test.com in case the user wanted to use forget password option in order to sign in locally. How can I redirect users after deleting their social login email to set a new password for the new email? -
Many to many fields in widget form
I have problem with display many to many field in form widget. Category is not display in template. Title is ok (is display) but category isn't - category is empty. What can I do to display many to many fields in my template form with multiplechoice checkboxes? Why I cant display article categories in widget form? MODELS.py article model: class Article(Created, HitCountMixin): title = models.CharField(max_length=120) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) category = models.ManyToManyField(ArticleCategory, related_name='articles') category model: class ArticleCategory(Created): category_name = models.CharField(max_length=128) slug = models.SlugField(null=False, unique=False) VIEWS: class UpdateArticleView(LoginRequiredMixin, UpdateView): template_name = 'news/update_article.html' form_class = EditArticleForm model = Article def get_success_url(self): pk = self.kwargs["pk"] slug = self.kwargs['slug'] return reverse_lazy("news:article_detail", kwargs={'pk': pk, 'slug': slug}) FORMS.py class AddArticleForm(forms.ModelForm): title = forms.CharField( label="Tytuł", max_length=120, help_text="Tytuł newsa", widget=forms.TextInput(attrs={"class": "form-control form-control-lg pr-5 shadow p-1 mb-1 bg-white rounded"}), required=True, ) category = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, ) And in my HTML TEMPLATE: <form method="post" enctype='multipart/form-data'> {% csrf_token %} {{ form.media }} {# {% crispy form %}#} {{ form|crispy }} <button type="submit" class="btn btn-outline-primary">EDYTUJ NEWS</button> </form> -
Django model filefield -> upload file from one server to another
I am trying to upload the content of FileField field to 3rd party server but i am getting empty binary at 3rd party server end. Suppose i have FileManager table which has file as a coloumn Model schema: class FileManager(models.Model): file = models.FileField(upload_to=file_input_path) .... Now suppose i have this below function which is getting some particular row from file_manager table and uploading that particular file to some 3rd party service as: def some_task(): some_file = FileManager.objects.get(id=some_id) some_file.file.name = "Some Random custom name" form_data = { "file": some_file.file, } print(form_data['file'].read()) # it is printing empty binary b'' requests.post("xyz.com/process_file", files=form_data) #3rd party service class def process_file(request): data = request.FILES['file'] print(data.read()) #Getting empty binary as-> b'' print(data.name) #printing correct name -> some_file.xlsx How can i access the content of FileField field? Currently i am using FileField.file to access this but while reading its content, it shows empty binary b'' -
How to use async await to get the https response from the request.post in django views?
I have built the project with Django and React. the part of one of API view is looking like follows: data = {"userId": str(email), "answers1": answers1, "answers2": answers2, "words": words} # To get the score from the api using the prepared data score = requests.post(api_url, headers=headers, data=json.dumps(data)) res = [] for s in score: mid = s.decode('utf-8') res.append(json.loads(mid)) result = AnalysisResult.objects.get(user=user) result.w_1 = res[0]['graphA']['W'] result.x_1 = res[0]['graphA']['X'] result.y_1 = res[0]['graphA']['Y'] result.z_1 = res[0]['graphA']['Z'] result.w_2 = res[0]['graphB']['W'] result.x_2 = res[0]['graphB']['X'] result.y_2 = res[0]['graphB']['Y'] result.z_2 = res[0]['graphB']['Z'] result.save() return Response({"message": "The result score is stored in database successfully!"}) Here w_1, w_2, ... are the columns of table in the database. In this view, there is a https request(api_url and headers are defined in my code, and they are all correct). I want to return the response of this view just after get the score from the api, and save it in the table. If this description is not enough, please let me know. I will add more information. -
[DRF]: extra field in serializer with related id
I've been trying hard but I can't find a solution for this, maybe you can help me: I have 2 models: consumption and message. The messages have a field "consumption" so I can know the consumption related. Now I'm using DRF to get all the consumptions but I need all the messages related with them This is my serializers.py file: class ConsumptionSapSerializer(serializers.HyperlinkedModelSerializer): client = ClientSerializer(many=False, read_only=True, allow_null=True) call = CallSerializer(many=False, read_only=True, allow_null=True) course = CourseSerializer(many=False, read_only=True, allow_null=True) provider = ProviderSerializer(many=False, read_only=True, allow_null=True) # messages = this is where I failed class Meta: model = Consumption fields = [ "id", "client", "course", "provider", "user_code", "user_name", "access_date", "call", "speciality_code", "expedient", "action_number", "group_number", "start_date", "end_date", "billable", "added_time", "next_month", "status", "incidented", "messages" ] class MessageSapSerializer(serializers.ModelSerializer): user = UserSerializer(allow_null=True) class Meta: model = Message fields = [ "user", "date", "content", "read", "deleted" ] I have read here Django REST Framework: adding additional field to ModelSerializer that I can make a method but I don't have the consumption ID to get all the messages related. Any clue? -
Use same template with different data on links created in another template
I am facing problem using urls created in the for loop of template file(URL patching). The views file consist of following functions def home(request): data = request.FILES['file'] # i got the data request.session['data'] = data # able to store data so that i can manipulate data ''' data is dictionary suppose data ={'a': [2,3,4], 'b':[4,3,2], 'c':['6,7,3]} ''' members = data.items() return render(request, 'home.html', {'members': members}) to plot data extracted from the sessions data another def plot_graph(request): data = request.session['data'] selected_data = data['a'] # suppose i click on link 'a' link return render(request, 'graph.html', {'selected_data': selected_data}) plotting data with chartjs so that template is graph.html (Its working fine for me) var myLineChart = new Chart(ctx, { type: 'line', data: selected_data, options: options }); home.html {% for member in members %} <tr> <td><a href="{% url "my_app:plot_graph"%}">{{member}}</a></td> </tr> {% endfor %} my_app/urls.py urlpatterns = [ path('', views.home, name='GroupChat'), path('<str:name>/', views.plot_graph, name='plot_graph') ] Here i am missing how to map urls from plot_graph to url patterns, I tried different sources to solve this but none of them helped me, in short my problem is to create links('a', 'b', 'c'..) if you click any link that should display in new page with data associated with … -
IntegrityError when creating a new model object
I'm getting the error: IntegrityError at evaluation/evaluee/new Null value in column "Evaluation_data_id" violates not-null constraint I think it has to do with the way I set up the relationship with the two models. The ideia is: every time one EvaluationModel is created, an EvaluatorModel object should be created too (getting some values such as evaluee and evaluator) from the first model. I created an evaluation_data field so that I could access EvaluationModel Thanks in advance! My model: class EvaluationModel(models.Model): evaluee = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name= '+', verbose_name='Evaluee', ) evaluator = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name= '+', verbose_name='Evaluator', ) dgl = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name= '+', verbose_name='DGL', ) promotion_window = models.BooleanField(default=False, verbose_name = "") currentrole = models.CharField(max_length=50, choices=ROLES, default=None, null = True, blank = True, verbose_name="") promotionrole = models.CharField(max_length=50, choices=ROLES, default=None, null = True, blank = True, verbose_name="") tenure = models.CharField(max_length=50, default=None, null = True, blank = True, verbose_name="Tenure") adjustedtenure = models.CharField(max_length=50, default=None, null = True, blank = True, verbose_name="") pinputlimitdate = models.DateField(null = True, blank = True, verbose_name='', help_text="Format: <em>MM/DD/YYYY</em>.") exposurelistlimdate = models.DateField(null = True, blank = True, verbose_name='', help_text="Format: <em>MM/DD/YYYY</em>.") evaluatorlimitdate = models.DateField(null = True, blank = True, verbose_name='', help_text="Format: <em>MM/DD/YYYY</em>.") shared_with_PM = models.BooleanField("", default=False) shared_with_DGL = models.BooleanField(default=False) shared_with_Evaluator = …