Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I keep getting this "OperationalError at / (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)")" after django deploy
I keep getting this "OperationalError at / (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)")". I only turned DEBUG to True since to see what the error is and since I'm only the one currently accessing it. This is my first deployment of a django app. I've tried checking for the socket path, I can't find any folder called run. I think mysqld is in C:/Program Files/MySQL/MySQL Server 8.0/bin but when i tried setting C:\Program Files/MySQL/MySQL Server 8.0/bin/mysqld.mock it as my socket it didn't work either. I'd really appreciate the help -
How to use Exception in python?
I wrote code below. def get(self, request): ... try: ... ... food = Food.objects.get(food_id="red") if food: data = { "name" : food.name, } res.append(data) return JsonResponse({"success": res}, status=200) except Exception as e: return JsonResponse({"failed": e}, status=403) My intention is, I would like to go to exception and get 403 if there is no food. However, in this case, if there is no 'food' data, a 500 error (DoesNotExist) occurs. Why do I get this error? Am I misunderstanding the concept of exception? -
Django returns session id but doesn't authenticate user
I have the following code that sends requests to check JWT token, then authorize user and return authorized session with Access token, Refresh Token and Session ID. @csrf_exempt def new_login_view(request, *args, **kwargs): def convert_data(req): data = { "email": req.data['username'], "password": req.data['password'], } try: data["language"] = request.LANGUAGE_CODE except: data["language"] = request.POST.get('language', 'en') return data if request.user.is_authenticated and not request.META.get('HTTP_X_AVOID_COOKIES'): return HttpResponseRedirect(request.GET.get(KEY_NEXT, '/')) if request.method == 'POST': request_data = convert_data(request) # request to Accounts API to check if user exists response = send_service_request(EnumAuthUrls.sign_in.value, json_data=request_data, original_response=True) if isinstance(response, dict): return JsonResponse(response) if response.status_code == 200: tok_ac = response.headers.get(HEADER_ACCESS_KEY) tok_ref = response.headers.get(HEADER_REFRESH_KEY) # checking JWT token user = ApiAuthenticationBackend().authenticate(request, tok_ac) # creates session data = login_session(request, response, user) data['user_id'] = request.user.id data['account_id'] = request.user.profile.account_id data['balance'] = request.user.balance if request.META.get('HTTP_X_AVOID_COOKIES'): return JsonResponse(data) response = AuthResponse( data=data, ssid=request.session.session_key, access_token=tok_ac, refresh_token=tok_ref, ) return response else: return ErrorApiResponse(response.json()) service = urllib.parse.quote_plus(request.build_absolute_uri()) return HttpResponseRedirect(settings.ACCOUNTS_URL + f'login/?service={service}') Here's the code of login_session fucntion: def login_session(request: HttpRequest, response: HttpResponse, user): request.user = user request.session.create() base_data = response.json().get(KEY_DATA) return request.user.serialize(request, base_data, token=True) And here's the class AuthResponse that is eventually based on HttpResponse: class AuthResponse(SuccessResponse): def __init__(self, data={}, ssid='', access_token: str = '', refresh_token: str = '', **kwargs): super().__init__(data, **kwargs) if ssid: … -
Copy content from an html tag in a file to a tag in another html file
all in peace? In Django, I need the content of an HTML tag to appear in another template. Using the code JS: <script> var source = document.getElementById("teste").innerHTML; document.getElementById("texto").innerHTML = source; </script> <div id="teste">context</div> <div id="texto"></div> It even works in the same template, but if the destination tag is in another template, it doesn't work. Any idea? -
How to filter some words in a queryset
I have a variable, which contains stock symbols. I need to split each symbol, to compute it independently. print(Symbols_Splitted) #returns this ["'['AAPL", 'TSLA', "MSFT']'"] I need something to filter the relevant words, the pattern is always the same. I tried this, which works but I find out an issue. Some symbols have special characters in them like "EURUSD=X", and this code remove the "=" which makes it not valid. def convertor(s): perfect = re.sub('[^a-zA-Z]+', '', s) return perfect all = list(map(convertor, Symbols_Splitted)) So, by taking the first example I need something like this: Some_function(Symbols_Splitted) Symbols_Splitted[0] > AAPL Symbols_Splitted[1] > MSFT Symbols_Splitted[2] > TSLA -
I have a problem importing openai in Django for web application purposes
My python version is able to run open ai on its own, but when I tried to integrate it with Django I ran into the following issue: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1031, in _bootstrap_inner self.run() ^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 968, in run self._target(*self._args, **self._kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run self.check(display_num_errors=True) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: ^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/urls/resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/urls/resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked … -
setting up and processing 2 modelforms with the same FormView class
I am trying to use a single FormView class to render and process two related but different ModelForms. One of the forms has FileInput as one of its fields and it is not submitting properly when I click the respective button. views.py class MyView(LoginRequiredMixin, FormView): template_name = "tmp.html" http_method_names = ["get", "post"] login_url = "/to/login" form_class = AForm success_url = reverse_lazy("profile") def get_context_data(self, **kwargs): context = super(MyView, self).get_context_data(**kwargs) prf = ModelA.objects.get(id=self.request.user.id) context["form_a"] = AForm(instance=prf) context["form_b"] = BForm(instance=None) return context def post(self, request, *args, **kwargs): if "submit_a" in request.POST: self.form_class = AForm if "submit_b" in request.POST: self.form_class = BForm return super().post(request, *args, **kwargs) def form_valid(self, form): if self.form_class == AForm: form.save() elif self.form_class == BForm: form.save() return super().form_valid(form) The related forms.py for ModelA looks something like this: class AForm(ModelForm): img_field = ImageField(widget=FileInput) Two issues I'm currently having: When the form loads and the user clicks the submit button with previous data, I'm getting <ul class="errorlist"><li>img_field<ul class="errorlist"><li>This field is required.</li></ul></li></ul> when I check form.errors. When the user selects an image to upload and clicks submit (submit_a), I'm getting IntegrityError on the id (user id) column which is returning null. I assume that since I am sending a specific user instance to the … -
Django, How to clear the previous data model thoroughly?
I'm viewing my admin site, but in the Add Groups page, I can still see the available permissions that I have deleted before. and in my models.py I haven't configured any of these table yet. Does this mean I didn't clear my database thoroughly? Is there any way to delete all of these, just leave the permissions I have in this list? Thank you! -
get a specific variable from a queryset
I'm trying to get a specific part of the cd output, but my code is not working. I'm trying to define a new variable, with only the object 'symbols' from the Queryset output. if cmd_exec == '/wanalysis': get_Memory = Memory.objects.filter(user=current_user).values() cd = get_Memory.all() X = cd['{id}'] print(X) This is the output for print(cd) <QuerySet [{'id': 183, 'user_id': 1, 'raw_message': '/setworkspace AAPL TSLA MSFT 12/12/2018 12/12/2022', 'date1': '2018-12-12', 'date2': '2022-12-12', 'symbols': "['AAPL', 'TSLA', 'MSFT']"}]> I would like to define a variable X, with the 'symbols' output from the QuerySet. So something like: X = cd['symbols'] -
Python/Django -> Gunicorn error: ModuleNotFoundError: No module named '<project directory>'
I'm trying to deploy a django application with Gunicorn and Nginx on Ubuntu server, but I'm getting this "ModuleNotFoundError". Can anyone help me out with this, please? The files gunicorn_myproject.socket [Unit] Description=myproject socket [Socket] ListenStream=/run/gunicorn_myproject.sock [Install] WantedBy=sockets.target gunicorn_myproject.service [Unit] Description=myproject daemon Requires=gunicorn_myproject.socket After=network.target [Service] User=myuser Group=www-data WorkingDirectory=/home/myuser/github/myproject ExecStart=/home/myuser/github/venvs/myproject/bin/gunicorn \ --access-logfile - \ --workers 5 \ --bind unix:/run/gunicorn_myproject.sock \ /home/myuser/github/myproject/MyProject.wsgi:application [Install] WantedBy=multi-user.target The error log: When I run sudo systemctl start gunicorn.socket then sudo systemctl status gunicorn.socket: ● gunicorn_myproject.socket - myproject socket Loaded: loaded (/etc/systemd/system/gunicorn_myproject.socket; enabled; vendor preset: enabled) Active: active (listening) since Tue 2023-01-31 18:43:11 -03; 1s ago Triggers: ● gunicorn_myproject.service Listen: /run/gunicorn_myproject.sock (Stream) CGroup: /system.slice/gunicorn_myproject.socket Jan 31 18:43:11 cpro49739 systemd[1]: Listening on myproject socket. Nothing wrong yet, so then I run curl --unix-socket /run/gunicorn_myproject.sock localhost and get: curl: (56) Recv failure: Connection reset by peer Then I run sudo systemctl status gunicorn.service aaaand: ● gunicorn_myproject.service - myproject daemon Loaded: loaded (/etc/systemd/system/gunicorn_myproject.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2023-01-31 18:47:29 -03; 1min 33s ago TriggeredBy: ● gunicorn_myproject.socket Process: 2539537 ExecStart=/home/myuser/github/venvs/myproject/bin/gunicorn --access-logfile - --workers 5 --bind unix:/run/gunicorn_myproject.sock /home/myuser/github/myproject/MyProject.wsgi:application (code=exited, status=3) Main PID: 2539537 (code=exited, status=3) Jan 31 18:47:29 cpro49739 gunicorn[2539539]: ModuleNotFoundError: No module named '/home/myuser/github/myproject/MyProject' Jan 31 … -
UpdateView form_valid is not redirecting as expected - keeps saying form_valid?
I've got a Django UpdateView that I am trying to test against. The UpdateView only accepts post requests, handles the form and redirects the user appropriately depending how the form submission went. The test fails, but if I run the local server, it works as I would expect. I'm not sure if it's an indication that my test is setup wrong - or if the test is exposing some weird bug. My view looks like this: class TressleUpdateView(UpdateView): http_method_names = ["post"] form_class = TressleForm model = Tressle pk_url_kwarg = "tressle_id" raise_exception = True def form_valid(self, form): """ This method is called when valid form data has been POSTed. We set the updated_by to the requestor to know who updated this. """ # Ensure the tressle is at a point to be finalized # If not, add a message informing the user that the tressle is not # complete, and redirect to the summary detail page. if form.instance.progress() < 100: messages.error( self.request, _( "The tressle is not complete. Please ensure that all " "requirements have been met." ), ) return redirect( reverse_lazy( "myapp:tressle-detail", kwargs={ "tressle_id": self.kwargs["tressle_id"], }, ) ) # Get the requestor Person object request_person = get_object_or_404( Person, id=self.request.user.person_id ) … -
How can I install React and Python packages on a single DigitalOcean App?
I have a Django project with a ReactJS application (index.html) directly integrated into the Django template system. This is an alternative way of integrating Django and React where you can have shared authentication and have your React app seamlessly display within the template (look and feel) of the Django website. One issue you must overcome is getting your DigitalOcean environment built so that it includes all the packages and dependencies for Python, Django, and NodeJS/React. The DigitalOcean platform does not include any specific instructions on accomplishing this complete setup. I've struggled to find answers here too. -
django.db.utils.OperationalError 3780 - Referencing column and referenced column "id" in foreign key constraint are incompatible
After reading this django.db.utils.OperationalError: 3780 Referencing column and referenced column are incompatible and SQLSTATE[HY000]: General error: 3780 Referencing column 'user_id' and referenced column 'id' in foreign key are incompatible I have two models in Django 3.2.16 declared in different apps, it's a long time project which started in Django 2.2 and was upgraded over time. Here are the two model classes: from city_search.models class Città(models.Model): nome = models.CharField(max_length = 50, db_index = True) def __str__(self): return "{} - {}".format(self.nome,self.regione) provincia = models.ForeignKey(Provincia, models.SET_NULL, blank=True,null=True) capoluogo = models.BooleanField(default=False) regione = models.ForeignKey(Regione, models.SET_NULL, blank=True,null=True, related_name='comuni') slug = models.SlugField(null=True) latlng = LocationField(null=True,map_attrs={"center": [2.149123103826298,41.39496092463892], "zoom":10}) from eventos.models instead, which I'm developing from schedule.models import events class Manifestazione(events.Event): ciudad = models.ForeignKey('city_search.Città', on_delete=models.CASCADE, verbose_name='Ciudad', related_name='manifestaciones', blank=False, null=False) The migration of the latter model fails with the following error: django.db.utils.OperationalError: (3780, "Referencing column 'ciudad_id' and referenced column 'id' in foreign key constraint 'eventos_manifestazio_ciudad_id_74f49286_fk_city_sear' are incompatible.") these two models declarations translate to the following MySQL tables (the second is only partially created by the faulty migration) mysql> describe city_search_città; +--------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+-------------+------+-----+---------+----------------+ | id | int | NO | PRI | NULL | auto_increment | | … -
Issues deploying Django app to AWS web server
I would like to complete the Django first app but instead of accessing it via the local host on my machine. Id like to access it through a free tier on AWS. This is for an Education tool I am presenting to a class. Im wondering if anyone has done this, or if there is any videos/guides for this? I would also like to have a number of students working on this as well so it would be great if there was also a guide for explaining to the students how to use Docker, pull the container to their local machines (all students will be using VSC as their IDE). The end goal is for the base app to be developed on their local machines (macOS/Windows/Linux etc). When they commit their code to the repo, for it to deploy to an AWS web sever (free educational tier account) for them to see their changes. Then if the changes are good, they can deploy to the "production" server. If these are not the normal steps of the deployment pipeline, might someone clarify for me? Thanks for any assistance! -
Where to define custom data handling for a m2m field in django
Let's say for example I want the many to many 'tags' modelfield to be inputted as a space-separated list, were an unrecognized name be submitted it should also be created in the 'Tag' model. I'm aware this could be written either at: View level Form level FormField level ModelField level I want to adhere to the DRY principle as tightly as possible. For the time being I have defined it at ModelForm level but my setup is not very flexible. I would have to write new forms for every variation in each part of the website I place this formfield in. -
Update table every time my database is changed [HTMX][Dajngo-tables2]
I want to Update table every time my database is changed, without refreshing. Also, I want to keep my quarry parameters from a search when the update happens What I done so far is use hx-get to retrieve my table from another template and view to get me the updated table. However, I don't know where to start to trigger a update when the database is changed Views.py def display_view(request): myFilter = ParticipantFilter(request.GET, queryset=Participant.objects.all()) table = ParticipantTable(myFilter.qs) table.paginate(page=request.GET.get("page", 1), per_page=10) return render(request, 'display.html', {'table': table,'myFilter': myFilter}) def data_only_view(request): myFilter = ParticipantFilter(request.GET, queryset=Participant.objects.all()) table = ParticipantTable(myFilter.qs) table.paginate(page=request.GET.get("page", 1), per_page=10) return render(request, 'updatedDisplay.html', {'table': table}) display.html {% extends "base.html" %} {% block content %} <form method="get"> {{ myFilter.form }} <button type="submit">Search</button> </form> <div id="table-results" hx-get="/updatedDisplay" hx-include = "[name='first_name']"> {% load render_table from django_tables2 %} <table class="table"> {% render_table table %} </table> {% endblock %} </div> updateDisplay.html {% load render_table from django_tables2 %} <table class="table"> {% render_table table %} </table> -
How to capture all the options user selected in a webpage and pass it to the backend using JavaScript?
I have a requirement to capture all the options which the user has selected and pass them to the backend(view in Django. There are text boxes and Radio buttons on the web page user has to select the options, and on click of a save button based on user selections, I have to initiate the process in the backend. -
Django REST: make request.session['key'] available on all views
I'm trying to check if a user logged in saving a token in request.session["token"]. On login, the request.session["token"] is set and the print() works. How do I make that key available on all views? @api_view(['POST']) def login(request): if request.data["usuario"] and request.data["pwd"]: try: user_item = User.objects.get(usuario=request.data["usuario"]) except User.DoesNotExist: return Response({'errors': 'Usuario no existe'}, status=402) usr_pwd = request.data["pwd"] bd_pwd = user_item.pwd if bcrypt.checkpw(usr_pwd.encode('utf-8'),bd_pwd.encode('utf-8')): token = jwt.encode({'user': request.data["usuario"]}, 'palacin', algorithm='HS256') request.session["token"] = token print(request.session["token"]) # <-- THIS PRINT WORKS return Response(200) else: return Response({'errors': 'Usuario y/o contraseña incorrectos.'}, status=401) else: return Response({'errors': 'Usuario y/o contraseña no especificados'}, status=400) @api_view(['POST']) def getUser(request): print(request.session["token"]) # <-- THIS PRINT DOESN'T WORK '''if "token" in request.session: return Response(jwt.decode(request.session["token"], 'palacin', algorithms=['HS256'])) else: return Response({'errors': 'Sesión no iniciada'}, status=403)''' -
Django restframework can't get post data with a multipart parser
i am trying to save an object with an image using django restframework but when i use the FormParser and MultiPartParser classes the request.data object get seemingly encoded msgs and when i try to decode using utf-8 it outputs an error saying this data is not utf-8 i want to have access to the request.data data and be able to save the image for future requests here is my view function: @parser_classes([FormParser, MultiPartParser]) @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) def products(request): if request.method == 'POST': print(request.data) serializer = ProductSerializer(data=request.data) serializer.initial_data['user'] = request.user.pk serializer.initial_data['price'] = float( request.data['price']) serializer.initial_data['quantity'] = int( request.data['quantity']) if serializer.is_valid(): serializer.save() return Response({'message': "product added"}, status=status.HTTP_201_CREATED) else: print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my front end code: export const addProduct = async (product) => { const fd = new FormData(); fd.append("name", product.name); fd.append("price", product.price); fd.append("quantity", product.quantity); fd.append("image_url", product.image_url); console.log(product.image_url) //this prints a file object const response = await fetch(`${URL}/products`, { method: "POST", headers: { "Content-Type": `multipart/form-data; boundary=${fd._boundary}`, }, body: fd, }) return response } -
How do I refresh the Google access token with Django allauth?
The access token for google typically lasts 1 hour. How do I refresh the token without having the user login again? github code for project: https://github.com/theptrk/learn_gcal django-allauth Google login is set up the normal way with an added scope THIRD_PARTY_APPS = [ # ... "allauth.socialaccount", "allauth.socialaccount.providers.google", # This allows you to assign a site to a "social application" SITE_ID = 1 SOCIALACCOUNT_PROVIDERS = { "google": { "SCOPE": [ # minimum scopes "profile", "email", # additional scopes "https://www.googleapis.com/auth/calendar.readonly", ], "AUTH_PARAMS": { "access_type": "offline", }, } } # https://django-allauth.readthedocs.io/en/latest/configuration.html # Use this for additional scopes: This defaults to false SOCIALACCOUNT_STORE_TOKENS = True Creating the credentials is different than the docs since the docs use a "secrets file" instead of getting tokens from the db # get user and client credentials token = SocialToken.objects.get( account__user=request.user, account__provider="google" ) client_id = env("GOOGLE_CLIENT_ID", default="") client_secret = env("GOOGLE_CLIENT_SECRET", default="") # create Credentials object from google.oauth2.credentials import Credentials creds=Credentials( token=token.token, refresh_token=token.token_secret, token_uri="https://oauth2.googleapis.com/token", client_id=client_id, client_secret=client_secret, ) Trying to retrieve events is totally fine if the access token is not expired # retrieve google calendar events from googleapiclient.discovery import build from datetime import datetime service = build("calendar", "v3", credentials=creds) try: events_result = ( service.events() .list( calendarId="primary", timeMin=datetime.now().date().isoformat() + "Z", maxResults=30, … -
CSRF verification failed. Request aborted in http URL
In my login showing error when submit the form in http url but https url working fine. my login form is ` {% csrf_token %} Please log in Or click here to register {% if msg %} Error Invalid credentials or inactive account. If you have registered please make sure to activate your account by clicking on the link sent to your email address. Please check your spam folder if you are unable to find the email. {% endif %} <input type="text" class="form-control" name="email" placeholder="Email Address" required="" autofocus="" ng-model="loginEmail"></input> <input type="password" class="form-control" name="password" placeholder="Password" required="" ng-model="loginPwd"></input> <button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login(loginForm.username.$viewValue, loginForm.password.$viewValue)">Log in</button> </form>` localhost working proper this code but live site not working in http. Also i add {% csrf_token %} in login form please someone help me! -
Django: how to take input as range and store it in the database?
I am beginner in django and thinking to create a website that asks the user for input (the input here is an hour range) and store it in the data base e.g. A slider that ranges from 5am till 9pm the user can set the start and end for example 7am-9am and submit it and then it will be stored in the database I am not sure how to appriach it also how will it be stored in the database as a single entry or multiple entries your help is much appreciated I have been trying continuously to search for tutorials, vidoes, articles, even any piece of information here and there that could give me the kickstart but I failed -
Pass data from the pipeline to views in Django Python Social Auth
I was reading the documentation of Python Social Auth and got curious about the section of Interrupting the Pipeline (and communicating with views). In there, we see the following pipeline code In our pipeline code, we would have: from django.shortcuts import redirect from django.contrib.auth.models import User from social_core.pipeline.partial import partial # partial says "we may interrupt, but we will come back here again" @partial def collect_password(strategy, backend, request, details, *args, **kwargs): # session 'local_password' is set by the pipeline infrastructure # because it exists in FIELDS_STORED_IN_SESSION local_password = strategy.session_get('local_password', None) if not local_password: # if we return something besides a dict or None, then that is # returned to the user -- in this case we will redirect to a # view that can be used to get a password return redirect("myapp.views.collect_password") # grab the user object from the database (remember that they may # not be logged in yet) and set their password. (Assumes that the # email address was captured in an earlier step.) user = User.objects.get(email=kwargs['email']) user.set_password(local_password) user.save() # continue the pipeline return and the following view def get_user_password(request): if request.method == 'POST': form = PasswordForm(request.POST) if form.is_valid(): # because of FIELDS_STORED_IN_SESSION, this will get copied # … -
How to fix 'qr_code' is not a registered tag library. in Django and HTML
How to fix 'qr_code' is not a registered tag library. I use Django version 4.1.4. setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'qrcode', ] In setting.py, if I use qr_code instead of qrcode, this error will occur ModuleNotFoundError: No module named 'qr_code'. It will display the error 'qr_code' is not a registered tag library. {% load qr_code %} {% qr_from_text request.build_absolute_uri size="T" image_format="png" error_correction="T" %} In HTML, how should I edit? Command I used to install django-qr-code 3.1.1 pip install django-qr-code And I tried installing it with conda after trying it in pip and it didn't work. conda install -c auto django-qrcode -
Django order model by date and move models without date to the end
I have a model tickets, with a sum in it. I'm trying to make spending tickets by nearest expire date. But if I'm ordering by date_expire, it move date_expire=None models to the top. But date_expire=None means that ticket has no limit by time, and should be used after all tickets, that has time limit. My code: ticket = Tickets.objects.filter( sum__gte=0, date_expire__gte=timezone.now(), user_id=user.id, burned=False ).order_by( 'date_expire' ).first() I can try to sort by sorted func with lambda key, but I think there's a better way to do this in orm