Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Difficult Django: Is it really impossible to redirect to a url without using test_func() if don't meet a certain criteria? (urgent)
I want to make it such that if the user has blocked me or if I have blocked the user, I want to redirect them back to the homepage and not allow them to view the detail page. Because this is a class based view, do you have any ways for me to achieve what I want and not affecting what already exists? I tried to do all sorts of things but didn't work, and none of my friends could solve this. I cannot directly use return redirect(HomeFeed:main) because I have other contexts in the same view which I need it to return in the template. I also do not want to use UserMixin's test_funct() which involves showing a 403 Forbidden Error because it isn’t user friendly and doesn’t show the user what exactly is happening. That’s why I want to do a redirect followed by django messages to inform them why they can’t view the page class DetailBlogPostView(BlogPostMixin,DetailView): template_name = 'HomeFeed/detail_blog.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_post=self.get_object() blog_post.save() context['blog_post'] = blog_post account = Account.objects.all() context['account'] = account if blog_post.interest_set.exists(): context["interest_pk"]=blog_post.interest_set.first().pk if blog_post.author in self.request.user.blocked_users.all(): messages.warning(self.request, 'You cannot view post of ideas authors that you have blocked.', extra_tags='blockedposts') hi … -
How to fix problems converting string to datetime with Python / Django?
I have the following two imports: from datetime import datetime, timedelta import datetime as dt If I try date = dt.datetime.strptime(data['Time'][i],"%Y-%m-%d").date() I get the following error: AttributeError: 'datetime.date' object has no attribute 'endswith' If I try date = dt.strptime(data['Time'][i],"%Y-%m-%d").date() I get the following error: AttributeError: module 'datetime' has no attribute 'strptime' I am using Python 3.8.3 with Django 3 - why is it behaving like this and how can I fix this? -
How to have one mandatory and two optional positional arguments?
I need to run a python file as follows python runnning_program.py argument1 [argument2] [argument3] def main(argument1,argument2 = default2, argument3 = default2): code if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument("argument1") kwargs = vars(ap.parse_args()) main(**kwargs) How to add argument2 and argument3 as optional positional arguments? -
Prevent Django model field from being rendered
I'm adding a per-user secret key to one of my Django models for internal usage, but I want to make sure that it is not accidentally exposed to the user. Obviously, I can check all the forms using that model today and ensure that they exclude the field, but that is not future proof. Is there any way I can mark a field so it is never rendered or sent to the client even if a form otherwise includes it? -
Send image to server through js fetch
I am changing my form submission to make it more fluid via using fetch. In order to process the value of my input image: <input name="perfil" type='file' id="imageUpload /> And then, in order to upload it to Amazon S3, I do this in my views.py: if request.method == "POST" image = request.FILES['perfil'] im = Image.open(image) output = BytesIO() rgb_im = im.convert('RGB') rgb_im.save(output, format='JPEG', quality=90) output.seek(0) s3.Bucket('bucketname').upload_fileobj(output, request.user.email + '.profileImage') But now (because i'm trying to implement fetch), I am getting the image file like this: fetch(`url`, { method: 'POST', body: JSON.stringify({ image: document.querySelector('#imageUpload').files[0], }), headers: { "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) } The problem is that when I do request.body['image`] in the server (views.py), all I'm getting is this: "image":{} And I don't know how to process this file in JS before I send it to the server (that will end up uploading it to amazon s3) -
Django raising a TemplateDoesNotExist at /web/edit/
The HTTP is giving me the ModuleNotFoundError whichever link I go. The ModuleNotFoundError is giving me the following information: ModuleNotFoundError at /url/ No module named 'django.core.context_processors' Request Method: GET Request URL: http://127.0.0.1:8000/web/ Django Version: 3.1.5 Exception Type: ModuleNotFoundError Exception Value: No module named 'django.core.context_processors' Exception Location: <frozen importlib._bootstrap>, line 984, in _find_and_load_unlocked Python Executable: /Users/william/Documents/coding/WDTP/wfw_fixed/env/bin/python3 Python Version: 3.9.0 Python Path: ['/Users/william/Documents/coding/WDTP/wfw_fixed/wfw', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/william/Documents/coding/WDTP/wfw_fixed/env/lib/python3.9/site-packages'] Server time: Sat, 23 Jan 2021 00:07:14 +0000 -
Derived field upon model creation - Django models
I have those 3 Django models. class Order(models.Model): materials = models.ManyToManyField(Material, through='OrderMaterial') class Material(models.Model): description = models.CharField(max_length=150) unit_price = models.FloatField() class OrderMaterial(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) material = models.ForeignKey(Material, on_delete=models.CASCADE) legacy_unit_price = models.FloatField() amount = models.IntegerField() total_price = models.FloatField() I need to calculate the total for the OrderMaterial object is literally material.unit_price * amount the problem is that the unit_price can't change in the OrderMaterial if the price in Material changes. So I created a legacy_unit_price that will hold the old price of the material no matter what. How can I store the material.price inside legacy_unit_price only when CREATING the object? -
TypeError at /cart/ cannot unpack non-iterable Cart object
I am developing an eCommerce app in Django. I am still developing locally. As I try to access to http://127.0.0.1:8000/cart/ I get the error: TypeError at /cart/ cannot unpack non-iterable Cart object in cart_home cart_obj, new_obj = Cart.objects.new_or_get(request) TypeError: cannot unpack non-iterable Cart object variable value request <WSGIRequest: GET '/cart/'> and I can't understand what is wrong. Here is my models.py: from django.db import models from django.conf import settings from products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1 : new_obj = False print('Cart ID exists') cart_obj=qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id']=cart_obj.id else: print('Cart ID does not exists') return cart_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated: user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) timestamp = models.DateTimeField(auto_now=True) updated = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) Here is my views.py: from .models import Cart def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) products = cart_obj.products.all() total = 0 for x in products: total += … -
How to build a Voice based Email Web System for Blind
I want to build a Voice based Email Web System for Blind in Django but I face a problem. When I call a text to speech function for voice commands and open localhost Website loads after tts execution. I want that text to speech only works when website fully loaded. Also I want to know how to put data in Django form Fields by using voice (speech to Text) Please as soon as possible I need to know about how things done. Thanks -
Django - redis TLS encryption not working
actually I wanted to implement TLS encryption to connect my django application with redis but im failing with the following error (using without TLS work like a charm): app | raise ConnectionError("Error while reading from socket: %s" % app | redis.exceptions.ConnectionError: Error while reading from socket: (104, 'Connection reset by peer') my settingy.py: CACHES = { 'default': { 'BACKEND': 'django_prometheus.cache.backends.redis.RedisCache', 'LOCATION': [ 'rediss://' + ':' + env.str('REDIS_PWD') + '@' + env.str('REDIS_HOST') + ':' + env.str('REDIS_PORT') + '/' + env.str('REDIS_CACHE_DB') ], 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'SOCKET_CONNECT_TIMEOUT': 30, # seconds 'SOCKET_TIMEOUT': 30, # seconds 'COMPRESSOR': 'django_redis.compressors.zlib.ZlibCompressor', 'CONNECTION_POOL_KWARGS': {'max_connections': env.int('REDIS_MAX_CONN'), 'retry_on_timeout': True, 'ssl_ca_certs': '/etc/ssl/CAcert.pem' }, 'REDIS_CLIENT_KWARGS': {'skip_full_coverage_check': True, 'ssl': True, 'ssl_cert_reqs': None } } } } This is how I start redis using docker: redis: image: redis:alpine command: > --requirepass ${REDIS_PWD} --protected-mode no --logfile "/var/log/redis-server.log" --loglevel "verbose" --tls-ca-cert-file /etc/ssl/CAcert.pem --tls-key-file /etc/ssl/redis.key --tls-cert-file /etc/ssl/redis.crt --tls-dh-params-file /etc/ssl/dhparams.pem --port 0 --tls-port 6379 --tls-auth-clients yes --tls-protocols "TLSv1.2 TLSv1.3" container_name: ${REDIS_HOST} hostname: ${REDIS_HOST} networks: - backend ports: - ${REDIS_PORT} labels: - traefik.enable=false volumes: - ./hard_secrets/ssl/redis:/etc/ssl - ./runtimedata/log/redis:/var/log The redis log is showing the following: 1:C 22 Jan 2021 23:15:23.486 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo 1:C 22 Jan 2021 23:15:23.486 # Redis version=6.0.9, bits=64, commit=00000000, modified=0, pid=1, just … -
How to resolve SMTP error while sending email in django?
I have deployed my django project successfully on a server but i have having an issue, Whenever i register new user, It returns the following traceback: Traceback (most recent call last): File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/home/ubuntu/dotescrow/dotescrow_main/accounts/views.py", line 51, in post user.email_user(subject, message) File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/contrib/auth/models.py", line 380, in email_user send_mail(subject, message, from_email, [self.email], **kwargs) File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 69, in open self.connection.login(self.username, self.password) File "/usr/lib/python3.8/smtplib.py", line 734, in login raise last_exception File "/usr/lib/python3.8/smtplib.py", line 723, in login (code, resp) = self.auth( File "/usr/lib/python3.8/smtplib.py", line 646, in auth raise SMTPAuthenticationError(code, resp) Exception Type: SMTPAuthenticationError at /accounts/signup/ Exception Value: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt\n5.7.14 pHaElEUTuIMKjGk_0IzO_HxLrVh9yMT7UqnNvrxOgU3my55CdagEe5S1ajgmVozLXO5Tm\n5.7.14 5cgniqTT9lFr3rhyMprFMkfuoOoCKfFGkUx5y9JKEaGr1VkXLIMdb6IFo_gjEoXT>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 z16sm9400103pgj.51 - gsmtp') locally everything is working fine but on the server this is happening , I dont understand whats the matter , … -
Update Jquery Nestable List In Django View
I have an application on Django and I had some information about JQuery Nestable List. When I change to drag or drop the item it will give output like in Django console : [{'name': 'Home', 'id': 264}, {'name': 'About', 'id': 265, 'children': [{'name': 'Product', 'id': 266}]}] So I just want to update my Django-MTTP model in my view. How can I make connections between Jquery Nestable List children and the MTTP parent field? My MODEL class Menu(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') def __str__(self): return str(self.name) JQUERY jQuery.noConflict()(function ($) { $(document).ready(function(){ var csrftoken = getCookie('csrftoken'); var updateOutput = function(e){ var list = e.length ? e : $(e.target),output = list.data('output'); json_response = JSON.stringify(list.nestable('serialize')); $.post('myurl/menu/create_menu',{data:json_response,'csrfmiddlewaretoken':csrftoken}); }; $('#nestable').nestable({ group: 1, maxDepth: 2, }) .on('change', updateOutput); updateOutput($('#nestable').data('output', $('#nestable-output'))); }); }); MY VİEW def create_menu(request): data = json.loads(request.POST.get('data', '')) print(data) return HttpResponse("Ok") -
How do you create a model using opencv in django?
Anybody know who to integrate django and opencv(cv2) together. My goal is to create an model that can store the user and a picture of them. I first tried just using UserPicture.objects.create(user=request.user, picture=image) but that wouldn't work because the function was not taking request as a parameter. Should I create an APIView somehow? Anyways, here is the code I am using for the opencv class: def __init__(self): self.video = cv2.VideoCapture(0, cv2.CAP_DSHOW) def __del__(self): self.video.release() def create_facial_boundary(self, image, cascadeClassifier, color, emotion): grayScaled = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) face = cascadeClassifier.detectMultiScale(grayScaled, 1.1, 10) coords = [] for (x, y, w, h) in face: cv2.rectangle(image, (x, y), (x + w, y + h), color) roi_gray = grayScaled[y : y+h, x: x+w] cv2.putText(image, emotion, (x, y-4), cv2.FONT_HERSHEY_PLAIN, 2, (255, 255, 255)) coords = [x, y, w, h] self.update_time() return coords, image def detect_face(self, image, cascadeClassifier): color = {"green" : (0, 145, 25)} coords, image = self.create_facial_boundary(image, cascadeClassifier, color["green"], "ExText") image = cv2.flip(image, 1) return image def update_time(self): time.sleep(5) def get_user_face(self): success, frame = self.video.read() # img_file = "User-Face.jpg" frame = self.detect_face(frame, cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')) new_frame = cv2.flip(frame, 1) _, image = cv2.imencode(".jpg", new_frame) return image def get_user_emotion(): pass def get_frame(self): success, frame = self.video.read() image_flip = … -
Can not get my static style sheet to connect to my html using django
so i am having weird issue with my static css in the newest django. It is only changing to color on my <h1> the rest is totally unchanged. The static folder is in the root of the project. here is my css h1{ color: red; text-align: center; background-color: black; margin-left:150px; } body{ background-color: lightblue; } .container{ width:100%; } .products{ display: inline-block; width: 30%; } h5{ color:red; } here is the html i am trying to change {%extends "base.html"%} {%block content%} <div class="container"> <!-- for loop to render each product --> {%for product in product_list%} <!-- <h1>test</h1> --> <div class="products"> <ul> <h5>{{product.title}}</h5> <li>Price:{{product.price}}</li> {% if product.available %} <li>In stock</li> <li> Amount in Backstock:{{product.quantity}}</li> <li>Sell by Date:{{product.date}}</li> {%else%} <li>Out of Stock</li> {% endif %} <a type="button" class="btn btn-secondary"href='/product/{{product.id}}/update'> update </a> <a type="button" class="btn btn-danger" href='/product/{{product.id}}/delete'> delete </a> </ul> </div> {%endfor%} </div> {%endblock%} here is my static and static_dir STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", '/var/www/static/', ] -
Why fields are missing in django while using forms
I want to add data to my model through a form For that purpose my I have created the following form file in forms.py class Organization_Profile_Form(forms.ModelForm): class Meta(): model = Organization_Profile fields = ['organization_profile_pic', 'organization_slogan', 'organization_bio', 'organization_email', 'organization_contact', 'Service_type', 'category', 'city', 'status', 'scale'] This form is using the model class Organization_Profile(models.Model): organization = models.OneToOneField(Organization,on_delete=models.CASCADE,primary_key=True, related_name='Organization') organization_profile_pic=models.ImageField(default='default.jpg', upload_to='organization_profile_pics') organization_slogan=models.CharField( max_length=100) organization_bio=models.CharField( max_length=400,null=True) organization_email = models.EmailField(max_length=254,null=True) organization_contact = models.IntegerField(null=True) Service_type = models.CharField(max_length=50,choices=SERVICE, default='PART',blank=True) category = models.CharField(max_length=50,choices=CATEGORY, default='LABOUR_AGENCY',blank=True) city= models.CharField(max_length=200,null=True) date_created = models.DateTimeField(auto_now_add=True, null=True,) status = models.CharField(max_length=200, default='Pending', choices=STATUS) scale = models.CharField(max_length=200,default='SMALL', choices=SCALE) I have created options for status scale etc, not showing it because of extra detailing My view for this form is @login_required def Organization_Profile_View(request): if request.user.is_organization==False: return HttpResponse('Sorry!! This page requires organization previlidge') else: profile_submitted = False organization = request.user.Organization if request.method=='POST': form = Organization_Profile_Form(request.POST) if form.is_valid(): upload = form.save(commit=False) upload.organization = organization upload.save() profile_submitted=True else: form = Organization_Profile_Form() return render(request, 'organization/organization_profile_form.html', {form:'form', profile_submitted:'profile_submitted'}) and the html file this view is reffering to is {% extends "organization/index.html" %} {% load crispy_forms_tags%} {% block content %} <form method="POST"> <h1>Organization Profile Form</h1> {% csrf_token %} <fieldset> {{ form|crispy }} </fieldset> <button type="submit">Submit</button> </form> {% endblock content %} Now the problem is I … -
is a Django model with 800 fields bad design?
This is more of a database design question. I have a Django application that manages consumer data, so, there is 800+ data points on a given consumer. I am not sure what the best way to translate this into a django model is? The current option I have implemented is: class Consumer(models.Model): name=models.CharField(max_length=100, unique=True) address=models.CharField(max_length=100, unique=True) state=models.CharField(max_length=100, unique=True) country=models.CharField(max_length=100, unique=True) income=models.CharField(max_length=100, unique=True) owns_vehicle=models.BooleanField() # 800+ more fields This way works well, as it is easy to filter using Django Filters and there are few table joins so it is performant. However, I am wondering if there would be a better, more performant, or more maintainable way to accomplish this? Maybe using a JSONField and ForeignKey relationships? class Consumer(models.Model): name=models.CharField(max_length=100, unique=True) address=models.CharField(max_length=100, unique=True) state=models.CharField(max_length=100, unique=True) country=models.CharField(max_length=100, unique=True) class DataPoint(models.Model): consumer = models.ForeignKey(Consumer, on_delete=models.CASCADE) column_name = models.CharField(max_length=100, unique=True) value = models.JSONField() However, this is an API, that is reliant on filtering through URL calls, and this method would create more work in building custom filters since the dataset should be able to be filtered by each data point. What is the best way to Translate consumer data with more than 800 columns into a Django model? -
Django functional testing access production database
Is it somehow possible to access my production database in Django selenium functional testing? Let's assume that I have created a library app. In the app there is a button allowing the user to check number of books available. This function will then check with the database the number of available books. In the Django functionality test, can I test this functionality. If I use the test database there will be no books in it. I can of cause, in the test, added books to the test database but I would still like to know if I access the production database? -
Overload of logs from Django-Docker
I'm usually watching the the logs of my Django-Docker by using docker logs django_web_1 -f. Which would only display the set logging and errors, yet (probably due to an upgrade) I'm receiving an overly unusual amount of all kinds of messages which won't stop being outputted and I have difficulties to categorize. The Django-Docker is only used by me and not to be accessed from the internet. At this point it's just running idle, so there's no request coming from me. I can't post the entire log as it exceeds a few Megabytes on each call. Doing an ordinariy start-up of the docker by docker-compose up gives me the regular logs: web_1 | INFO:django.utils.autoreload:Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | January 22, 2021 - 20:07:39 web_1 | Django version 3.1.3, using settings 'DjangoMoP.settings' web_1 | Starting development server at http://0.0.0.0:9900/ web_1 | Quit the server with CONTROL-C. The new logs are also presnet in the specified Django-Handlers. What is the background of these logs and why am I getting them? INFO:django.server:"GET / HTTP/1.1" 200 33226 WARNING:django.request:Not Found: /client/ ---------------------------------------- Exception happened during processing … -
Loading fixture after migrating from auto-generated primary keys to slug primary keys. AttributeError: Problem installing fixture
I've updated my models to use slugfields as primary keys. I've modified the fixtures for the models so they are pointing to the correct field/model for any ManyToMany fields and ForeignKeys. Ie: app.model.settings is a ManyToMany field referencing another model that now uses SlugField as PK. // Before { "model": "app.model", "pk": "Test", "fields": { "settings": [ 8, 9, 10, 11 ] } }, // After { "model": "app.model", "pk": "Test", "fields": { "settings": [ "slug-value8", "slug-value9", "slug-value10", "slug-value11" ] } }, However I'm running into an issue when I try to load the fixture. AttributeError: Problem installing fixture '/project/app/fixtures/app.json': 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' I've searched everywhere I can think of an I'm not sure where this issue is coming from. I'm assuming it is directly related to the ManyToMany fields I have, but other than that I haven't found much on the error. -
Django Microsoft Authentication Backend not succeeding on new deployments
I have an app deployed in many places and it uses Django Microsoft Authentication Backend. Starting yesterday when we deploy the app the auth is now not working. We get back Failed to authenticate you for an unknown reason. Please try again later. We can see in the azure logs that the login was successful. We have the same version of Django Microsoft Authentication Backend installed, but for some reason on newly built boxes it is failing but older ones it is succeeding. What could be causing this? What can we check to track down what the issue may be? -
How can I download the file linked with the post?
I'm quite new to using Django and I am trying to develop a website where the user can download file at the end of the post. Post model: class Article(models.Model): title = models.CharField(max_length=30) content = models.TextField() pub_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField(upload_to='code_files/') def __str__(self): return self.title I have a views: def download(request): response = HttpResponse(open(f"media/code_files/tests.py", 'rb').read()) response['Content-Type'] = 'text/plain' response['Content-Disposition'] = f'attachment; filename=tests.py' return response How can I download the file linked with the post? -
Django ajax comment reply
Please answer the bellow question: Django jquery ajax comment reply create multiple values -
Django 3, how to tell ModelViewSet that a certain field is not required?
So I have a reservation modelviewset, which calls a serializer that takes a user, room, start time and end time and when I run it it keeps saying the user is required. I think this is Django processing the request data and stopping, but if it actually ran my code it would realize i actually fetch that required field when creating (I fetch the logged in user, so I don't need the request to specify it) How do i tell django that the user is not required in the data of the request? If code actually needed for this I can post, but I'm thinking it's a quick fix? -
How to execute insert into in django with raw sql commands from a html form
I'm using Django and I have a form in html which gets the data to store in the database, I would like to know how can I insert this data without using ORM, just pure SQL commands. Do I have to create a model? Does anyone have any example? -
function in Django behaves differently
I have a function named localtime(ltz, /) to calculate users' local time. Outside of Django it works, but I get localtime takes 0 positional arguments but 1 was given error inside of Django. Here's the function UTILITY.PY def localtime(ltz, /): utc_now = datetime.datetime.now(tz=pytz.UTC) return utc_now.astimezone(pytz.timezone(ltz)) VIEWS.PY .... qs = Users.objects.filter(id=self.request.user).values() for val in qs: local_time = localtime(val['time_zone']) print(local_time) .... Can anyone help figure out why I'm getting localtime takes 0 positional arguments but 1 was given error in Django? Thank you in advance.