Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run migrations on Dockerfile deploying on Elastic Beanstalk
I have a problems making migrations (Django App 4.0.6) on Elastic beanstalk. This is my Dockerfile: FROM python:3.8 ENV PROJECT_DIR=/usr/src/app/ ENV PYTHONIOENCODING=utf-8 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 ENV PIPENV_USE_SYSTEM=1 WORKDIR ${PROJECT_DIR} COPY . ./ RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] Until here, all works well, but if I try to add RUN python manage.py migrate before to EXPOSE 8000 and make the deploy, I have an 504 error. I tried to add .ebextensions and config file like this: container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true But I don't sure how to activate my env in a Docker, I have an error when I try to make the deploy 2022-08-01 03:10:23,328 P28507 [INFO] Command 01_migrate 2022-08-01 03:10:23,331 P28507 [INFO] -----------------------Command Output----------------------- 2022-08-01 03:10:23,331 P28507 [INFO] /bin/sh: /var/app/venv/*/bin/activate: No such file or directory 2022-08-01 03:10:23,331 P28507 [INFO] ------------------------------------------------------------ 2022-08-01 03:10:23,331 P28507 [ERROR] Exited with error code 1 ¿What is the best solution for my case? Thanks for your help! :) -
Designing Django admin panel by tailwind
I hope you are fine. I want to customize my django admin panel by tailwind. I know how to use tailwind in the templates of my django apps but unfortunately I am not able to use tailwind in the admin template and I have also tried multiple ways to solve this such as putting cdn in the admin base.hml or installing django-tailwind but all of them hasn’t worked for me yet. I will thank if anyone who has experience about this matter give me a piece of guidance. -
How to only perform action once instance created
my code: def save(self, *args, **kwargs): <My_CODE> if <having_register>: <send_email_to_admin> but this function will work when I run an update instance ( The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be an SQL insert or update ) so if I just want to send an email to admin only once having a new registration? Any way to check the request method or prevent force_insert in this case? -
exclude field from a nested serializer
to get the information of a user I use a serializer with nested serializers but I have a problem which is that I do not know how to exclude certain fields that are not necessary in this case the user's password, is there any way to exclude that field? here is the code of the endpoint and the serializers endpoint @api_view(['GET']) @has_permission_decorator('view_team_member') def getTeamMembers(request, pk): try: token = decodeJWT(request) team_member = TeamMember.objects.filter(pk=pk, company_id=token['company_id']) print(team_member) serializer = TeamMemberSerializer(team_member, many=True) return Response({'data': serializer.data}, status=status.HTTP_200_OK) except TeamMember.DoesNotExist: return Response({'Error': 'Not Found'}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) team member serializer class TeamMemberSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) team = TeamSerializer(read_only=True) team_role = TeamRoleSerializer(read_only=True) company = CompanySerializer(read_only=True) class Meta: model = TeamMember fields = "__all__" read_only_fields = ['state', 'created_at', 'updated_at'] required_fields = ['team', 'user', 'team_role'] user serializer class UserSerializer(serializers.ModelSerializer): role = serializers.CharField(style={'input_type': 'text'}, write_only=True) password2 = serializers.CharField(style={'input_type': 'text'}, write_only=True) class Meta: model = User fields = ['first_name', 'last_name', 'email', 'password', 'password2', 'company', 'role'] extra_kwargs = { 'username': {'required': True}, 'email': {'required': True}, 'first_name': {'required': True}, 'last_name': {'required': True}, 'role': {'required': True}, 'company': {'required': True}, 'password': {'required': True}, 'password2': {'required': True}, } def save(self): password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: … -
Why do uploaded images in my Django project have larger file sizes than the source images? And how do I compress them?
I am working on a project that receives in Django a user uploaded image from Javascript via fetch API. The user uploads images for each tile in a custom grid. I have managed to get my app working, but I noticed that the uploaded tile images (all 1:1 ratio) have a much larger filesize than the ones that are actually uploaded. Why is this? I am using cropper.js to crop and save the files on my frontend. I wonder if that could affect the filesize in this way? Also, how do I compress the images before they are saved to save storage space? I have tried overriding the Pillow save method as mentioned in other posts, but could not get it to work. Here is some of my code: A paired-down version of the view that receives and saves the tile image: def add_image(request, tile_id): # Query for requested tile try: tile = Tile.objects.get(pk=tile_id) except Tile.DoesNotExist: return JsonResponse({"error": "Tile not found."}, status=404) if request.method == "POST": image = request.FILES.get("image") if image is not None: print(f"Image received: {image}") # Add image to tile tile.image = image tile.save() tiles = Tile.objects.select_related("grid").filter(grid=grid).all() return JsonResponse({ "tiles": [tile.serialize() for tile in tiles], }, safe=False) else: … -
Organize CSS and margin placement spaces between text in HTML
i am new to html. I'm trying to create a page that look exactly like what I design in XD, which looks like this But Currently my progress is up until like this, i created this using the language html & it is a django project. The problem I'm having right now is that the margin and the placement of the elements are not match and i found it is difficult to align them accordingly. I need help and suggestion to make the spacing looks more neat, text-alignment and the css thingy. The code is implement in Django/HTML. {% load static %} <html lang="en"> <head> <!-- Character Encoding and Viewport Meta Tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Website Title --> <title> 404 - Page Not Found </title> <!-- Fonts --> <link href="http://fonts.cdnfonts.com/css/lemonmilk" rel="stylesheet"> <script> document.getElementsByTagName("html")[0].className += " js"; </script> <!-- Website Favicon/Icon --> <link rel="icon" href="{% static 'landing/images/logo/favicon-96x96.png' %}"> {% block head %} {% endblock %} <style> @import url('http://fonts.cdnfonts.com/css/lemonmilk'); body { color: #666; text-align: center; font-family: "Segoe UI", sans-serif; margin: auto; } .status-error-code { text-align: center; font-size: 232px; color: #5AC69D; font-family: 'Lemon/Milk', sans-serif; } .content-first-message{ margin: auto; text-align: center; font-size: 60px; font-weight: 400; } .content-middle-message{ margin: … -
django cannot assign must be an instance
I'm trying to insert an item. but it's throwing `Cannot assign "'2003-221'": "ClearanceItem.recorded_by" must be a "ClearanceCustomuser" instance.` models.py class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) resolution = models.TextField(blank=True, null=True) resolve = models.BooleanField(blank=True, null=True) resolve_date = models.DateField(blank=True, null=True) resolve_by = models.CharField(max_length=8, blank=True, null=True) recorded_by = models.ForeignKey('ClearanceCustomuser', models.DO_NOTHING, db_column='recorded_by', blank=True, null=True) record_date = models.DateField(default=datetime.now, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' class ClearanceCustomuser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.BooleanField() userid = models.CharField(primary_key=True, max_length=9) email = models.CharField(unique=True, max_length=254) is_staff = models.BooleanField() is_active = models.BooleanField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'clearance_customuser' views.py class Add(LoginRequiredMixin, CreateView): form_class = CreateForm model = ClearanceItem template_name = 'clearance/add.html' def form_valid(self, form): instance = form.save(commit=False) instance.recorded_by = self.request.user.userid instance.save() return HttpResponseRedirect(self.get_success_url()) search few related question Cannot assign must be a instance. Django and someone answer that Scripter.title is a foreign key to Book, so you must give it an actual Book, not a string. I believe I am giving my clearanceitem an actual user which is userid = 2003-221. I dont understand … -
Unable to specify foreign key in managed model to non-managed model (Django 3.2.7 / Postgresql 10.18)
I am implementing a "profile model" in Django 3 that at its simplest is a two field model: a one-to-one relationship field to the default Django User model and a foreign key relationship to an unmanaged model TeamDim that is populated and managed by an ETL job outside the Django app. I'm using Postgresql 10 as the DB backend. I had no trouble creating the initial table with the one-to-one field and placeholder teamname CharField, but adding the ForeignKey field causes the migration to fail with the following error: django.db.utils.ProgrammingError: column "index" referenced in foreign key constraint does not exist The primary key in TeamDim is team_id and is appropriately specified in the model definition, so I'm not sure where the reference to column index is coming from in the foreign key constraint the migrator is attempting to apply. Other non-managed models in my app have no trouble referencing TeamDim via foreign keys with the same declaration, so I'm not sure why it's failing in the managed case. Adding kwargs db_index=False or to_field='team_id' to the ForeignKey declaration don't remedy the issue. Below are the two relevant models - TeamDim and CefhUser from django.db import models from django.contrib.auth.models import User # … -
How do I make a Django form that display's model objects to chose from
Ok, I am building a hotel application and in the booking section of the various hotels, I want there to be a dropdown in the booking section and that dropdown would contain the number of rooms the hotel has so a user can book a specific room. Now each hotel has different number of rooms, so I want it to be that, based on the number of rooms the hotel has, that number would be the number of rooms in the drop down. here is my code... registration 'models.py' class Hotel(models.Model): name = models.CharField(max_length=120, null=True) hotel_location = models.CharField(max_length=3000, null=True) number_of_rooms = models.IntegerField(null=True) number_of_booked_rooms = models.IntegerField(null=True, default=0) and here is the booking 'models.py' class RoomBooking(TrackingModel): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) room_number = models.ForeignKey('Room', on_delete=models.CASCADE) class Room(TrackingModel): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) room_information = models.ForeignKey(RoomBooking, on_delete=models.CASCADE) room_number = models.IntegerField() here is my 'views.py' def book_a_room(request, *args, **kwargs): hotel_slug = kwargs['slug'] hotel = Hotel.objects.get(slug=hotel_slug) form = BookingARoomForm() if request.method == 'POST': form = BookingARoomForm(request.POST) if form.is_valid(): if hotel.number_of_booked_rooms < hotel.number_of_rooms: hotel.no_rooms_available = False if hotel.no_rooms_available == False: hotel.number_of_booked_rooms += 1 hotel.save() room_booking = RoomBooking.objects.create(hotel=hotel, guest=request.user, **form.cleaned_data) Room.objects.create(hotel=hotel, room_information=room_booking, is_booked=True, checked_in=True, **form.cleaned_data) return HttpResponse('<h1>You just booked a hotel</h1>') else: hotel.no_rooms_available = True hotel.number_of_booked_rooms = hotel.number_of_rooms hotel.save() … -
Creating a separate comments app for a django ticket app
Trying to create a separate comments app using class-based views for a ticket project. I think the problem lies in my comments’ models.py or its urls.py file but I dont know how to proceed. Here is the error that I get and the code and traceback. Traceback Installed Applications: ['tickets.apps.TicketsConfig', 'users.apps.UsersConfig', 'comments.apps.CommentsConfig', 'demo.apps.DemoConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\contrib\auth\mixins.py", line 71, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 174, in post return super().post(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 144, in post return self.form_valid(form) File "C:\Users\mikha\issuetracker\comments\views.py", line 41, in form_valid return super().form_valid(form) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 128, in form_valid return super().form_valid(form) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 59, in form_valid return HttpResponseRedirect(self.get_success_url()) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 118, in get_success_url url = self.object.get_absolute_url() File "C:\Users\mikha\issuetracker\comments\models.py", line 21, in get_absolute_url return reverse('tickets:ticket-detail', kwargs={'pk': self.ticket_id}) File "C:\Users\mikha\bug_env\lib\site-packages\django\urls\base.py", line 86, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\urls\resolvers.py", line 729, … -
Knox logout error "authentication credentials not provided"
I was working on user register login and logout using Knox, the register returns the usern and the login returns the token and token expiry time . But when I try to logout it returns ‘authentication credentials not provided’. I sorry if I provided too many pictures. views serializers urls error -
Django application with ASGI Uvicorn increasing the latencies by 4x
We are using a Django application (https://github.com/saleor/saleor) to handle our e-commerce use-cases. We are using ASGI with Uvicorn in production with 4 workers. Infra setup - 4 instances of 4 core 16 GB machines for hosting the Django application (Saleor). The app is deployed using docker on all the instances. 2 instances of 4 core 16 GB for Celery. Hosted PostgresSQL solution with one primary and one replica. Saleor uses Django and Graphene to implement GraphQL APIs. One of the API is createCheckout which takes around 150ms to 250ms depending on the payload entities. While running load test with 1 user, the API consistently gives similar latencies. When number of concurrent users increase to 10, the latencies increase to 4 times (1sec - 1.3 secs). With 20 users, it reaches to more than 10 seconds. Average CPU usage doesn't exceed more than 60%. While tracing the latencies, we found out that the core APIs are not taking more than 150-250ms even with 20 users making concurrent requests. This means that all the latencies are being added at ASGI + Uvicorn layer. Not sure what are we missing out here. From the deployment perspective, we have followed standard Django + ASGI … -
InvalidProfileError using github actions to deploy on Elastic Bean
I am using github actions to deploy my Django app to Elastic bean. My .elasticbeanstalk/config.yml file is: branch-defaults: amazon-deploy: environment: platform-prod group_suffix: null global: application_name: platform branch: null default_ec2_keyname: aws-eb default_platform: Python 3.8 running on 64bit Amazon Linux 2 default_region: eu-north-1 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: git workspace_type: Application I have the following code on my github actions (.github/workflows/github_actions.yml: name: EB deploy on: push: branches: [ master ] jobs: deploy: runs-on: ubuntu-latest env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} steps: - uses: actions/checkout@v2 - name: Install Python 3.8 uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install EB CLI using pip run: | python -m pip install --upgrade pip pip install awsebcli - name: Deploy to Elastic Beanstalk run: | eb deploy platform-prod When I execute github action, I get the following error: ERROR: InvalidProfileError - The config profile (ecb-cli) could not be found Error: Process completed with exit code 4. I have changed the profile from ecb-cli to default but I still get the same error. Can anyone please help. Thank you. -
Authenticating users with django in external application
I am creating a project where I have a downloadable software on a clients computer in python. I want to create a login system where I use the users on my django server to authenticate the login on the downloadable software that runs on the clients computer. It is an inventory management system that does some other stuff as well which I am unable to elaborate on. I am unsure what python packages might help with this or where to start. Do I just make my project a webapp or am I able to go with my original idea. I have done quite a lot of searching around to find an answer but haven't found one. This is not a server to server communication that I am looking for but rather a client requesting from the server. This will be a subscription based software and I do not want users accessing the product if they have not paid for their usage. Is this possible? I would appreciate any feedback. -
Cant trigger a view's breakpoint in django tests
I want to debug a view that gets triggered inside a django tests.py Here's the view code: def test_view(request): if request.method == "POST": with open("a_path_to_the_file/aaa.txt", "w") as f: f.write("done!") Here's the test: class ViewsTests(TestCase): def test_add_address(self): self.client.post(reverse("address_book:test_view")) The view just doesn't run in that way. I want the file to be created after I run the test. The breakpoint is set on the if request.method == "POST": line. I use pycharm and run tests via pycharnm run config. -
Problems with a backend part of search line in Django
who can explain me why my SearchView doesn't work. I have some code like this: search.html <div class="justify-content-center mb-3"> <div class="row"> <div class="col-md-8 offset-2"> <form> <div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search..." /> <div class="input-group-append"> <button class="btn btn-dark" type="submit" id="button-addon2">Search</button> </div> </div> </form> </div> </div> </div> search/urls.py path('search/', SearchView.as_view(), name='search') search/views.py class SearchView(ListView): model = Question template_name = 'forum/forum.html' def get_queryset(self): q = self.kwargs.get('q', '') object_list = self.model.objects.all() if q: object_list = object_list.filter(q__icontains=q) return object_list -
How do I create a LinkedIn ad campaign api using Django?
I am working on a project where I am trying to create an API of an ad campaign manager using LinkedIn oauth2 and Django. I have managed to get connected and authorized to LinkedIn with rw_ads permissions but I have absolutely no idea where to go from here. Any help would be much appreciated, thanks in advance! -
Django rest framework and React: TypeError: NetworkError when attempting to fetch resource
I am using Django rest framework for back-end and react for front-end of a website. Back-end is working fine in my Postman app and browser. However, when I fetch data using react it prints following error in my console TypeError: NetworkError when attempting to fetch resource. and nothing is shown in XHR tab of Networks. Here is my code export default function Contact() { const [contactData, setContactData]=useState({ 'name': '', 'email': '', 'phone': '', 'describe': '', 'status': '', }); const change=(event)=>{ setContactData({ ...contactData, [event.target.name]: event.target.value }); } const submitForm=()=>{ const contactFormData=new FormData(); contactFormData.append('name', contactData.name) contactFormData.append('email', contactData.email) contactFormData.append('phone', contactData.phone) contactFormData.append('describe', contactData.describe) fetch('http://127.0.0.1:8000/ask/', { mode: 'cors', method: 'POST', headers: { "Access-Control-Allow-Origin": "*", 'Content-Type': 'application/json', }, body: JSON.stringify({ // your expected POST request payload goes here name: contactData.name, email: contactData.email, phone:contactData.phone, describe: contactData.describe }) }) .then(res => res.json()) .then(data => { // enter you logic when the fetch is successful setContactData({ 'name': '', 'email': '', 'phone': '', 'describe': '', 'status': 'success', }) } ) .catch(error => { // enter your logic for when there is an error (ex. error toast) console.log(error) }) here is the part of settings.py file where I added cors headers INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', … -
Starting a login session once check_password verifies a password is correct
I have a user logi form i am using to authenticate users in django and this is the code that processes from django.contrib.auth.hashers import make_password from django.contrib.auth.hashers import check_password from django.contrib.auth import login def process_login(request): if request.method == 'POST': var = request.POST["email_or_telephone"] print(var) obj=AuthUsers.objects.create( email_address = "info@google.com", user_type = "inapp", telephone_number = "08002556155", user_password = make_password("logan2900"), account_status = "not_verified", full_names = "Michael Jackson", pronouns = "Hee/Hee", country = "UK", gps_location = "London", role_name = "user", profile_picture = "image.png", kyc_documents = "1.png,2.jpg" ) obj.save() if check_password("logan2900", "pbkdf2_sha256$320000$S8u10Fh1yz0NssYphC1qW1$LvnhBHACIqr6dGX7Bae19k8/yGf/omNLQcvl88QXodv="): print("Correct Password") else: print("Incorrect Password") I am using the the check_password method to check if a user password is correct and the function works as expected. How can i start session and actually login user after verifying the password is correct? Also after successfully logging the user, how can i verify a user is logged in in another function? -
Django: how to check if the users that are registered under me have new users registered under them in Django
I am writing a referral system logic in django. The referral system works fine now, but what i want to implement is this. When i refer a user "user 2" and "user 3", it is stored that i have refered two users, now how do i check if "user 2" or "user 3" which are refered by me: have gotten a new user refered by them ("user 2" or "user 3"). This is the code i have written to register users as referalls views.py def registerRef(request, *args, **kwargs): profile_id = request.session.get('ref_profile') print('profile_id', profile_id) code = str(kwargs.get('ref_code')) try: profile = Profile.objects.get(code=code) request.session['ref_profile'] = profile.id print('Referer Profile:', profile.id) except: pass print("Session Expiry Date:" + str(request.session.get_expiry_age())) form = UserRegisterForm(request.POST or None) if form.is_valid(): if profile_id is not None: recommended_by_profile = Profile.objects.get(id=profile_id) ref_earn = InvestmentPackageID.objects.get() instance = form.save() registered_user = User.objects.get(id=instance.id) registered_profile = Profile.objects.get(user=registered_user) registered_profile.recommended_by = recommended_by_profile.user registered_profile.save() else: instance = form.save() registered_user = User.objects.get(id=instance.id) profile = Profile.objects.get(user=registered_user) profile.save() username = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('core:index') context = {'form':form} return render(request, 'userauths/sign-up.html', context) in the profile model i have a field like this models.py class Profile(models.Model): ... code = models.CharField(max_lenght=100, ...) recommended_by = models.ForeignKey(User, ...) What is … -
Grouping entries from PostgreSQL database by their week or month based on timestamp value?
I have been trying to resolve a solution to this for a while now but due to my inexperience with both postgres(and SQL in general) and Django ORM I haven't been able to get a result that I can use. I have this model: class EventItem(models.Model): Id = models.CharField(max_length=200, primary_key=True) StartTime = models.DateTimeField(null=True) EndTime = models.DateTimeField(null=True) Duration = models.TimeField(null=True) Creator = models.CharField(max_length=50, null=True) and I want to get the EventItems and group the entries by their week and/or month. So for every week starting from the earliest entry group all of the events for that week into one group. Right now I am able to return the week number for each individual item by doing this: weeks = EventItem.objects.annotate(week=ExtractWeek('StartTime')).values('week') But this obviously doesn't group the results and I also need to keep the columns from the original table. -
Django authenticate() command returns None
I am doing a website which has Google sign in and I am trying to log in the user when they click the sign in with Google button. This is the code that doesn't work: def google_login(request): security_key = request.GET.get("security_key","") email = request.GET.get("email","") if security_key == "" or email == "": return redirect("/403/") timestamp_now = time.time() try: obj = GoogleSignupToLoginSecurityKey.objects.get(email=email,security_key=security_key) if (timestamp_now-float(obj.timestamp_created)) < 50: print(email) user = authenticate(email=email, password="GOOGLE USER") print(user) if user is not None: login(request, user) else: redirect_url = "/accounts/signup/" return redirect(redirect_url+"?error=google_unknown") return redirect("/accounts/signup/welcome/") else: return redirect("/accounts/signup?error=google_unknown") except: return redirect("/403/") return All the security and timestamp stuff is for security purposes but the bit that doesn't work is the authenticate() command. For this command the email is retrieved by a url parameter and I have checked and it is correct. For a Google Account I have made the password "GOOGLE USER" since I am lazy and haven't bothered taking out the password field for a Google Account, this means that every Google account has the same password but for this type of account it is completely unnessesary to have a password. The command returns "None". Hopefully you understand this and I haven't made it too confusing. -
TypeError at /password-reset/ filter_users_by_email() got an unexpected keyword argument 'is_active'
I am trying to use the password-reset api endpoint in dj_rest_auth. It requires that I enter the email address of the user but wehenever I do that, I get TypeError at /password-reset/ filter_users_by_email() got an unexpected keyword argument 'is_active' error. Please help me solve this. Thank you. models.py from django.conf import settings User = settings.AUTH_USER_MODEL from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth.models import UserManager from orders.models import Orders # Create your models here. class CustomUser(AbstractUser): phone_number = models.CharField(max_length=100) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) id = models.IntegerField(primary_key=True) username = models.CharField(max_length=100, default="") email = models.CharField(max_length=100, default="") def save(self, *args, **kwargs): self.id = self.user.id self.username = self.user.username self.email = self.user.email super().save(*args, **kwargs) def __str__(self): return f'{self.user.username} Profile' urls.py from django.contrib import admin from django.urls import path, include from orders import views from django.views.generic import TemplateView from dj_rest_auth.views import PasswordResetView, PasswordResetConfirmView urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index.html')), path(('users/'), include('users.urls')), path('orders-list/', views.OrdersList, name = "orders-list"), path('orders-detail/<str:pk>', views.OrdersDetail, name = "orders-detail"), path('orders-create/', views.OrdersCreate, name = "orders-create"), path('orders-update/<str:pk>', views.OrdersUpdate, name = "orders-update"), path('orders-delete/<str:pk>/', views.OrdersDelete, name = "orders-delete"), path('password-reset/', PasswordResetView.as_view()), path('password-reset-confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name = 'password_reset_confirm'), path("djangoflutterwave/", include("djangoflutterwave.urls", namespace="djangoflutterwave")) ] -
DJango project & app layout and Imports seem to be extremely repetative
I'm trying to layout my Django app, and I just cannot figure out what the appropriate way to do it is. I've read many questions and blog posts, but nothing seems obvious. Here's my app (I hate the repetition of these terms like buildhealth, but I guess it's idomatic in Django?) - the name of the project, created by django-admin startproject buildhealth and the name of the first app (a performance dashboard) created by django-admin startapp performance is performance): [ROOT] ├── ... ├── buildhealth │ ├── __init__.py │ ├── buildhealth │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── performance │ │ │ ├── __init__.py │ │ │ ├── ... │ │ │ ├── views.py │ │ │ └── ... │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── ... │ ├── manage.py │ └── staticfiles │ └── ... ├── poetry.lock ├── pyproject.toml └── ... This sort of works, but then i have files all over the place for doing imports which feels terrible. For example - in settings.py, i have to type this: ROOT_URLCONF = "buildhealth.buildhealth.urls" This feels super wrong to have two imports like this. Am I laying this out wrong? … -
Django Limit Choices in Admin
I need to filter categories that I can select in PostAdmin exact which was confirmed, how to do that? in models: class Category(models.Model): name = models.CharField(max_length=200) confirmed = models.BooleanField(default=False) .... def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') ... def __str__(self): return self.title in admin: class PostAdmin(models.ModelAdmin): list_display = ['title', 'category'] fields = ['title, 'category'] admin.site.register(Post, PostAdmin)