Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter queryset against time in django with custom timezone?
I know the question seems stupid, but for some reason I am not able to understand why my django app does not return the correct filtering results when I change my TIME_ZONE = 'UTC' to 'TIME_ZONE = 'Asia/Kolkata''. Everything else is working just fine, but when I change the timezone to my local timezone, it does not give any error, but the function in views.py also gives 0 matching results. This question is also related to this question. This is my function in views.py importing the data in the Itembatch model: @method_decorator([login_required, teacher_required], name='dispatch') class UploadedItems(ListView): model = ItemBatch ordering = ('name',) context_object_name = 'quizzes' template_name = 'classroom/teachers/item_list.html' def get_queryset (self): # queryset = self.request.user.uploaded_by print("----------------" + str(ItemBatch.objects.latest('time'))) return ItemBatch.objects.filter(uploaded_by=self.request.user) And this is the model: # item upload class ItemBatch(models.Model): # uploaded_by = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='uploaded_by') ttypes =(('Open','Open'),('Container','Container'),('Trailer','Trailer'),('All','All')) uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='uploaded_by') name = models.CharField(max_length=30) pid = models.CharField(max_length=30) quantity = models.CharField(max_length=30) length = models.CharField(max_length=100, blank=True) width = models.CharField(max_length=100, blank=True) height = models.CharField(max_length=100, blank=True) volume = models.CharField(max_length=100, blank=True) weight = models.CharField(max_length=100, blank=True) truck_type = models.CharField(max_length=255,default=0, choices=ttypes) origin = models.CharField(max_length=100, blank=True) destination = models.CharField(max_length=100, blank=True) time = models.DateTimeField(max_length=100, blank=True,default=now) def __str__ (self): return self.name This is my models database: -
The result was empty after raw SQL queries in django but right with same sql in mysql db?
I'm using Django's raw query like below: And the generated sql like below : # exe_ret = SmbFbCampaignStatDaily.objects.raw('''sql'') # print(exe_ret) sql: SELECT async.id AS id, ... async.name AS NAME, async.status AS STATUS, async.daily_budget AS daily_budget, statistic.spend AS spend, statistic.clicks AS clicks, statistic.impressions AS impressions, statistic.spend AS spend, ... FROM `smb_fb_campaign_async` async LEFT JOIN (SELECT fb_campaign_id, SUM(impressions) AS impressions, SUM(clicks) AS clicks, ... FROM `smb_fb_campaign_stat_daily` WHERE dt BETWEEN "2019-04-29" AND "2019-04-29" GROUP BY fb_campaign_id) statistic ON statistic.fb_campaign_id = async.fb_campaign_id WHERE async.fb_account_id = "113743809520028" AND (async.fb_campaign_id LIKE '%%' OR async.name LIKE "%%") ORDER BY id asc I can got the right result using the genrated sql in mysql db, but the rawQueryset was always empty. print(len(exe_ret )) # 0 How can I make it work correctly? Any commentary is very welcome. great thanks. -
How to add a non_form_errors to a formset in Django?
Hi in my project I need to find a way to add a non_form_error to the formset I am using. I can't use the clean function of this formset because I need to pass cleaned values from other forms. I check first that all my forms and formset are valid, and then I try to do the following in my view: error = ValidationError(_("The total amount of tranches doesn't match the loan amount"),code='tranche_total_amount') tranche_formset._non_form_errors.append(error) print(tranche_formset.non_form_errors()) #then I render all my forms again return self.render_to_response( self.get_context_data( form = form, ... #other forms here, tranches = tranche_formset, ) ) In the terminal I can see that the error is displayed correctly: <ul class="errorlist"><li>The total amount of tranches doesn&#39;t match the loan amount</li></ul> But in my template the errors are not shown: {% if tranches.non_form_errors%} <div class="alert alert-danger mt-2" role="alert"> {{ tranches.non_form_errors}} </div> {% endif %} -
How to use the uploaded filename in another python script in Django
In my Django "sources" project I have the "bulletins" app. I have a view "model_form_upload" inside of which I get the uploaded file name ("csvFilename") when I upload it. views.py from bulletins.forms import ErnageForm from bulletins.models import ErnageModel from bulletins.pretreatment import pretreatment def model_form_upload(request): if request.method == 'POST': form = ErnageForm(request.POST, request.FILES) if form.is_valid(): form.save() for filename, file in request.FILES.items(): csvFilename = file.name resultPretreatment = pretreatment() print(resultPretreatment) return redirect('proceed_FT') else: return redirect('upload_fail') else: form = ErnageForm() return render(request, 'bulletins/upload_csv.html', {'form': form}) Beside that, I have a python script "pretreatment.py" that effectuates a bunch of pandas-dataframe transformations on my csv file. pretreatment.py def pretreatment(csvFileToTreat="..." #... all the transformations with pandas dataframes... df.to_csv(txtExportFilePath, index=False, header=None, sep='\t') My csvFilename will always be a string of this type : "Ernageyyyymm.csv". My question here is : How can I collect my csvFilename variable out of the views.model_form_upload function to use its date information it in the pretreatment python script variables "csvFileToTreat" and "txtExportFilePath". Those two ones are of the type "path/Ernage{0}{1}.format(yearToTreat,monthToTreat). I hope all this is as clear as possible, thank you for your help. -
The changes in Javascript do not work on elasticbeanstalk (aws) but it works on local (localhost)?
part of code inside js that doesn't work document.getElementById("partinfo").innerHTML = part.fields.name; -
Django AppConfig::ready cannot use module which impoorts models
I wish to run an initialisation function when my django app is loaded, using the AppConfig::ready method. However, the functionality I wish to run needs to use django models, and you can't import this module at the point that apps.py is imported, because the models aren't fully loaded at this time. How can I get around this limitation? from django.apps import AppConfig from . import populate_db from . import server_settings class ServerConfig(AppConfig): name = 'server' def ready(self): populate_db.populate_db(server_settings.opt.data_root) Produces there errors: File "/home/ian/dev/obd/django_site/server/apps.py", line 2, in <module> from . import populate_db File "/home/ian/dev/obd/django_site/server/populate_db.py", line 16, in <module> import server.models as models File "/home/ian/dev/obd/django_site/server/models.py", line 6, in <module> class Scan(models.Model): File "/home/ian/.local/lib/python3.6/site-packages/django/db/models/base.py", line 87, in __new__ app_config = apps.get_containing_app_config(module) File "/home/ian/.local/lib/python3.6/site-packages/django/apps/registry.py", line 249, in get_containing_app_config self.check_apps_ready() File "/home/ian/.local/lib/python3.6/site-packages/django/apps/registry.py", line 132, in check_apps_ready raise AppfunctionRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Django: How to login a user who have some special permission
I am new to Django. I am working on a project where I want to login a manager. Manager is not a admin or superuser here but a manager have some permission which is given by admin from back end. I want that if a user/manager have a specific permission then it will render a different page. I have done it for admin but i have no idea how can i do it for a user who have some permission. Any help will be appreciated. This is my views.py for authentication of user and admin. def login(request): if request.method =='POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) # return redirect('index') if user.is_superuser: return redirect('manager') else: return redirect ('index') else: messages.error(request, 'Invalid Credentials') return redirect('login') else: return render(request, 'vadash/sign-in.html') how can i authenticate a user/ manager who have some special permission. -
Django auto update the column to inactive when current datetime greater than stored column datetime
I have stored expired datetime of an account in during insert, I should update the account as "Inactive" when the current time is greater than stored expired datetime automatically. -
server taking too much time to serve static files
In my django project, I am using django=1.8, ngix, uwsgi, postgresql my project is deployed in a live server which os is ubuntu 16.04 when I am requesting the home page, then here is the scenario of the times taking to serve static files as mentioned below. static files taking too much time to be served. But if I request individual static file from browser, then it takes a few milliseconds. my site is very slow and the circle on browser tab is moving for long time to response. Please help me, what can i do... -
What is parameters in hosting a website with payment gateway
Payment gateway support team ask me to tell them what parameters I'm using at my end ...but i don't understood which type of parameters they ask about -
Https does not work. Ubuntu 16+, DigitalOcean
I am trying to add my SSL certificate to my django application according to this tutorial. I have done all the steps, my certificates are visible in the folder but I still can not use https to load my site. IMPORTANT NOTES: - Unable to install the certificate - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/ebluedesign.online/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/ebluedesign.online/privkey.pem Your cert will expire on 2019-07-29. To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the "certonly" option. To non-interactively renew *all* of your certificates, run "certbot renew" How can I solve this problem with SSL certificate. Or how can I get more information, why does not it work? Any help will be appreciated. -
Django: filter returns empty result
I have the following table in my database : workspace_role_id | workspace_role_name --------------------------------------+--------------------- 3f76103f-732a-435a-a88f-737f4a6f1b87 | Owner c73b7c35-237e-4e13-8269-b259c2858b71 | Admin a61890fc-1c29-4817-8687-30786a5db17a | User built from this Django model: class WorkspaceRole(models.Model): class Meta: ordering = ("workspace_role_name",) workspace_role_id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True, editable=False) workspace_role_name = models.CharField(max_length=64, unique=True) def __repr__(self): return f"<{self.__class__.__name__}: {self.workspace_role_name}>" And I want to retrieve the workspace_role_name from the ID. However, the result of WorkspaceRole.objects.filter(workspace_role_id="a61890fc-1c29-4817-8687-30786a5db17a") is an empty queryset <QuerySet []>, but when I run WorkspaceRole.objects.all() I get the correct output: <QuerySet [<WorkspaceRole: Admin>, <WorkspaceRole: Owner>, <WorkspaceRole: User>]> What am I doing wrong with my filter? -
Testing if user is not login, redirect to login page
Just testing if my application will redirect to the login page if the user is not logged in. The url /confirmation/TEST01 where TEST01 is a reverse url. It should redirect to /accounts/login/?next=/confirmation/TEST01 But I am getting an error: AssertionError: 404 != 302 : Response didn't redirect as expected: Response code was 404 (expected 302) Test.py def test_redirect_to_login(self): response = self.client.get('/confirmation/TEST01/') self.assertRedirects(response, '/accounts/login/?next=/confirmation/TEST01', status_code=302, target_status_code=404, fetch_redirect_response=True) Terminal [30/Apr/2019 08:45:01] "GET /confirmation/XZC456 HTTP/1.1" 302 0 Not Found: /accounts/login/ [30/Apr/2019 08:45:01] "GET /accounts/login/?next=/confirmation/XZC456 HTTP/1.1" 404 2386 -
how does django `makemigrations` work under the hood?
My question is: what does calling manage makemigrations actually do? I know it creates migration files, but how? How does it keep track of what changed since last migration? Does it directly compare the current status of the models to the database? Does it keep some hidden files describing the previous status? Which part of the framework code does it call? The documentation says nothing on the subject. -
How can I change a column's structure in a simple table with data fields into interactive voting?
I have the following simple table in my django project which is shown to users who visit a specific page: In the html page that contains this table, my code looks like this: <table id="my-table" class="table simple"> <thead> <th data-field="record" data-sortable="false">Record</th> <th data-field="names" data-sortable="false">Name</th> </thead> <tbody id="top_body" style="direction: rtl;"></tbody> </table> As you can see I have used data fields for each column, which later using an ajax request (which performs some codes through a url connected to a views.py file) brings up the data you see in the above image; some routine and simple python, django stuff. As follows: function ajax_request(record, name, csrftoken){ $.ajax({url: "/peopleinfo/load_info_table/", dataType: "json", type: "POST", data: {'csrfmiddlewaretoken': csrftoken, 'personrecord':record, 'personname':name, }, success: function(data){ person_dict = data.persons; personsinfo = [] $.each(person_dict, function( index, person ) { var person_dict = {'record':person.record, 'names':person.name}; personsinfo.push(person_dict) }); Now what I want to do is adding another column which allows the users who visit the page, vote-up or vote-down for each person. Like this: I have defined the models.py stuff and everything is ready. I am just stuck with html and don't know how to add this column which has a different structure (with two buttons in it and a number field … -
django_channels "Reader at end of file" exception
I have implemented django_channels AsyncJsonWebsocketConsumer consumer which subscribes to "chat" group: from channels.generic.websocket import AsyncJsonWebsocketConsumer class CeleryTaskConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.channel_layer.group_add(group='chat', channel=self.channel_name) async def new_message_handler(self, event): await self.send_json(content={'event': event}) Then I regularly send a message to a "chat" group: import channels.layers from asgiref.sync import async_to_sync def send_notification(): channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)("chat", { 'type': 'new.message.handler', 'message': 'Hello world!' }) Everything works as expected, however I regularly get this exception: Exception inside application: Reader at end of file File "/usr/lib64/python3.6/asyncio/coroutines.py", line 129, in throw return self.gen.throw(type, value, traceback) File "/venv/lib64/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/usr/lib64/python3.6/asyncio/coroutines.py", line 129, in throw return self.gen.throw(type, value, traceback) File "/venv/lib64/python3.6/site-packages/channels/utils.py", line 59, in await_many_dispatch await task File "/venv/lib64/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch result = task.result() File "/usr/lib64/python3.6/asyncio/coroutines.py", line 126, in send return self.gen.send(value) File "/venv/lib64/python3.6/site-packages/channels_redis/core.py", line 429, in receive real_channel File "/usr/lib64/python3.6/asyncio/coroutines.py", line 110, in __next__ return self.gen.send(None) File "/venv/lib64/python3.6/site-packages/channels_redis/core.py", line 484, in receive_single index, channel_key, timeout=self.brpop_timeout File "/usr/lib64/python3.6/asyncio/coroutines.py", line 110, in __next__ return self.gen.send(None) File "/venv/lib64/python3.6/site-packages/channels_redis/core.py", line 327, in _brpop_with_clean await connection.eval(cleanup_script, keys=[], args=[channel, backup_queue]) File "/venv/lib64/python3.6/site-packages/aioredis/commands/scripting.py", line 12, in eval return self.execute(b'EVAL', script, len(keys), *(keys + args)) File "/venv/lib64/python3.6/site-packages/aioredis/commands/__init__.py", line 51, in execute return self._pool_or_conn.execute(command, *args, **kwargs) File … -
unable to send email to other user emails account in django
i previously i was using gmail smtp to send mail but now i created new account in sendgrid and im using free plan in my django project this my complete setting about send grid EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey' EMAIL_HOST_PASSWORD = 'SG.cn5r80oYR9q-absma6OLpQ.9lG0dXM3IFiUV4LfxTdKtQ8pGG0XgPxxxxxx' # this is API key EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' is any other settings required i am testing email using rest auth lib http://127.0.0.1:8000/rest-auth/password/reset/ is show msg like success": "Password reset e-mail has been sent." but recipient not received any mails but in sendgrid dashboard it is showing 9 or 10 etc msg delivered -
Convert base64 string to png image with python
I'm working on a Django application where the user can trigger the webcam with javascript and snap a picture. This picture is stored in a canvas. I want to retrieve this image with python as a base64 string, convert that into a png file and save it into the Django server. This is my code so far HTML Template <center> <button type="button" name="button" class='btn btn-outline-dark btn-lg' id='start'>Start Video Capture</button> <div class="container-fluid mt-2"> <video id="video" width="640" height="480" autoplay></video><br> <button type="button" data-toggle="modal" data-target="#image_model" class="btn btn-lg btn-dark" id="snap">Snap Photo</button> </div> </center> <center> <canvas id="canvas" width="640" height="480"></canvas> </center> <button type="button" class="btn btn-secondary" data-dismiss="modal">Retake</button> <form class="image_to_server" action="{% url 'img_submit' %}" method="post"> {% csrf_token %} <input type="text" name="base64Field" value="" id='base64'> <input type="submit" value="Use Image" class="btn btn-primary" id="use_image"> </form> Javascript Code // Grab elements, create settings, etc. var video = document.getElementById('video'); // Elements for taking the snapshot var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); $('#start').click(function() { // Get access to the camera! if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) { //video.src = window.URL.createObjectURL(stream); video.srcObject = stream; video.play(); }); } $('#snap').fadeIn(); // Trigger photo take $('#snap').click(function() { context.drawImage(video, 0, 0, 640, 480); var dataURL = canvas.toDataURL(); $('#base64').val(dataURL) $("#use_image").click(function() { console.log('clicked'); }); }); }); Django views.py … -
djano field datetime set auto_now_add = true but mysql error field has no default value
I have this field in my model: created_at = models.DateTimeField(auto_now_add=True) but when I try to save data to mysql with this command: INSERT INTO unprocessed(provider_id, record, type ) VALUES (1, 1, 1); this error appear: ERROR 1364 (HY000): Field 'created_at' doesn't have a default value I searched the INTERNET but i couldn't find a way to solve it -
Django Admin: list_display() order by count of related object
Imagine you have a model Person which can have N Book instances. I want to display the number of books a person has in the django admin change-list view. It is easy to display the number (write a custom method on PersonAdmin). But I could not find a way to make it sortable by the number of books a person has. I read the docs for list_display, but could not find an answer. According to the docs a query expression could be used. Is it possible to solve it this way? -
XML ParseError: junk after document element: line 1, column 11 in custom validator (Wagtail)
I'm getting an error in validator when adding '\n' character in wagtail admin into RichTextField and publishing the page. An error occurs here plain_text = ''.join(fromstring(value).itertext()) class ProhibitBlankRichTextValidator: """ Validate that the incoming html-string contains plain text characters. Common usage: Proper RichTextField validation Reason: Handling improper RichTextField validation by Wagtail 2.1: https://github.com/wagtail/wagtail/issues/4549 """ message = "This field is required." def __init__(self, message=None): if message is not None: self.message = message def __call__(self, value): plain_text = ''.join(fromstring(value).itertext()) # Escape html tags if not plain_text: raise ValidationError(self.message) -
FileNotFoundError: [Errno 2] No such file or directory: '/Users/dir/portfolio/portfolio/app/static'
Static files were working correctly last night. I did nothing then when I worked on it today, the css file won't load anymore. I have the {% load static %} on base.html When I run manage.py collectstatic, this is the error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/dir/portfolio/folio_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/dir/portfolio/folio_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/dir/portfolio/folio_env/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/dir/portfolio/folio_env/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/dir/portfolio/folio_env/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/Users/dir/portfolio/folio_env/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect for path, storage in finder.list(self.ignore_patterns): File "/Users/dir/portfolio/folio_env/lib/python3.7/site-packages/django/contrib/staticfiles/finders.py", line 131, in list for path in utils.get_files(storage, ignore_patterns): File "/Users/dir/portfolio/folio_env/lib/python3.7/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/Users/dir/portfolio/folio_env/lib/python3.7/site-packages/django/core/files/storage.py", line 315, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/Users/dir/portfolio/portfolio/app/static' -
Is there a way to get remote users' distribution name
I am running a django server.I want to get remote users' distribution name. Like that; >>> import platform >>> print(platform.dist()) ('centos', '6.0', 'Final') is it possible. -
How to send Email with html page in Django?
I'm new in Django ! I don't know how to send email in Django. I refer Django documentation but it didn't help me . I need to send email with html page to different users .In models.py i have two values Name and Email. When i click button ,the html page should be send to appropriate user's Email -
How to latest objects created in django models by similar field value?
I have created an app here people can upload 'csv' files of their items details to the server, and then perform various opertaions upon it. But, because every item has it's own unique ID, whenever a csv is uploaded, there is no way to figure out which item-batch was uploaded last. Upload function This is my function in views.py importing the data in the Itembatch model: @method_decorator([login_required, teacher_required], name='dispatch') class UploadedItems(ListView): model = ItemBatch ordering = ('name',) context_object_name = 'quizzes' template_name = 'classroom/teachers/item_list.html' def get_queryset (self): # queryset = self.request.user.uploaded_by print("----------------" + str(ItemBatch.objects.latest('time'))) return ItemBatch.objects.filter(uploaded_by=self.request.user) And this is the model: # item upload class ItemBatch(models.Model): # uploaded_by = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='uploaded_by') ttypes =(('Open','Open'),('Container','Container'),('Trailer','Trailer'),('All','All')) uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='uploaded_by') name = models.CharField(max_length=30) pid = models.CharField(max_length=30) quantity = models.CharField(max_length=30) length = models.CharField(max_length=100, blank=True) width = models.CharField(max_length=100, blank=True) height = models.CharField(max_length=100, blank=True) volume = models.CharField(max_length=100, blank=True) weight = models.CharField(max_length=100, blank=True) truck_type = models.CharField(max_length=255,default=0, choices=ttypes) origin = models.CharField(max_length=100, blank=True) destination = models.CharField(max_length=100, blank=True) time = models.DateTimeField(max_length=100, blank=True,default=now) def __str__ (self): return self.name What I tried As you can see, print("----------------" + str(ItemBatch.objects.latest('time'))) prints only the latest item and not the whole batch which I need. I need a queryset with all the items which …