Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static files in Django with AWS S3
I just moved the static files of my Django project into AWS S3. It works so far. But my .css files contain relative paths, for example to fonts, for example: @import "variables"; @font-face { font-family: '#{$font-family}'; src: url('#{$font-path}/#{$font-family}.eot?4zay6m'); format('svg'); font-weight: normal; font-style: normal; } My browser console shows that the path to these file is set correctly, for example https://mybucket.s3.amazonaws.com/static/plugins/fonts/myfont.ttf?4zay6m but I get a permission denied, because unlike the other (from django set paths), these paths do not contain the "Amazon stuff" after the question mark like https://mybucket.s3.amazonaws.com/static/js/jquery.tablednd.js?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXXXXXX Is there a simple workaroud? Thanks in advance. -
Why django dependent dropdownn is not working
I cant tell where there is an error in my code. It just doesnt work as expected. My views.py def load_cities(request): year_id = request.GET.get('year') terms = Term.objects.filter(school=request.user.school).filter(year_id=year_id).order_by('name') return render(request, 'city_dropdown_list_options', {'terms': terms}) My models. class Year(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) year = models.CharField(max_length=200,unique=True) class Term(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) year = models.ForeignKey(Year,on_delete=models.CASCADE) name = models.CharField(max_length=200,unique=True) class Exam(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) year = models.ForeignKey(Year,on_delete=models.SET_NULL, null=True) term = models.ForeignKey(Term,on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=20) form = models.ManyToManyField(FormModel) My forms.py class NewExamForm(forms.ModelForm): class Meta: model = Exam fields = ("year","term","name","school","form") widgets = { 'school':forms.TextInput(attrs={"class":'form-control','value':'','id':'identifier','type':'hidden'}), "year":forms.Select(attrs={"class":'form-control'}), "name":forms.TextInput(attrs={"class":'form-control'}), "form":forms.Select(attrs={"class":'form-control'}), } def __init__(self, school, *args, **kwargs): super(NewExamForm, self).__init__(*args, **kwargs) self.fields['year'] = forms.ModelChoiceField( queryset=Year.objects.filter(school=school)) self.fields['term'].queryset = Term.objects.none() self.fields['form'] = forms.ModelMultipleChoiceField( queryset=FormModel.objects.filter(school=school), widget=forms.CheckboxSelectMultiple, required=True) if 'year' in self.data: try: year = int(self.data.get('year')) self.fields['term'].queryset = Term.objects.filter(school=school).filter(year_id=year).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['term'].queryset = self.instance.year.term_set.order_by('name') The template <div class="form-group"> <form method="post" id="examForm" data-cities-url="{% url 'ajax_load_cities' %}" novalidate enctype="multipart/form-data"> {% csrf_token %} <table> {{ form|crispy }} </table> <button type="submit">Save</button> </form> </div> I have tried but it works only after I select a year and refresh manually with the year selcted, that's when the terms appear. I tried following the code … -
What does this error mean? And how to solve it?
*** Good afternoon, sansei. Faced a problem and can't solve it. I am trying to add models to the database and I am getting an error. Please explain what I am doing wrong. Maybe someone came across such an error and will tell you how to solve it *** `` dadi2015@ubuntu:~$ sudo python3 /home/allianceserver/myauth/manage.py migrate [sudo] password for dadi2015: Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection return Database.connect(**conn_params) File "/usr/local/lib/python3.8/dist-packages/MySQLdb/init.py", line 130, in Connect return Connection(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/MySQLdb/connections.py", line 185, in init super().init(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1698, "Access denied for user 'root'@'localhost'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/allianceserver/myauth/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/migrate.py", line 75, in … -
from django.http import HttpResponse, JsonResponse ModuleNotFoundError: No module named 'django'
I am running a project in python 3.7 to obtain data from a server through a GET, for this I import the following: django.http import HttpResponse, JsonResponse When executing the project I get the following error as output: from django.http import HttpResponse, JsonResponse ModuleNotFoundError: No module named 'django' -
Django return field for each model object
I have two models Game and People. I'm trying to iterate through the People model & return a single CharField for each value that people has & save their score with their name to the Game when creating the game. (Don't want name to be a field, just save with the score). The error I'm currently getting with this is the following: no such column: home_game.score class People(models.Model): name = models.CharField(verbose_name="Name", max_length=250) def __str__(self): return self.name Game Model: class Game(models.Model): title = models.CharField(verbose_name="Title", max_length=100) details = models.TextField(verbose_name="Details/Description", blank=False) for each in People.objects.all(): score = models.CharField(verbose_name=each.title, max_length=4) -
problem with displaying CSS and the image in django
I'm just not able to get the CSS properties to display on the browser and also the image. I don't know what I'm doing wrong,i'd appreciate someone helping me out with this. thank you. -
Filtering with wildcards in Django Rest Framework
I'm looking for a way to be able to filter my dataset in DRF using a wildcard. For example; I want to return any hostname in the below model that starts with 'gb'. I also have some requirements to search in the middle and the end of the hostname depending on usecase. I'd expect to be able to hi the following endpoint: /devices/?host_name=gb* and it return everything that has a host_name starting with gb. Model: class Device(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) host_name = models.CharField(max_length=64) mgmt_ip_address = models.GenericIPAddressField() domain_name = models.CharField(max_length=64) class Meta: ordering = ['host_name'] def __str__(self): return self.host_name Serializer: class DeviceSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField() class Meta: model = Device fields = '__all__' View: class DeviceViewSet(viewsets.ModelViewSet): permission_classes = (DjangoModelPermissions,) queryset = Device.objects.all() serializer_class = DeviceSerializer filter_backends = [DjangoFilterBackend, filters.rest_framework.DjangoFilterBackend, drf_filters.SearchFilter] filter_fields = ['id', 'host_name', 'mgmt_ip_address', ] I have tried creating custom filters but not sure that is the right approach since I haven't been able to get it working. -
Using Django, should I implement two different url mapping logics in my REST API and web application, and how?
I have a Book model an instance of which several instances of a Chapter model can be linked through Foreign Key: class Book(models.Model): pass class Chapter(models.Model): book = models.ForeignKey(to=Book, ...) class Meta: order_with_respect_to = "book" I decided to use Django both for the RESTful API, using Django Rest Framework, and for the web application, using Django Template. I want them separate as the way should be open for another potential application to consume the API. For several reasons including administration purposes, the API calls for a url mapping logic of this kind: mylibrary.org/api/books/ mylibrary.org/api/books/<book_id>/ mylibrary.org/api/chapters/ mylibrary.org/api/chapters/<chapter_id>/ For my web application, however, I would like the user to access the books and their contents through this url mapping logic: mylibrary.org/books/ mylibrary.org/books/<book_id>-esthetic-slug/ mylibrary.org/books/<book_id>-esthetic-slug/chapter_<chapter_order>/ The idea is the router to fetch the book from the <book_id>, whatever the slug might be, and the chapter according to its order and not its ID. Now I need some advice if this is desirable at all or if I am bound to encounter obstacles. For example, how and where should the web app's <book_id>/<chapter_order> be "translated" into the API's <chapter_id>? Or if I want the web app's list of books to offer automatically generated slugged links … -
Using value from URL in Form Wizard for Django
I'm trying to use this Form Wizard to design a multipage form in Django. I need to catch a value from the URL, which is a client's ID, and pass it to one of the Forms instance, as the form will be built dynamically with specific values for that client. I have tried redefining the method get_form_kwargs based on this thread, but this isn't working for me. I have the following code in my views.py: class NewScanWizard(CookieWizardView): def done(self, form_list, **kwargs): #some code def get_form_kwargs(self, step): kwargs = super(NewScanWizard, self).get_form_kwargs(step) if step == '1': #I just need client_id for step 1 kwargs['client_id'] = self.kwargs['client_id'] return kwargs Then, this is the code in forms.py: from django import forms from clients.models import KnownHosts from bson import ObjectId class SetNameForm(forms.Form): #Form for step 0 name = forms.CharField() class SetScopeForm(forms.Form): #Form for step 1, this is where I need to get client_id def __init__(self, *args, **kwargs): super(SetScopeForm, self).__init__(*args, **kwargs) client_id = kwargs['client_id'] clientHosts = KnownHosts.objects.filter(_id=ObjectId(client_id)) if clientHosts: for h in clientHosts.hosts: #some code to build the form When running this code, step 0 works perfectly. However, when submitting part 0 and getting part 1, I get the following error: _init_() got an unexpected keyword … -
How to receive the emails from the user, using office365 mail credentials, In `Django`?
As office 365 requires to use only the HOST_USER mail as the sender, tha mail which was used to buy the office365 credentials. So how can we receive the mail from the user. -
how to jquery ajax json response for loop / django
django model class UserAlbum(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='albums') album_photos = models.ManyToManyField(Photo, through='AlbumPhoto') album_name = models.CharField(max_length=50, blank=False) is_private = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date_created'] def __str__(self): return f"{self.user}'s album [{self.album_name}]" def get_absolute_url(self): return reverse('album:album', args=[self.user, str(self.id)]) django view @login_required def get_album_list(request): if request.method == 'GET': user = request.user albums = user.albums.all() return JsonResponse(serializers.serialize('json', albums), safe = False) script $("#album_list_modal_button").click(function () { $.ajax({ type: "GET", url: "{% url 'album:get_album_list' %}", dataType: "json", success: function (response) { if (response) { //test $("#modal_body_album_list").html(response) //loop test 1 $.each(response, function(i, item) { $("#modal_body_album_list").append(item.fields.album_name); }); //loop test 2 for (var i = 0; i < response.length; i++) { $('#modal_body_album_list').append('<li>'+response[i].fields.album_name+'</li>'); } } else { $("#modal_body_album_list").html('None'); } }, error: function (request, status, error) { window.location.replace("../user/login") }, }); }) what i need to do is print each albums name using iteration only test part works and printed like this. [{"model": "album.useralbum", "pk": 6, "fields": {"user": 6, "album_name": "test album name1", "is_private": true, "date_created": "2021-03-26T19:20:23.571"}}, {"model": "album.useralbum", "pk": 4, "fields": {"user": 6, "album_name": "test album name2", "is_private": false, "date_created": "2021-03-18T20:30:09.575"}}] i've searched and find two way of loop. But these are not working. please help!! -
Python DJANGO input fields
I want to make simple "calculator" on django app. I want to make 2 fields. Visitor put 2 numbers into fields and multiplication this numbers. I want to make input1 = 2, input2 = 3 and output will be 6. only this inputs make customer on website. Thanks for help and hve a great day -
How to handle excel file sent in POST request in Django?
I sent an excel file in a post request to my back-end and I tried handling the file using the following: def __handle_file(file): destination = open('./data.xslx', 'wb') for chunk in file.chunks(): destination.write(chunk) destination.close() However, the output from that is not an excel file. It is a collection of XML files. My end goal is to obtain a data frame from the file data that was sent so that I can extract the data. What is a clean way of handling this type of file? -
Why do I get "HTTP Error 404: Not Found" when installing pyaudio with pipwin in Python Django project in Windows 10?
I'm trying to install pyaudio with pipwin in a Python Django project in Windows 10. I first run CMD as admin in Windows 10. Then I run the command: pipwin install pyaudio and I get the following error: raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found the full output from the command: Package `pyaudio` found in cache Downloading package . . . https://download.lfd.uci.edu/pythonlibs/z4tqcw5k/PyAudio-0.2.11-cp38-cp38-win_amd64.whl PyAudio-0.2.11-cp38-cp38-win_amd64.whl Traceback (most recent call last): File "C:\Users\Knowe\AppData\Local\Programs\Python\Python38\Scripts\pipwin-script.py", line 11, in <module> load_entry_point('pipwin==0.5.1', 'console_scripts', 'pipwin')() File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pipwin\command.py", line 103, in main cache.install(package) File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pipwin\pipwin.py", line 300, in install wheel_file = self.download(requirement) File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pipwin\pipwin.py", line 294, in download return self._download(requirement, dest) File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pipwin\pipwin.py", line 290, in _download obj.start() File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pySmartDL\pySmartDL.py", line 267, in start urlObj = urllib.request.urlopen(req, timeout=self.timeout, context=self.context) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 222, in urlopen return opener.open(url, data, timeout) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 531, in open response = meth(req, response) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 640, in http_response response = self.parent.error( File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 569, in error return self._call_chain(*args) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 502, in _call_chain result = func(*args) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 649, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found Why can I not install pyaudio? Thanks! -
Error while installing mysqlclient in django project on cPanel
I've been trying to solve this problem for a couple of days. I am trying to put my Django project in a venv on cPanel and install mysqlclient. So after setting up my Python (version = 3.7.8) on Cpanel, I installed Django version 3.1.7 and mysqlclient from the terminal using pip install django and pip install mysqlclient. However when I try to install mysqlclient, this error pops out. Using cached mysqlclient-2.0.3.tar.gz (88 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/canggihmallmy/virtualenv/django_test/3.7/bin/python3.7_bin -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ct08p_k4/mysqlclient_5cd61bc8b4de40efb5731cfe082b4d65/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ct08p_k4/mysqlclient_5cd61bc8b4de40efb5731cfe082b4d65/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))'bdist_wheel -d /tmp/pip-wheel-scx4wswm cwd: /tmp/pip-install-ct08p_k4/mysqlclient_5cd61bc8b4de40efb5731cfe082b4d65/ Complete output (43 lines): mysql_config --version ['10.0.38'] mysql_config --libs ['-L/usr/lib64', '-lmysqlclient', '-lpthread', '-lz', '-lm', '-ldl', '-lssl', '-lcrypto'] mysql_config --cflags ['-I/usr/include/mysql', '-I/usr/include/mysql/..'] ext_options: library_dirs: ['/usr/lib64'] libraries: ['mysqlclient', 'pthread', 'm', 'dl'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/include/mysql', '/usr/include/mysql/..'] extra_objects: [] define_macros: [('version_info', "(2,0,3,'final',0)"), ('__version__', '2.0.3')] /opt/alt/python37/lib64/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.7 creating build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> … -
Circular import Django and im lost ... :(
I got my services.py where i am trying to make api connections based on some tables in models(fex user): import requests import json from django.contrib.auth.models import User from .models import UserProfile,House have a function here that call 2 database queries to get more info to connect towards the API and my models.py contains: from django.db import models from django.contrib.auth.models import User from django.contrib.auth.signals import user_logged_in from .services import * connectApi() -> function in services.py -
How do I sort a Queryset according to a list?
For example, I do this: m.objects.filter (id__in = [3,1,8]) And it is necessary that the elements in the queryset go in order, that is, first id = 3, then id = 1, then id = 8, etc. But in the end, you need a queryset, not a list! -
Set up Flutter Client for Django/GraphQL
I've been trying to get this to work, it looks like it should be fairly simple but I just can't find a recent reference, the README file at pub.dev isn't all that clear and the only other examples are all from before flutter 2.0, so I don't know if that's what it is. import 'package:flutter/material.dart'; import 'package:graphql_flutter/graphql_flutter.dart'; String search = """ query { units { title } } """; void main() async { WidgetsFlutterBinding.ensureInitialized(); final HttpLink httpLink = HttpLink( 'http://localhost:8000/graphql/', ); ValueNotifier<GraphQLClient> client = ValueNotifier( GraphQLClient( link: httpLink, // The default store is the InMemoryStore, which does NOT persist to disk cache: GraphQLCache(store: InMemoryStore()), ), ); runApp(GraphQLProvider( child: MaterialApp( title: "APIClient", home: MyApp(), ), client: client, )); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return Query( options: QueryOptions(document: gql(search)), builder: (QueryResult result, {fetchMore, refetch}) { if (result.data == null) { return Text("No data found"); } return ListView.builder( itemBuilder: (BuildContext context, int index) { return Text(result.data!['title'][index]); }, itemCount: result.data!.length, ); }); } } I already got a django/graphql server running on localhost:8000/graphql. Any help would really help. thx, oscrr -
Users reset password
I get a 404 not found error when users trie to reset their password. It worked fine until I had to reinstall my server due to OVH datacenter fire ... I also uprade Django version to the last one. You can try here : https://www.lamontagnesolitaire.fr/start/forget/ My views def view_forget(request): media = settings.MEDIA if request.method == 'POST': form = ForgetForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] try: user = User.objects.get(email=email) except: messages.add_message(request, messages.INFO, 'Vérifiez votre messagerie, un e-mail vous a été envoyé !') messages.add_message(request, messages.INFO, 'Vous pouvez fermer cette page.') return redirect(view_forget) token = default_token_generator.make_token(user) uidb64 = urlsafe_base64_encode(force_bytes(user.pk)) from django.core.mail import send_mail corps = 'Bonjour, la modification de votre mot de passe est à effectuer en suivant ce lien : https://www.lamontagnesolitaire.fr/start/forget/reset/%s/%s' %(uidb64, token) subject = "Changement de mot de passe" message = corps sender = "Equipe@LaMontagneSolitaire.fr" recipients = [email, ] send_mail(subject, message, sender, recipients) messages.add_message(request, messages.INFO, 'Vérifiez votre messagerie, un mail vous a été envoyé !') messages.add_message(request, messages.INFO, 'Vous pouvez fermer cette page.') else: form = ForgetForm() return render(request, 'forget.html', locals()) def view_forget_reset(request, uidb64, token): media = settings.MEDIA if uidb64 is not None and token is not None: from django.utils.http import urlsafe_base64_decode uid = urlsafe_base64_decode(uidb64) try: from django.contrib.auth import get_user_model from django.contrib.auth.tokens … -
const product = products.find(p => Number(p._id) === Number(match.params.id)) geting type error
import React from 'react' import { Link } from 'react-router-dom' import { Row, Col, Image, ListGroup, Button, Card } from 'react-router-bootstrap' import Rating from '../components/Rating' import products from '../products' function ProductScreen({ match }) { const product = products.find(p => Number(p._id) === Number(match.params.id)) return ( {product.name} ) } export default ProductScreen -
DetailView with UUID getting NoReverseMatch
It was working with a normal pk but when I changed to UUID it stopped working. Model: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) order_number = models.CharField(primary_key=True, default=uuid.uuid4().hex[:5].upper(), max_length=50, editable=False) product_cost = models.IntegerField(default=0) order_cost = models.IntegerField(default=0) order_status = models.CharField(max_length=100, default='Pending') completion_date = models.DateField() def __str__(self): return self.order_number url: path('panel/orders/<uuid:pk>', views.OrderDetail.as_view(), name='order-detail') template: <a href="{% url 'order-detail' o.pk %}" aria-current="page" class="dropdown-link w-inline-block w--current"> Error: Reverse for 'order-detail' with arguments '('65830',)' not found. 1 pattern(s) tried: ['panel/orders/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$'] -
using following approach: for key in ("a1", "a2", "a3" .....) How can I change values of list members? [closed]
I have something like this: for key in ("a1", "a2", .....) if key == "": (the member which is empty) = getattr(object, key) Is there a way to do so? -
How to handle large numbers in python, django models for mysql?
How to handle large numbers in python and django models for mysql datatype? I want to store large decimal numbers e.g mass of the Sun in kg (1.98847±0.00007)×10^30 kg and other large numbers of physics and astronomy. What max_digits and decimal_places will I need? For simple longitude, latitude I use 11,6: models.DecimalField(max_digits=11, decimal_places=6, null=False) >>> s = 1.9884723476542349808764 >>> s 1.988472347654235 >>> -
Exception caused due to DateTimeField in Django unit test cases with SQLite
We are by default running unit tests & production against postgres. Normally it takes almost 10 mins to run 58 test cases. To achieve faster test performance for dev environment, I am experimenting with running tests against SQLite3 locally by providing different test specific configuration. But I ran into issues while creating object with DateTimeField as follows. Default auto_now and auto_now_add DateTimeField seems to be working fine. import dateutil.parser st1 = dateutil.parser.parse('2021-02-28T11:00:00Z') et1 = dateutil.parser.parse('2021-02-28T12:00:00Z') self.event2, created = Event.objects.get_or_create(name='test_event_2', owner=owner_id, start_time=st1, end_time=et1) Exception: Traceback (most recent call last): File "/home/vikram/.virtualenvs/my_venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/vikram/.virtualenvs/my_venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: unrecognized token: ":" -
User permissions in django using decorators
I am following a tutorial from youtube he used some codes that I did not understand please explain it if anyone can. def allowed_user(allowed_roles=[]): def decorators(view_func): def wrapper(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not athorize to veiw this page') return wrapper return decorators