Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Datefield after Today and Before another date not returning the expected object
I am writing an app in Django where I have created a PayPeriods model as such: class PayPeriods(models.Model): first_day = models.DateField(default=date.today) last_day = models.DateField(default=date.today) pay_day = models.DateField(default=date.today) I've created a small function that allows me to get the current PP through my app, def get_pp(): _pp = PayPeriods.objects.filter(first_day__gte=datetime.today())[0] return _pp but its not returning as expected. What am I missing? Current day today is 11/29/2022, so I am expecting to return Obj #4, as the code is written. PP Object #3: first_day = 11/13/22, last_day = 11/26/22 PP Ojbect #4: first_day = 11/17/22, last_day = 12/10/22 PP Ojbect #5: first_day = 12/11/22, last_day = 12/24/22 I have verified that my dates are formatted the same way, (stored data & datetime.today(), and my timezone settings are correct.). -
How to set a logic that only event attendant can give review regarding an event in drf?
i'm new in drf i'm managing event management system, i tried to count event attendees and only event attendees can review about event. i facing issue to in review model. i manage attendees in Event model with ManyToManyField. here my models , class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="event_user") attendees = models.ManyToManyField(User, blank=True, related_name='attendees_user') venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='venue_user') event_type = models.CharField(max_length=50, choices=event_type) event_name = models.CharField(max_length=25) start_time = models.DateTimeField(blank=False, null=True) end_time = models.DateTimeField(blank=False, null=True) def __str__(self): return f'{self.venue} - {self.event_name}' class Reviews(models.Model): reviewer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="reviewer_user") event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name="event") review = models.TextField() class Meta: verbose_name_plural = "Reviews" def __str__(self): return f'{self.reviewer} -- {self.review} -- {self.event}' here my serializers class EventSerializer(serializers.ModelSerializer): images = serializers.ListField( child=serializers.FileField(allow_empty_file=True, use_url=True, ), required=False) class Meta: model = Event fields = ( 'id', 'user', 'attendees', 'venue', 'event_type', 'event_name', 'start_time', 'end_time', 'images') def create(self, validated_data): uploaded_data = validated_data.pop('images') attendees = validated_data.pop('attendees') instance = Event.objects.create(**validated_data) instance.attendees.set(attendees) instance.save() for pics in uploaded_data: EventImages.objects.create(event=instance, event_pics=pics) return instance def to_representation(self, instance): response = super(EventSerializer, self).to_representation(instance) response["venue_name"] = instance.venue.venue_name response["start_time"] = instance.start_time.strftime("%d/%m/%Y, %H:%M:%S") response["end_time"] = instance.end_time.strftime("%d/%m/%Y, %H:%M:%S") return response def validate(self, data): if data.get("start_time") > data.get("end_time"): raise serializers.ValidationError("'End time' must be after 'Start time'.") else: pass if Event.objects.filter( (Q(venue=data['venue']) & … -
How do I test views in Django Rest Framework that make calls to other apis/ google earth engine
A lot of views on my project makes http requests to other services, and one of the views makes a call to google earth engine service. How do I go about testing these components? Should I just let them make the calls and make my tests depend on an internet connection? Is there a design structure in which I can choose to mock the request data? -
Update is creating new entry rather than updating it
I have a model where users save their details. I am able to save user details through the template I have created. But whenever I edit the data to update it, a new entry is created in database models.py class User(AbstractUser): pass def __str__(self): return self.username class Detail(models.Model): """ This is the one for model.py """ username = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default="") matricno = models.CharField(max_length=9, default="") email = models.EmailField(default="") first_name = models.CharField(max_length=200, default="") last_name = models.CharField(max_length=255, default="") class Meta: verbose_name_plural = "Detail" def __str__(self): return self.first_name+ " "+self.last_name views.py @login_required(login_url="signin") def details(request): form = Details() if request.method == "POST": form = Details(request.POST) if form.is_valid(): detail = form.save(commit=False) detail.username = request.user detail.save() return redirect(success, pk=detail.pk) else: form = Details(initial={"matricno":request.user.username}) return render(request, "details.html", {"form":form}) def success(request,pk): return render(request, "success.html", {"pk":pk}) def updatedetails(request, pk): detail = Detail.objects.get(id=pk) form = Details(instance=detail) if request.method == "POST": form = Details(request.POST, instance=detail) if form.is_valid(): form.save() return redirect(success, pk=detail.pk) return render(request, "details.html", {"form":form}) urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("details/", views.details, name="details"), path("success/<int:pk>/", views.success, name="success"), path("edit/<int:pk>/", views.updatedetails, name="updatedetails"), ] The template used for rendering out the form to input user details goes as follows <!DOCTYPE html> <html lang="en"> <head> … -
Get values of Enum fields from Django Queryset
I have a model with an enum column, e.g. from django_enum_choices.fields import EnumChoiceField class Service(Enum) MOBILE: "MOBILE" LAPTOP: "LAPTOP" class Device(models.Model): service = EnumChoiceField(Service) ... Is it possible to get get the query results with the enumerated column being the value of the enum? For example: If I do: query = Device.objects.values("service") print(query) I get: <QuerySet [{'service': <Service.MOBILE: 'MOBILE'>}, {'service': <Service.MOBILE: 'MOBILE'>}, {'service': <Service.LAPTOP: 'LAPTOP'>}]> I wish to get: <QuerySet [{'service': 'MOBILE'}, {'service': 'MOBILE'}, {'service': 'LAPTOP'}]> I get errors when I run: query = Device.objects.values("service__value") or query = Device.objects.values("service.value") I want to something like how we can get value of an enum field by saying mobile_service = Service.MOBILE # <Service.MOBILE: "MOBILE"> mobile_service_as_string = mobile_service.value # "MOBILE" The errors: django.core.exceptions.FieldError: Cannot resolve keyword 'value' into field. Join on 'service' not permitted. django.core.exceptions.FieldError: Cannot resolve keyword 'service.value' into field. Choices are: service, .. -
Django Selenium Parsing Data
How can return WebDriver=auth in function parameters? I have a task.py file in which, first, in the login function, I use Selenium to log in to my personal account, then the form_fill function receives the Url parameters in which the form is filled, and the WebDriver and returns the data and the driver. I'm trying in views.py to first call the login function for authorization and return the WebDriver to another form_fill function. task.py def login(url): driver = webdriver.Chrome(service=service,options=options) driver.maximize_window() driver.get(url) driver.find_element(By.ID,"login").send_keys(LOGIN) driver.find_element(By.ID,"password").send_keys(PASSWORD) driver.find_element(By.ID,'bind').click() return driver def form_fill(url_pars,driver,name_flat): driver.get(url_pars) driver.find_element(By.ID,"epd_field").click() codplat=driver.find_element(By.CLASS_NAME,"home_right").text driver.find_element(By.XPATH,'//span[contains(text(),"name_flat}")]'.format(name_flat)).click() driver.find_element(By.CLASS_NAME,"js-find-btn").click() driver.find_element(By.CLASS_NAME,"js-more-btn").click() driver.find_element(By.CLASS_NAME,"btn-close-pop").click() return [driver,codplat] views.py class AuthView(TemplateView): template_name="mos_sel/login.html" def get_context_data(self, **kwargs) : context=super().get_context_data(**kwargs) # login(URL_LOGIN) return WebDriver in auth auth=login(URL_LOGIN) return context views.py class PaymentListView(AuthView,ListView): template_name='mos_sel/parse_list.html' model=Flat context_object_name='fields' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['name_flat']=Flat.objects.get(pk=self.kwargs['pk']).name_flat # How get WebDriver in parameters call form_fill function forma_fill=form_fill(GET_USLUGA_URL,auth,context['name_flat'].upper()) return context login.html {% extends "base.html" %} {% block content %} <h3>Enter for authorization</h3> <a href="{% url 'AuthView' %}"><button type="button" class="btn btn-success">Enter</button></a> {% endblock content %} parse_list.html {% extends "base.html" %} {% block sidebar %} <h5>{{name_flat}}</h5> {% for field in fields %} {{field.cod_platelshika}} {{field.period_oplaty}} {{field.summa}} {% endfor %} {% endblock sidebar %} I want get WebDriver in function fill_form parameters -
Render multiple models with pk in a single view
I'm trying to pass lesson.price, and lesson.invoice_id from Lesson model and student.student_id from Student Model into the single view so that I can display them in a template. However, Lesson model has a field "student" which has a foreign key to User, not to Student model. You will see my code for view class is wrong since I have no clue how to get a proper student object with a primary which is used for lesson object. How could I get a proper student object with lesson_id primary key in view class? class User(AbstractUser): '''User model for authentication and lessons authoring.''' class Role(models.TextChoices): ADMIN="ADMIN",'Admin' STUDENT="STUDENT",'Student' TEACHER="TEACHER",'Teacher' id = models.AutoField(primary_key=True) username = models.CharField( max_length=30, unique=True, validators=[RegexValidator( regex=r'^@\w{3,}$', message='Username must consist of @ followed by at least three alphanumericals.' )] ) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True, blank=False) gender = models.CharField(max_length=255) address = models.TextField(default='') baseRole = Role.ADMIN role = models.CharField(max_length=50, choices=Role.choices) created_at = models.DateTimeField(default=timezone.now, blank=True) updated_at = models.DateTimeField(default=timezone.now, blank=True) def save(self, *args, **kwargs): self.role = self.baseRole return super().save(*args, **kwargs) def __str__(self): return self.first_name+" "+self.last_name class Student(User): student_id = models.CharField(max_length=10, default=uuid.uuid4) baseRole = User.Role.STUDENT student = StudentManager() class Lesson(models.Model): lesson_id = models.AutoField(primary_key=True) lesson_name = models.CharField(max_length=255) student = models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name='studying', unique=True) teacher … -
Is it possible to pass command line arguments to a decorator in Django?
I have a decorator that is supposed to use a parameter that's passed in from the commandline e.g @deco(name) def handle(self, *_args, **options): name = options["name"] def deco(name): // The name should come from commandline pass class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( "--name", type=str, required=True, ) @deco(//How can I pass the name here?) def handle(self, *_args, **options): name = options["name"] any suggestions on this? -
How to show a field seperately in drf
I have Reviews & Ratings serializer. I want to show the total count of reviews in response. The current implementation I am getting review count but it shows on all review response like below: [ { "review_count": 2, "user": "don sebastian", "rating": 3.9, "review": "Rating for pendant 1 by Don", "created_at": "2022-11-27", "updated_at": "2022-11-27" }, { "review_count": 2, "user": "Jackson Patrick Gomez", "rating": 4.5, "review": "cool review Pendant 1", "created_at": "2022-11-27", "updated_at": "2022-11-29" } ] What I want to get is like this review_count seperatley [ "review_count": 2, { "user": "don sebastian", "rating": 3.9, "review": "Rating for pendant 1 by Don", "created_at": "2022-11-27", "updated_at": "2022-11-27" }, { "user": "Jackson Patrick Gomez", "rating": 4.5, "review": "cool review Pendant 1", "created_at": "2022-11-27", "updated_at": "2022-11-29" } ] #Serializer.py class ReviewSerializer(ModelSerializer): user = SerializerMethodField() review_count = SerializerMethodField() class Meta: model = ReviewRatings fields = ["review_count", "user", "rating", "review", "created_at", "updated_at"] def get_user(self, obj): return f"{obj.user.first_name} {obj.user.last_name}" def get_review_count(self, obj): -
Web page I am scraping requires credit card details to work. Any idea how I can keep my credit card info secure?
Hello I have a Django/postgres backend service that starts jobs with my webscraper service running puppeteer/express. Additionally, all these services are running on Dokku. The webscraper goes and purchase products from websites and thus need to enter my credit card number each time. Kind of scared about storing my credit card number some where and what service to give it to. I have never done this before. Should have I just hash the credit card number and store it in an environment variable or is there any better ideas? -
Software for creating interactive forms [closed]
my problem is in relation with structuring text. i am searching for a opportunity that helps me structuring text. It should be able to create a fillable form and generate an PFD out of this. Hope you have any idea... -
Problem of signature with webauthn on django with djoser
I'm working at the moment on an implementation of webauthn on a project. The main point is to give the possibility to user to use FaceId or fingerprint scan on their mobile on the website. I tried the djoser version of webauthn but I wanted to give the possibility to user that already have an account so I took the implementation of webauthn of djoser and I updated it to make it working with already created account. I can ask for the signup request of a webauthn token and create the webauthn token with the front (Angular) where I use @simplewebauthn/browser ("@simplewebauthn/browser": "^6.3.0-alpha.1") . Everything is working fine there. I use the latest version of djoser by pulling git and the version of webauthn is 0.4.7 linked to djoser. djoser @git+https://github.com/sunscrapers/djoser.git@abdf622f95dfa2c6278c4bd6d50dfe69559d90c0 webauthn==0.4.7 But when I send back to the backend the result of the registration, I have an error: Authentication rejected. Error: Invalid signature received.. Here's the SignUpView: permission_classes = (AllowAny,) def post(self, request, ukey): co = get_object_or_404(CredentialOptions, ukey=ukey) webauthn_registration_response = WebAuthnRegistrationResponse( rp_id=settings.DJOSER["WEBAUTHN"]["RP_ID"], origin=settings.DJOSER["WEBAUTHN"]["ORIGIN"], registration_response=request.data, challenge=co.challenge, none_attestation_permitted=True, ) try: webauthn_credential = webauthn_registration_response.verify() except RegistrationRejectedException as e: return Response( {api_settings.NON_FIELD_ERRORS_KEY: format(e)}, status=status.HTTP_400_BAD_REQUEST, ) user = User.objects.get(username=request.data["username"]) user_serializer = CustomUserSerializer(user) co.challenge = … -
Django json response stay in the same page
I'm making a like button for a post in django. What I need is that when the like button is clicked, the function is executed, but I need the page not to be reloaded (To later use javascript). To do that I return a jsonresponse() instead of a return render. But the real problem is that it redirects me to the page that I show in the photo. The page is not reloaded. as I want it. but I don't want it to show me the blank page with the jsonresponse data (like this photo).I want to stay in the same page without reload. Thanks in advance! My view function: def liking (request, pk): posts = get_object_or_404(Post, id = pk) if request.user in posts.likes.all(): posts.likes.remove(request.user) else: posts.likes.add(request.user.id) likes_count = posts.likes.all().count() print(f'likes_count = {likes_count}') data= { 'likes_count': likes_count, } #return redirect ('index')# This is commented return JsonResponse(data, safe=False, status=200 ) -
Products are not displayed when simple search on django
I do search on Django and faced with a problem: products are not displayed. I dont understand why views class SearchView(ListView): template_name = 'store/products.html' def get_queryset(self): query = self.request.GET.get('search', '') if query: products = Product.objects.filter(Q(name__icontains=query) | Q(description__icontains=query)) else: products = Product.objects.all() return products search template <form class="form-inline mb-3" action="{% url 'search' %}" method="get"> <div class="form-group col-8 col-md-10 pl-0"> <input class="form-control w-100" type="search" placeholder="Поиск по сайту" name="search"> </div> <div class="form-group col-4 col-md-2 pl-0"> <button class="btn btn-info" type="submit">Найти</button> </div> </form> products template {% extends 'base.html' %} {% block title %} List {% endblock %} {% block content %} <body style="background-color: whitesmoke;"> {% for product in products %} <main class="container mt-3" style="text-align: center; max-width: 500px;"> <div style="border: 5px solid white; background-color: white;"> <a href="{% url 'product_detail' product.id %}"> <img src="{{ product.image.url }}" style="width:15vh; height:auto;"><br> </a> <p style="font-size: 20px">{{ product.name }}</p> <p style="font-size: 22px">{{ product.price }} руб.</p> <form method="post" action="{% url 'cart_add' product.id %}"><br> <p style="display: none"></p> {{ form }} {% csrf_token %} {% if request.user.is_authenticated %} <input type="submit" value="Add to cart"> {% else %} <p></p> {% endif %} </form> </div> </div> </div> </main> {% endfor %} </body> {% endblock %} I did the same search and all good. I think problem with templates … -
create Model objects inside another models's Adminview
I'm trying to generalize access permissions to certain Nodes for each of my Groups. I have an Access Model model with three different fields: access_type, group and node. Each group can have either Source, Destination or Bidirectional Access to a node which has a name: class Access(models.Model): class AccessType(models.TextChoices): BIDIRECTIONAL = "bi", "Bidirectional" SOURCE = "src", "Source" DESTINATION = "dst", "Destination" access_type = models.CharField(max_length=3, choices=AccessType.choices) group = models.ForeignKey(Group,on_delete=models.CASCADE, related_name='GroupAccess') node = models.ForeignKey(DicomNode, on_delete=models.CASCADE) name = models.CharField(unique=True, max_length=128, null = True) Similar to the common permission view inside the adminView I'd like to create Access objects inside the GroupView, so that they are created with the group which I am inside at the moment. Also, I'd like them do be displayed on the left side with all available Accesstypes and nodes, seperated with an '|' just like all the available permissions: enter image description here I have done the same already with a form to add existing users to a group: class GroupForm(forms.ModelForm): users = forms.ModelMultipleChoiceField( label='Users', queryset=User.objects.all(), required=False, widget=admin.widgets.FilteredSelectMultiple( "users", is_stacked=False)) class Meta: model = Group exclude = () # since Django 1.8 this is needed widgets = { 'permissions': admin.widgets.FilteredSelectMultiple( "permissions", is_stacked=False), } class MyGroupAdmin(GroupAdmin): form = GroupForm list_display … -
how to add pagination in Django?
I want to apply pagination on my data I tried to watch lots of videos and read lots of articles but still can't solve my problem. This is my Views. def car(request): all_products = None all_category = category.get_all_category() categoryid = request.GET.get('category') if categoryid: all_products = Product.get_all_products_by_id(categoryid) else: all_products = Product.get_all_products() data = {} data['products'] = all_products # all products data['category'] = all_category # all category all_products = Product.get_all_products() data['product'] = all_products ] return render(request, 'car.html', data) as you can see I made some changes in above code but its make no diffrence def car(request): all_products = None all_category = category.get_all_category() categoryid = request.GET.get('category') if categoryid: all_products = Product.get_all_products_by_id(categoryid) else: all_products = Product.get_all_products() #pagination paginator = Paginator(all_products,2) **Changes** page_number=request.GET.get('page') **Changes** finaldata=paginator.get_page(page_number) **Changes** data = {'all_products':finaldata,} **Changes** data['products'] = all_products #all products data['category'] = all_category #all category all_products = Product.get_all_products() data['product'] = all_products return render(request, 'car.html', data) I want to display 4 products per page I tried to apply data limit query that work but that not a genuine approach to display data. I read many articles and watch YouTube video. but can't find any solution. which videos and articles I watched there pagination method is totally different they use pagination with … -
Django form with multi input from loop save only last record to database
I have a problem with saving data from a form in django. Only the last record is saved. I generate a list of dates (days of the month) in the view and display it in the form in templates along with the fields next to the type. Everything is displayed correctly in templates, but when I submit to, only the last record from the form appears in the save view. What am I doing wrong, can someone help? forms.py ''' class DoctorsSchedule(forms.ModelForm): # work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00') # official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00') class Meta: model = DoctorSchedule fields = ['date', 'day_type', 'work_hours', 'scheme', 'official_hours'] ''' model.py ''' class DoctorSchedule(models.Model): id = models.AutoField(primary_key=True, unique=True) date = models.DateField(blank=True, null=True) day_type = models.CharField(max_length=255, blank=True, null=True, default='Pracujący') work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00') scheme = models.CharField(max_length=255, blank=True, null=True, default='20') official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00') def __str__(self): return self.date ''' view.py ''' def terminarz(request): today = datetime.now() now = date.today() locale.setlocale(locale.LC_TIME, 'pl_PL') def months(): months = {'1': 'Styczeń', '2': 'Luty', '3': 'Marzec', '4': 'Kwiecień', '5': 'Maj', '6': 'Czerwiec', '7': 'Lipiec', '8': 'Sierpień', '9': 'Wrzesień', '10': 'Październik', '11': 'Listopad', '12': 'Grudzień'} return months ##################### days of month list ###################################### def days_of_month_list(): … -
Using Django Bad Request
I'm new in Django and Rest Framework and I didn't find how to do that: Filter an endpoint request without argument to return Bad Request. Example: get_foo/?foo_id= Return: { "status": 400, "error": "Bad Request" } At this time, a get request without argument gives all the values from the database. It's a big DB, so I have to do this filter. -
How can I toggle databases in Django?
Django's settings.py file has a DATABASES dictionary that stores configuration information for any number of database backends: # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'test': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'testing', 'USER': 'bert', 'PASSWORD': '***', 'HOST': 'remotemysql.com', 'PORT': '3306', }, 'dev': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'development', 'USER': 'ernie', 'PASSWORD': '***', 'HOST': 'remotemysql.com', 'PORT': '3306', }, ... } I would expect the Django authors to have included a method to easily switch among these configuration options, such as a separate variable somewhere USE_THIS_DB = 'test'; in order to easily switch between testing, development, production, etc. databases. I can't find this option. The only information I can find about switching databases is to manually rename the different configuration options in DATABASES so that the one I want to use is called default, which seems unnecessarily clunky, error-prone, and non-portable. Is there no way to more elegantly switch Django among different databases at startup? -
How to do a good callback function with django rest framework
I would like to write an api with django rest framework, I got some issues with my callback function. I can get the access code, but how to give it to my app? This is my callback function : @api_view(['GET']) def callback(request): if request.method == 'GET': code = request.GET.get("code") encoded_credentials = base64.b64encode(envi.SECRET_ID.encode() + b':' + envi.SECRET_PASS.encode()).decode("utf-8") token_headers = { "Authorization": "Basic " + encoded_credentials, "Content-Type": "application/x-www-form-urlencoded" } token_data = { "grant_type": "authorization_code", "code": code, "redirect_uri": "http://127.0.0.1:800/callback" } test = "test :" + code return JsonResponse(test, safe=False) And this is my view where I try to do some stuff (I use spotify's API, with spotipy), I need to get the users name or mail : @api_view(['GET']) @permission_classes([permissions.IsAuthenticated]) def test(request): if request.method == 'GET': test = "test " + request.user.username scope = "user-read-private" sp = getScope(scope) print(sp.current_user()) urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu' sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=envi.SECRET_ID, client_secret=envi.SECRET_PASS, redirect_uri=envi.SPOTIPY_REDIRECT_URI)) artist = sp.artist(urn) print(artist) user = sp.current_user() return JsonResponse(user, safe=False) def getScope(spotipyScope): token = SpotifyOAuth(scope=spotipyScope,client_id=envi.SECRET_ID, client_secret=envi.SECRET_PASS, redirect_uri=envi.SPOTIPY_REDIRECT_URI) spotifyObject = spotipy.Spotify(auth_manager= token) return spotifyObject When I do a get on 127.0.0.1:8000/test/, I have a new page on my browser, from spotify, I connect my account, and then, it redirects me on 127.0.0.1:8000/callback/?code=some_code How can I give it to … -
LoginRequiredMiddleware - redirection to previous page after allauth path not working
I implemented LoginRequiredMiddleware so that when user connect to any page of the app, they are redirected to the login_page. Once the login, or sign they are redirected to the page they previoulsy landed on. To do that I am using a path variable (code at the end) which is then used in both login and register views. This work fine for classic the login and register. However, I have also implemented allauth and when a user sign up with, say Google, the redirection to previous page is not happening and the user is redirect to LOGIN_REDIRECT_URL. This is because I haven't created a specific view for google sign up. I suppose there is 2 options from there: create a google sign up view and use the path variable - I am not sure how to (the biggest problem); There is an easier around the problem. middleware.py import re from django.conf import settings from django.shortcuts import redirect from django.contrib.auth.views import redirect_to_login from django.urls import reverse .. class LoginRequiredMiddleware: pass def __init__(self, get_response): self.get_response = get_response def __call__ (self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request,'user') path = request.path_info.lstrip('/') print(path) if not request.user.is_authenticated: if … -
Django: Is it possible to upload a file from a known local path with a button click only?
I need users to upload a particular system file and handle it in a views.py. Since I already know the absolute path of the file I need from the user's computer (e.g. '/Users/JohnDoe/Application\ Support/blah/blah.plist'), I'm wondering if it's possible to achieve this with a single click, without having to have the user select the file from file picker UI. If this is not possible, is it possible to set the starting location of file picker UI to pre-select the file when it opens? Despite spending a lot of time researching, I wasn't able to find an example suiting my needs given the unique use case. -
Imap not login with godaddy domain (imaplib.error: b'[AUTHENTICATIONFAILED] Authentication failed.)
the imap.py connect function work with gmail but not with other like godaddy code is here ` def connect(self, username, password): self.server = self.transport(self.hostname, self.port) if self.tls: self.server.starttls() typ, msg = self.server.login(username, password) if self.folder: self.server.select(self.folder) else: self.server.select() ` i got imaplib.error: b'[AUTHENTICATIONFAILED] Authentication failed. error try to connect with imap through login but got error Authentication failed imaplib.error: b'[AUTHENTICATIONFAILED] Authentication failed.' -
How do I create a profile by fetching data from an html form ? (Using JS, Django in backend)
I tried to fetch the data from the below file and display as a profile on a different page named 'startups.html'. Every person who fills the following profile form, his/her profile should be displayed on the 'startups.html' page. <form action="startups" name="createprofile" method="get" onclick="prof()"> {% csrf_token %} Company Image<input type="image" id="c_img" name="c_img" > Company Name<input type="text" id="c_name" name="c_id" > Startup or Investor <input type="text" id="c_type" name="c_type" > Username<input type="text" id="username1" name="username1" > Password<input type="text" id="password1" name="password1" > Confirm Password<input type="text" id="con_pass1" name="con_pass1" > <button type="submit" id="profile_sub" onclick="prof()">SUBMIT</button> <!-- <button type="submit" id="createprof_submit"><a href="" action="/startups" name="startups">SUBMIT</a></button>--> </div> </form> -
Problem with annotate Sum When Case after django upgrade
So I have a problem with upgrading django. models.py: class TrackReport(BaseMixin): value = models.PositiveIntegerField() archive = models.ForeignKey("Archive", related_name="track_reports", on_delete=models.PROTECT) date = models.DateField(db_index=True) Query: qs = Archive.objects qs = qs.annotate( filtered_by_date_min=Sum( Case(When(track_reports__date__gte=date_min, then=Value(1)), default=Value(0), output_field=IntegerField()) ) ).filter(filtered_by_date_min__gt=0) python 3.8, django 1.12, postgres 15 no problem python 3.11 django 4.1.2, postgres 15: ../../mambaforge/envs/new_sponsordata_arm/lib/python3.11/site-packages/django/db/models/sql/query.py:1289: in build_lookup lookup_class = lhs.get_lookup(lookup_name) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = Sum(CASE WHEN <WhereNode: (AND: In(Col(archive_trackreport, archive.TrackReport.type), ['FACEBOOK_POPULARITY']))> THEN Value(1), ELSE Value(0)) lookup = 'gt' def get_lookup(self, lookup): > return self.output_field.get_lookup(lookup) E AttributeError: 'IntegerField' object has no attribute 'get_lookup' ../../mambaforge/envs/new_sponsordata_arm/lib/python3.11/site-packages/django/db/models/expressions.py:377: AttributeError I know it's been ages but did anything change?