Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.2 Upgrade + TransactionManagement Error + During Tests execution
We are upgrading the django application from version 1.11 to version 2.2 and we have almost done the necessary upgrade, and when we are running the testcases, we are getting error as django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. and we are able to run the same testcases in django 1.11. Even When I run below simple testcase with django 2.2 version is also giving error as mentioned above and its not even printing "hello" statement from setup method. libraries we are using pytest 4.4, pytest-django-3.4.5 and django 2.2 and djangorestframework 3.11 I have done more research, but could not able to find solution, please advise from django.test import TestCase class GetValuesTestCase(TestCase): def setUp(self): print("hello") def test_hello(self): print("hhh") -
PATCH request for myown user object returns a 405 code
so im trying to make a url like some_site/me/, that shows my profile and the patch for some reason doesnt work heres a view: class MyUserViewSet(viewsets.ModelViewSet): pagination_class = None permission_classes = [permissions.IsAuthenticated] serializer_class = UserSerializer def get_queryset(self): return User.objects.filter(username=self.request.user.username) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset[0]) return Response(serializer.data) def partial_update(self, request, *args, **kwargs): queryset = self.list() serializer = UserSerializer(queryset, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() a serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = 'first_name', 'last_name', 'username', 'bio', 'email', 'role' lookup_field = 'username' a model if needed class User(AbstractUser): USER_ROLE = ( ('user', 'user'), ('moderator', 'moderator'), ('admin', 'admin'), ) role = models.CharField(max_length=9, choices=USER_ROLE, default='user') email = models.EmailField('email address', unique=True) bio = models.TextField(max_length=300, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['role',] my guess is smths up with the retrieve thing -
How to parse the queryset from django-simple-history?
How to parse the queryset from the django-simple-history to a table with columns: history_id, history_date and etc. I'm inherit DetailView class -
Axios 404 (Not Found) on first click, third click works
I've built my react application (https://carru.co) using axios to connect to my backend django server, in which I have to send a request there to get some information required for it to work, the problem I'm having is that I'm sending exactly the same request from one device but when trying to do it from other one it doesn't work, it sometimes work and sometimes don't. For example, in my pagination, I need three clicks to get it to work as is shown in the console for exactly the same values on request: At the third click the request was performed with status 200 and data was received. This is my code: nextPage = () => { let local_page = this.state.page local_page += 1 console.log('clicked next', local_page) this.setState({loading: true}) getCarFiltersPage(this.state.brands, this.state.models, this.state.filters, local_page).then( res => { this.setState({list_json: res}) this.setState({loading: false}) this.setState({page: local_page}) window.scrollTo(0, 0) } ) } Thanks in advance for any hint or help -
Uncaught TypeError: Cannot read property 'Constructor' - Django Bootstrap-datapicker
I'm getting the error "Uncaught TypeError: Cannot read property 'Constructor' of undefined at bootstrap datepicker" and the date pop up doesn't work: I start getting this error after updating all my packages to the last version on the project and after hours of research, I didn't find any solution. After I had the following versions, among others: Django==2.1.7 django-bootstrap-datepicker-plus==3.0.5 django-bootstrap4==0.0.7 Now I have the following versions: Django==3.1.7 django-bootstrap-datepicker-plus==3.0.5 django-bootstrap4==2.3.1 This is how my code is structured and was working perfectly on old packages versions: main.html: <head> (some CSS's load's) {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {% block extrahead %} {{ form.media }} {% endblock %} </head> <body> (...) {% block content %} {% endblock %} (...) <script type="module" src="{% static 'vendor/jquery-easing/jquery.easing.min.js' %}"></script> <!-- Custom scripts for all pages--> <script type="module" src="{% static 'js/sb-admin-2.min.js' %}"></script> <!-- Page level plugins --> <script type="module" src="{% static 'vendor/datatables/jquery.dataTables.min.js' %}"></script> <script type="module" src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js'%}"></script> <!-- Page level custom scripts --> <script type="module" src="{% static 'js/demo/datatables-demo.js' %}"></script> <!-- Deletes --> <script type="module" src="{% static 'js/deletes.js' %}"></script> <!-- Tables sort and search --> <script type="module" src="{% static 'js/tables-aux.js' %}"></script> <script type="module" src="{% static 'js/add_types.js' %}"></script> <script type="module" src="{% static 'js/defult.js' %}"></script> … -
How to create a requirements.txt file in Django project?
I have been trying to create a requirements.txt file from the Pycharm terminal but it is adding all unnecessary packages as well. What should I do to show only used packages? Thanks, requirements.txt: aiohttp==3.7.3 aioredis==1.3.1 alabaster==0.7.12 anaconda-client==1.7.2 anaconda-navigator==1.9.12 anaconda-project==0.8.3 appdirs==1.4.4 appnope==0.1.0 argh==0.26.2 asgiref==3.3.1 asn1crypto==1.3.0 astroid==2.4.2 astropy==4.0.1.post1 async-timeout==3.0.1 atomicwrites==1.4.0 attrs==19.1.0 autobahn==21.2.1 Automat==20.2.0 autopep8 @ file:///tmp/build/80754af9/autopep8_1592412889138/work Babel==2.8.0 backcall==0.1.0 backports.functools-lru-cache==1.6.1 backports.shutil-get-terminal-size==1.0.0 backports.tempfile==1.0 backports.weakref==1.0.post1 bcrypt==3.1.7 beautifulsoup4==4.9.1 bitarray @ file:///C:/ci/bitarray_1594751092677/work bkcharts==0.2 bleach==3.1.0 bokeh @ file:///C:/ci/bokeh_1593183652752/work boto==2.49.0 Bottleneck==1.3.2 brotlipy==0.7.0 bs4==0.0.1 certifi==2020.6.20 cffi==1.13.1 channels==3.0.3 channels-redis==3.2.0 chardet==3.0.4 cheroot==8.5.2 Click==7.0 cloudpickle @ file:///tmp/build/80754af9/cloudpickle_1594141588948/work clyent==1.2.2 colorama==0.4.4 comtypes==1.1.7 conda==4.8.3 conda-build==3.18.11 conda-package-handling==1.7.0 conda-verify==3.4.2 constantly==15.1.0 contextlib2==0.6.0.post1 cryptography==3.4.6 cycler==0.10.0 Cython @ file:///C:/ci/cython_1594830140812/work cytoolz==0.10.1 daphne==3.0.1 dask @ file:///tmp/build/80754af9/dask-core_1594156306305/work decorator==4.4.0 defusedxml==0.6.0 diff-match-patch @ file:///tmp/build/80754af9/diff-match-patch_1594828741838/work distlib==0.3.1 distributed @ file:///C:/ci/distributed_1594747837674/work dj-database-url==0.5.0 dj-rest-auth==2.1.3 Django==3.1.5 django-admin-honeypot==1.1.0 django-allauth==0.44.0 django-bootstrap4==0.0.5 django-channels==0.7.0 django-crispy-forms==1.11.0 django-defender==0.8.0 django-heroku==0.3.1 django-honeypot==0.9.0 django-tastypie==0.14.3 djangorestframework==3.12.2 dnspython==1.15.0 docutils==0.16 entrypoints==0.3 et-xmlfile==1.0.1 Faker==0.8.13 fastcache==1.1.0 filelock==3.0.12 flake8==3.7.8 Flask==0.12.4 Flask-Bcrypt==0.7.1 Flask-Cors==3.0.3 Flask-JWT-Extended==3.7.0 Flask-Login==0.4.0 fsspec==0.7.4 future==0.18.2 gevent @ file:///C:/ci/gevent_1593010772244/work glob2==0.7 gmpy2==2.0.8 greenlet==0.4.16 gunicorn==20.0.4 h5py==2.10.0 HeapDict==1.0.1 hiredis==1.1.0 html5lib @ file:///tmp/build/80754af9/html5lib_1593446221756/work hyperlink==21.0.0 idna @ file:///tmp/build/80754af9/idna_1593446292537/work imageio @ file:///tmp/build/80754af9/imageio_1594161405741/work imagesize==1.2.0 importlib-metadata==0.23 incremental==17.5.0 intervaltree @ file:///tmp/build/80754af9/intervaltree_1594361675072/work ipykernel==5.1.3 ipython==7.8.0 ipython-genutils==0.2.0 ipywidgets==7.5.1 isort==5.7.0 itsdangerous==1.1.0 jaraco.functools==3.1.0 jdcal==1.4.1 jedi==0.15.1 Jinja2==2.10.3 joblib @ file:///tmp/build/80754af9/joblib_1594236160679/work json5==0.9.5 jsonschema==3.1.1 jupyter==1.0.0 jupyter-client==5.3.1 jupyter-console==6.0.0 jupyter-core==4.4.0 jupyterlab==2.1.5 jupyterlab-server @ file:///tmp/build/80754af9/jupyterlab_server_1594164409481/work keyring @ file:///C:/ci/keyring_1593109210108/work kiwisolver==1.2.0 lazy-object-proxy==1.4.3 libarchive-c==2.9 llvmlite==0.32.1 locket==0.2.0 lxml @ file:///C:/ci/lxml_1594826940903/work … -
Can I connect a Python GUI to a website using HTTP?
Is there a way to connect to a website from a Python Tkinter GUI using HTTP requests? Essentially, I want the following functionality: Press a button on the GUI A signal is sent to a website (from the GUI) that this button was pressed Send information along with that signal I only need to focus on the GUI side of this. I have no code to go along with this - I was just wondering if it's even possible. -
Django - AWS S3 - non-predictable behavior when reading a FileField
I have a django model like so: class Segmentation(models.Model): file = models.FileField(...) ... The file is an image (of a red blob) that is stored in an AWS bucket. I am trying to do some simple computer vision logic on each file in my segmentation instances. However I noticed some very strange non-predictable behavior when reading the file using: bytes_string = segmentation.file.read() if bytes_string: # conduct simple cv logic else: # do nothing Sometimes the file reading "fails" such that bytes_string is b'' and the remaining part of the script does not execute. However, if I rerun the script the file reading may indeed be successful and the remaining part of the script executes as desired. When exactly a file reading "fails" I have yet to determine. Has anyone come across an issue like this before? The cv-script lives in a post_save signal, meaning a solution (ideally) avoids having to repeatedly run this script in order to trigger a successful file-read. -
How to run periodic tasks concurrently with Celery and Django
I have some tasks being running by celery in my Django project. I use contrab to specify the time the task should be run, like this: from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'task_a': { 'task': 'tasks.task_a', 'schedule': crontab(minute=0, hour='5,18'), }, 'task_b': { 'task': 'tasks.task_b', 'schedule': crontab(minute=4, hour='5,18'), }, } What has been happening is that one task is executed, and only about 5 minutes later the other starts. When they should be executed at the same time. I would like all of them to be started at the same, but this it's not what is happening there are about eight tasks in total, some of which take a long time to complete I am using the following command at the moment initially, it was like this celery -A api worker --concurrency=4 -n <name> then I tried celery -A api multi --concurrency=4 -n <name> and finally celery -A api multi -P gevent --concurrency=4 -n <name> They are all shared_tasks @shared_task(bind=True, name="tasks.task_a") def task_a(self): pass and I'm using autodiscover_tasks app = Celery('<app-name>') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) -
In djangocms-picture how to set a default maximum image size?
I would like to set a default maximum size of images in the djangocms-picture plugin. I would like to do this at template level. This simple template for example: {% load thumbnail %} <img src="{% thumbnail instance.img_src 'golden_ratio_xlarge' %}"> Gives this error: SuspiciousFileOperation at /en/ The joined path (/media/filer_public_thumbnails/filer_public/a3/07/a3073ea1-a798-43c0-869f-689de5f53e7e/sawa.png__420x233_q85_subsampling-2.png) is located outside of the base path component (/home/mogoh/src/git.noc.ruhr-uni-bochum.de/ceres/website/ceres/media) -
Using Python/Django how do I substitute values from an external source into an HTML page
I am relatively new to Django and am trying to substitute values from an external source into an HTML page? Using the following HTML snippet: <div>UID: -3SDfguwvNuurPe44AnUjGdzOj_guWVP3QPjmhZyWsA1</div> <div>Validic ID: 5e220365bdb13500b03075a2</div> <div>Created: 2020-01-17T18:56:37Z</div> <div>Updated: 2020-01-17T18:56:37Z</div> I want to replace the text value for each of those rows (to the right of the "key:" with the value retrieved from a JSON response for each of the "keys". I have tried: <div>UID: {{ display_uid }}</div> <div>Validic ID: {{ display_vid }}</div> <div>Created: {{ display_created }}</div> <div>Updated: {{ diplay_updated }}</div>``` The examples I have found have shown how to build forms and use text fields/text areas, but nothing for a plain HTML page. Anybody got suggestions? Thanks. Jeff Brown -
How to replace comment column in django-simple-history view with action column from standard django admin view?
I'm trying to enhance tracking options of instances in my database. I've applied django-simple-history app. It helps a lot except of the column COMMENTS which I find totally useless. Comments column in django-simple-history view I would prefer to replace the column comments withe column ACTION from the standard history admin view. Action column in standard admin view Is there an easy way to do that? -
Replicating Django forms request.FILES to upload multiple image files using smartfields
I'm trying to take a single image using Django forms and upload it with resized version under 3 headers. I'm even able to do so with request.POST QueryDict but not with request.FILES MultiValueDict even after it shows filled data for respective field names. My Views.py def image_add(request,article_id): template_name = 'blogs/image_add.html' articles = Article.objects.get(article_id=article_id) form = ImageAddForm if request.method == 'POST': image = request.FILES["image_1080"] request.FILES['image_800'] = image request.FILES['image_350'] = image print(request.POST) print(request.FILES) form = ImageAddForm(request.POST, request.FILES) if form.is_valid(): new_form = form.save(commit=False) new_form.dir_id = article_id new_form.save() return redirect('/') context = {'form':form,'articles':articles} return render(request, template_name,context) My Models.py from smartfields import fields from smartfields.dependencies import FileDependency from smartfields.processors import ImageProcessor class Images(models.Model): dir_id = models.CharField(max_length=10,null=True) image_1080 = fields.ImageField(upload_to=img_1080_dir_path, name="image_1080", dependencies=[ FileDependency(processor=ImageProcessor( format='PNG', scale={'max_width': 1080, 'max_height': 1080})) ]) image_800 = fields.ImageField(upload_to=img_800_dir_path, blank=True, name="image_800", dependencies=[ FileDependency(processor=ImageProcessor( format='PNG', scale={'max_width': 800, 'max_height': 800})) ]) image_350 = fields.ImageField(upload_to=img_350_dir_path, blank=True, name="image_350", dependencies=[ FileDependency(processor=ImageProcessor( format='PNG', scale={'max_width': 350, 'max_height': 350})) ]) My Forms.py class ImageAddForm(forms.ModelForm): class Meta: model = Images fields = ('name','alt_text','image_1080') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'alt_text': forms.TextInput(attrs={'class': 'form-control'}), 'image_1080': forms.ClearableFileInput(attrs={'class': 'form-file-input'}) } This saves only one image - 'image_1080' but not the other two. -
Querying model by ForeignKey to receive data in another ForeignKey?
I am having trouble running a query through a table that I built as basically a linkage type table to link Company and Package class CompanyPackageLink(models.Model): company = models.ForeignKey('business.Company', related_name='company_packages') package = models.ForeignKey('business.Package', related_name='packages') I am trying to query the CompanyPackage table by company and then retrieve all packages associates to that query. I have something like... company = Company.objects.get(employee=self.request.user) company_packages = CompanyPackageLink.objects.filter(company=company).select_related('package') Now this returns a correct quesyset, but it returns the CompanyPackage instance. <QuerySet [<CompanyPackageLink: companyA: PackageA>, <CompanyPackageLink: CompanyB: PackageB>]> I would like my query to return the actual Package model instance where I can retrieve name, price, etc. So I would like the returned queryset to actually return this.. <QuerySet [<Package: $100.00>, <Package: $200.00>]> Any help is appreciated! -
Adding a language field to the login template in Django
I have to start a project in Django, which should be able to translate in three languages (Spanish, English and Italian). I have the 3 languages defined within the settings.py file, as it looks: LANGUAGES = [ ('es', _('Español')), ('en', _('English')), ('it', _('Italiano')), ] My intention (I am not sure if it is the one indicated) is that when the user logs in, they enter their username, their password and the language with which they will work and from there the application establishes the menus, forms, etc. according to to the indicated language. My first approach was to extend the user model by incorporating a language field, as seen: class User(AbstractUser): language = models.CharField(max_length=10, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE) modifying the AUTH_USER_MODEL variable: AUTH_USER_MODEL = 'usuarios.User' and modify the login form, as it looks: class LoginForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #self.fields['username'].widget.attrs['autofocus'] = True class Meta: model = User fields = 'username', 'password', 'language' widgets = { 'username': forms.TextInput( attrs={ 'placeholder': 'Ingrese su username', } ), 'password': forms.PasswordInput(render_value=True, attrs={ 'placeholder': 'Ingrese su password', } ), 'language': forms.SelectMultiple(attrs={ 'class': 'form-control select2', 'style': 'width: 100%', 'multiple': 'multiple' }) } As well as, add one more field to the login template: <div class="form-group form-primary"> {{form.username|add_class:'formcontrol'|attr:'type:text'}} … -
How to re-display formset & Select2 field with selected value on form error in Django
After searching for several days and trying different options, I decided to finally post the issue and question. I have a template that has a form and 2 different formsets. One of the formsets uses an intermediate model with a GenericForeignKey that will reference two other models. For the formset, I am using an inlineformset and adding a CharField which is used with Select2 to make an ajax call to check the two other models. The value returned by the ajax call will be a json/dict with 3 key/value pairs. The issue I am having is that when the template is submitted and there are errors, how can I redisplay the value that was entered in the Select2 CharField when the template is presented again? The value is in self.data and is sent back to the template. However, everything I've tried so far will not redisplay the select2 field with the value selected previously or the values that were submitted. The submitted values are returned to the template in a json/dict, key/value, format under form.fieldname.value but I am not sure how I can use that to repopulate the select2 field. I appreciate any suggestions or links. If there is an … -
Django: return distinct set of many to many relationship belonging to a particular model
I want a query that returns all the distinct tags belonging to all the entries in Model A. I suspect it's possible with clever query and a bit of filtering, but I can't work it out. I want to minimise database hits. Models: class Tag(models.Model): name = models.CharField(max_length = 50,) category = models.CharField(max_length = 50, blank=True) class A(models.Model): ... tags = models.ManyToManyField(Tag, blank=True) class B(models.Model): ... tags = models.ManyToManyField(Tag, blank=True) My solution in the meantime is: tags = list() for a in A.objects.all(): for t in a.tags.all(): if t not in tags: tags.append(t) Is there an elegant solution to achieve the above functionality? -
Django subsequent StringAgg with grouping
I'm using Django with postgresql. I have 3 tables with m2m relations: movies, genres and persons. Each person can have it's own role as actor, writer, or director. ---------|----------|------|--------------| Dark Star|Sci-Fi |Actor |Brian Narelle | Dark Star|Sci-Fi |Writer|John Carpenter| Dark Star|Sci-Fi |Writer|Dan O'Bannon | Dark Star|Sci-Fi |Actor |Cal Kuniholm | Dark Star|Comedy |Actor |Brian Narelle | Dark Star|Comedy |Writer|Dan O'Bannon | Dark Star|Comedy |Actor |Cal Kuniholm |``` What i'm trying to reach is grouped by genres and persons name and concatenated name fields for each movie: ---------|--------------|------|---------------------------------------| Dark Star|Comedy, Sci-Fi|Actor |Brian Narelle, Cal Kuniholm, Dre Pahich| Dark Star|Comedy, Sci-Fi|Writer|Dan O'Bannon, John Carpenter |``` Using raw sql it's quite easy to reach just subsequently group and string_agg subqueries. from ( select t.title, string_agg(t.genre_name, ', ' ORDER BY t.genre_name) as genres, t.role, t.name from ( SELECT "movies_filmwork"."title", "movies_genre"."name" as "genre_name", "movies_person"."role", "movies_person"."name" FROM "movies_filmwork" LEFT OUTER JOIN "movies_filmwork_genres" ON ("movies_filmwork"."id" = "movies_filmwork_genres"."filmwork_id") LEFT OUTER JOIN "movies_genre" ON ("movies_filmwork_genres"."genre_id" = "movies_genre"."id") LEFT OUTER JOIN "movies_filmwork_persons" ON ("movies_filmwork"."id" = "movies_filmwork_persons"."filmwork_id") LEFT OUTER JOIN "movies_person" ON ("movies_filmwork_persons"."person_id" = "movies_person"."id") where "movies_filmwork"."title" = 'Dark Star' ) t group by t.title, t.role, t.name ) tt group by tt.title, tt.role, tt.genres order by tt.title, genres ;``` But i … -
create an appointment app with registered user and tomporary user in Django
I want to create an appointment app with Django with the following condition: doctors and reception can add appointments for registered patients patient who already register can add appointment only for them self doctors and reception can add appointments for non register patient(Temporary patient, for example) in the first and the 2nd condition, no need for adding information about the patient (because he adds them) in the 3rd doctor and reception have the ability to add information so my idea is whene the paitent is not register. create a tomprary user and the form (in template ) will add the option of adding more information this is my models.py file class User(AbstractUser): STATUS_CHOICES = (('paitent', 'paitent'), ('Doctor', 'Doctor'), ('reception', 'reception'), ('temporary', 'temporary')) STATUS_CHOICES_2 = (('yes', 'yes'), ('no', 'no')) type_of_user = models.CharField(max_length=200, choices=STATUS_CHOICES, default='paitent') allowd_to_take_appointement = models.CharField(max_length=20, choices=STATUS_CHOICES_2, default='yes') def is_doctor(self): if self.type_of_user == 'Doctor': return True else: return False def is_paitent(self): if self.type_of_user == 'paitent': return True else: return False def is_reception(self): if self.type_of_user == 'reception': return True else: return False def is_temporary(self): if self.type_of_user == 'temporary': return True else: return False def can_add_appointement(self): if self.allowd_to_take_appointement == 'yes': return True else: return False class Profile(models.Model): BLOOD_GROUPS = [ ('O-', 'O-'), … -
Anonymous user during google social authentication
I am using Django3.1.7 and Python3.9.0 to set up Google Social Login. Here is a snippet of my home view. class Home(APIView): def get(self, request, *args, **kwargs): authenticated = request.user.is_authenticated print("Authenticated: ", authenticated) print("User: ", request.user) return Response({"message": "Home"}, status=status.HTTP_200_OK) Here is a snippet of my AuthURL view. class AuthURL(APIView): @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): SCOPE = "profile+email" uri = ( "https://accounts.google.com/o/oauth2/v2/auth?response_type=code" "&client_id={}&redirect_uri={}&scope={}" ).format(CLIENT_ID, REDIRECT_URI, SCOPE) return Response({"uri": uri}, status=status.HTTP_200_OK) Here is a snippet of my Login view. class LoginView(APIView): @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): code = request.GET["code"] data = { "code": code, "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "redirect_uri": REDIRECT_URI, "grant_type": "authorization_code", } token = post("https://oauth2.googleapis.com/token", data=data) response = post("https://oauth2.googleapis.com/tokeninfo", data=token) data = response.json() user = User.objects.filter(email=data["email"]).first() if user is None: user = User.objects.create_user(email=data["email"], username=data["name"]) login(request, user) print("Request User: ", request.user) return redirect("http://localhost:3000/") App.js const logIn = () => { fetch("http://localhost:8000/accounts/get-auth-url/") .then((response) => response.json()) .then((data) => { window.location.replace(data.uri); }); } const home = () => { fetch("http://localhost:8000/accounts/home/") .then((response) => response.json()) .then((data) => { console.log(data); }); } return ( <div className="App"> <button type="button" onClick={logIn}>Log In</button> <button type="button" onClick={home}>Home</button> </div> ); … -
Django Rest Framework allauth Authentication credentials were not provided
I am using django allauth for authentication this is my settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], } the installed app are these: 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', and i am trying like way: curl -X POST "http://127.0.0.1:8000/api/v1/cinema-hall/" -H 'Authorizaion: Token 44eba1cdb1ecde6d3a55d6c85d7c4f44315f2c44' this error i am getting: {"detail":"Authentication credentials were not provided."} I see many similar post exist like this: Django Rest Framework Authentication credentials were not provided but those are not solved my issue. Can anyone tell me what is the possible reason of facing this error? -
Django collectstatic --no input Yes instead of no
I am using Django3 and i have currently the following command in my makefile for "Build" python3 manage.py collectstatic to automate my buildprocess with a pipeline i would like to get rid of the prompt that asks You have requested to collect static files at the destination location as specified in your settings: URL This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel i found that out that i can add "--no-input" for the collectstatic at the end, but this will answer "no" in this case. Is there a way how i could say the script to answer "Yes" by default instead? -
Django - AttributeError: type object 'HttpRequest' has no attribute 'GET'
I am trying to get input from a checkbox from a website to go through django. I have already been through stackoverflow and found someone doing the same thing but for some reason it doesn't work for me and I get an error telling me that there is no 'GET' attribute for HttpRequest even though it says there is on the django documentation. html: '' python: from django.http import HttpRequest hedgecutb = HttpRequest.GET.get("hedgecutb") error: hedgecutb = HttpRequest.GET.get("hedgecutb") AttributeError: type object 'HttpRequest' has no attribute 'GET' -
object get with mixin or def in models
is it possible to issue a get result, only with certain fields in models, and not all? where fields must be defined inside models, like def or mixin. something like clean_data if a method is requested view cls = Class.objects.get(related_uuid='xxx') you only need to display device and related_uuid, but define this in models.py itself, not in views.py models class Orders(models.Model): device = models.CharField(max_length=150) serial = models.CharField(max_length=150, blank=True) related_uuid = models.CharField(max_length=22, blank=True) -
mod_wsgi setup in production failed to start
I am deploying a django project in production using ubuntu, and I have been following this tutorial explaining how to setup and run mod_wsgi in production. Upon running apachectl start I get the following error apachectl start AH00526: Syntax error on line 53 of /etc/apache2/sites-enabled/django_project-le-ssl.conf: SSLCertificateFile: file '/etc/letsencrypt/live/www.dimsum.dk/fullchain.pem' does not exist or is empty Action 'start' failed. The Apache error log may have more information. Prior starting the apachectl I did the followings: pip install mod_wsgi The installation was successful and I then put mod_wsgi.server in my INSTALLED_APPS under settings.py. I then run without problem python manage.py runmodwsgi \ --server-root/etc/wsgi-port-80 \ --user www-data --group www-data \ --port 80 --setup-only Then I stopped my current apache2 server by sudo service apache2 stop Followed by /etc/wsgi-port-80/apachectl start and got the error AH00526: Syntax error on line 53 of /etc/apache2/sites-enabled/django_project-le-ssl.conf: SSLCertificateFile: file '/etc/letsencrypt/live/www.dimsum.dk/fullchain.pem' does not exist or is empty Action 'start' failed. The Apache error log may have more information.