Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In the below code how def save() is working? [closed]
In This code explain the working of code block mentioned below from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class NewUserForm(UserCreationForm): CHOICES=( ('Doctor','D'), ('Patient','P'), ('Manager','M') ) email = forms.EmailField(required=False) username = forms.CharField(required=True) phone = forms.IntegerField(required=False) role = forms.CharField(widget=forms.Select(choices=CHOICES)) password1 = forms.CharField(required=True) password2 = forms.CharField(required=True) class Meta: model = User fields = ("email","username","phone","role","password1","password2") def save(self,commit=True): user = super(NewUserForm,self).save(commit=False) user.email = self.changed_data['email'] if commit: user.save() return user Please explain working of def save and class Meta , what is the use of .save(commit=False) here. -
Some static files are throwing 404 when deploying Django on vercel
I am deploying my Django project on vercel This is my vercel.json file { "version": 2, "builds": [ { "src": "event_management/wsgi.py", "use": "@vercel/python", "config": {"maxLambdaSize": "15mb", "runtime": "python3.9"} }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } } ], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "event_management/wsgi.py" } ] } my settings.py STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles_build', 'static') everything works fine but when I open the admin panel one CSS file static/admin/css/base.css is throwing 404 error all the other static files are loading fine Here is the admin panel link. the base.css is even listed in Vercel static Assets You can also check the file is present on the directory listing here here is my github repo link the code is in main branch -
Choose the best backend for real-time wbapp
I have a gps tracking service tha is monitoring data (ex cars) from database on the openlyers map realtime. I want to use websocket. So what is the best for backend . Django channels or nodejs?? I want to use postgresql but django channels use redis. -
Python Plotly Line Chart not displaying Lines
I am trying to create an app that would display some charts based on chosen item for an average monthly data, like "6/2023", "7/2023". I have the code which is working and I can see output in my terminal, but the line graph won't work, just a blank page, and looks like it is not receiving my data. Please help class Item(models.Model): item = models.CharField(max_length=100) date = models.DateField(null=True) price = models.FloatField() def __str__(self): return self.item def line(request): items = Item.objects.values_list('item', flat=True).distinct() item = request.GET.get('item', 'Drink') data = Item.objects.filter(item=item).annotate( month=F('date__month'), year=F('date__year') ).values( 'month', 'year' ).annotate( avg_price=Avg('price') ).order_by( 'year', 'month' ) item_years = [f"{k['month']}/{k['year']}" for k in data] item_price = [f"{v['avg_price']}" for v in data] cds = ColumnDataSource(data=dict(item_years=item_years, item_price=item_price)) fig = figure(height=500, sizing_mode="stretch_width", title=f"{item} GDP") fig.title.align = 'center' fig.title.text_font_size = '1.5em' fig.yaxis[0].formatter = NumeralTickFormatter(format="$0.0a") fig.circle(source=cds, x='item_years', y='item_price', size=12) fig.line(source=cds, x='item_years', y='item_price', line_width=2) tooltips = [ ('Year', '@item_years'), ('Price', '@item_price') ] fig.add_tools(HoverTool(tooltips=tooltips)) script, div = components(fig) context = { 'items': items, 'item': item, 'script': script, 'div': div, } if request.htmx: return render(request, 'analysis/partials/gdp-bar.html', context) return render(request, 'analysis/line.html', context) <div class="row"> <div id="linechart" class="col-10"> {% include 'analysis/partials/gdp-bar.html' %} </div> <div class="col-2"> <label>Product</label> <select id="select-year" class="custom-select" name="item" autocomplete="off" hx-get="{% url 'linechart' %}" hx-target="#linechart"> {% for … -
Django why my post.count_views increments by 2?
Good evening, everyone, I'm a beginner at Django I have blog page details that has count views and category for the blog post and blog post tags and other staff my post model is: class Post(models.Model): title = models.CharField(max_length=250) content = RichTextUploadingField() post_date = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=200, unique=True) image = models.ImageField(null=True, blank=True, upload_to="images/") tagss = models.ManyToManyField(Tags, blank=True, related_name='post') Categorys = models.ManyToManyField(Category, blank=True, related_name='post') views_count = models.IntegerField(default=0, null=True, blank=True) def __str__(self): return self.title and my view is: def post_page(request, slug): post = Post.objects.get(slug = slug) post.views_count = post.views_count + 1 post.save() print("views:", post.views_count ) cats = Category.objects.all() tags = Tags.objects.all() # change 2 to how many random items you want random_items = list(Post.objects.all().order_by('?')[:2]) related_posts = list( Post.objects.filter( Q(tagss__name__in=[tag.name for tag in post.tagss.all()]) | Q(Categorys__name__in=[Category.name for Category in post.Categorys.all()]) ).distinct() ) recent_posts = Post.objects.all().order_by('-id')[:4] context = {'post': post, 'cats': cats, 'tags': tags, 'recent_posts': recent_posts, 'random_blog': random_items, 'related_posts': related_posts} return render(request, 'blog/Blog_details.html', context) my problem is when I refresh the post page the views increase by 2 I need when the user refresh the page increase by 1 Thanks everyone -
Session is set to None when calling an rest_framework class based endpoint
In my webpage the user will login with spotify in order to use the spotify api and display things like top songs, top artists etc. After implementing the authorization flow of spotify api, I created and endpoint that should check if the current session_id is in my database with an already assigned access token / refresh token and login the user (and generate new access token if required). The problem is inside the endpoint function, the session is None. Checking session function (here self.session.session_key is None): class IsAuthenticated(APIView): def get(self, request, format=None): # self.request.session.save() # if not request.session.session_key: # request.session.save() is_authenticated = is_spotify_authenticated(self.request.session.session_key) return Response({'is_authenticated': is_authenticated}, status=status.HTTP_200_OK) Where I make the request from (and I have the correct session): def home(request): response = get('http://127.0.0.1:8000/api/is-authenticated').json() # print(response) # print(f"{request.session.session_key=}") request.session["is_authenticated"] = response.get("is_authenticated") return render(request, "home.html") I've tried as you can see from the commented code to call .save() but it just creates a new session, it does not use the initial one -
mypy django models typehint
I integrated mypy into my project and would like to type my django models, how would I enable the following conversions? ForeignKey to the actual model, charField and textField to str, DecimalField to Decimal... class mymodel(models.Model): address: str = models.CharField(max_length=100) description: str = models.TextField() organisation: Organisation = models.ForeignKey( "organisations.Organisation", on_delete=models.CASCADE, related_name="properties", editable=False, ) My current setup.cfg file looks like this: [mypy] plugins = mypy_drf_plugin.main, mypy_django_plugin.main, pydantic.mypy exclude = /migrations/|template python_version = 3.11 no_implicit_optional = True strict_optional = True [mypy.plugins.django-stubs] django_settings_module = "backend.settings" -
Django rest serializer problem with serializing many-to-many field
I cannot serialize menu object, which contains foreign key to DishOrder object which contains a foreign key to Dish object. class Dish(models.Model): name = models.CharField(max_length=20, blank=False, null=False, unique=True) ... def __str__(self): return self.name class Menu(models.Model): name = models.CharField(max_length=50, unique=True) ... @property def cost(self): return self.dishes.aggregate(total_cost=Sum('dish__price'))['total_cost'] or 0.00 def __str__(self): return f"Меню '{self.name}'" class DishOrder(models.Model): dish = models.ForeignKey(Dish, on_delete=models.SET_NULL, blank=True, null=True) menu = models.ForeignKey(Menu, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.PositiveIntegerField() def __str__(self): return self.dish.name Here are my serializers: class DishSerializer(serializers.ModelSerializer): category = serializers.CharField(source='category.category', read_only=True) price = serializers.FloatField() class Meta: model = Dish fields = '__all__' class DishOrderSerializer(serializers.ModelSerializer): dish = DishSerializer() class Meta: model = DishOrder fields = ['dish', 'quantity'] class MenuSerializer(serializers.ModelSerializer): dishes = DishOrderSerializer(many=True) class Meta: model = Menu fields = '__all__' Error after calling MenuSerializer(all_menus) AttributeError: Got AttributeError when attempting to get a value for field `dish` on serializer `DishOrderSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Dish` instance. Original exception text was: 'Dish' object has no attribute 'dish'. ChatGPT says: the problem may occur because of dish naming -
NoReverseMatch Django - Attribute printing elsewhere in file?
I am getting a 'No reverse match' error in my Django DeleteView template. I have done some research, and this is supposedly caused when an attribute for a url redirect is blank. The error looks like the following, however the success button redirect works as expected, it is only erroring on my 'cancel' option. In this case, the url thats generating this error looks like the following: <a class="mt-3 mb-3 btn btn-secondary" id="cancel-btn" href="{% url 'post-detail' object.id %}">Cancel</a> This would mean that, 'object.id' is blank/null... However, I have added this attribute into a paragraph tag within the same template, and am seeing the correct value print (in this case, 3). {% block content %} <div> <form method="POST"> {% csrf_token %} <!--required security token--> <fieldset class="form-group"> <legend class="border-bottom mb-4">Delete Event</legend> <p>Are you sure you want to delete the post "{{object.id}}"?</p> </fieldset> <div class="form-group text-center"> <button class="btn btn-danger m-3" type="submit">Yes, Delete</button> <a class="mt-3 mb-3 btn btn-secondary" id="cancel-btn" href="{% url 'post-detail' object.id %}">Cancel</a> </div> </form> </div> {% endblock content %} Perhaps I have incorrectly typed my code, but I can't seem to figure out how the value could possibly get erased and is unable to be referenced for the cancel button href? My … -
Movie cast with characters in Django
So, I'm doing the classical movie app in Django (I'm loving the framework!) and I feel like I hit a stump. So, I have my Movie model: class Movie(models.Model): TitlePRT = models.CharField(max_length=100) TitleORG = models.CharField(max_length=100) TitleAlt = models.CharField(max_length=100) Poster = models.ImageField(upload_to=posterPath, max_length=100) Synopsis = models.TextField() Year = models.IntegerField() DubStudio = models.ForeignKey("Studio", on_delete=models.CASCADE) Trivia = models.TextField() CreatedBy = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="+") CreatedAt = models.DateTimeField(auto_now=False, auto_now_add=True) Modifiedby = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="+") ModifiedAt = models.DateTimeField(auto_now=True, auto_now_add=False) My Actor model: class Actor(models.Model): Bio = models.TextField() Name = models.CharField(max_length=50) FullName = models.CharField(max_length=50) DateOfBirth = models.DateField() Country = models.TextField(max_length=100) Nationality = models.TextField(max_length=50) Debut = models.ForeignKey("Movie", on_delete=models.CASCADE) CreatedBy = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="+") CreatedAt = models.DateTimeField(auto_now=False, auto_now_add=True) ModifiedBy = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="+") ModifiedAt = models.DateTimeField(auto_now=True, auto_now_add=False) ClaimedBy = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="+") And, finally, my Cast model: class Cast(models.Model): Movie = models.ForeignKey("Movie", on_delete=models.CASCADE) Actor = models.ForeignKey("Actor", on_delete=models.CASCADE) Character = models.TextField(max_length=50) Observations = models.TextField(max_length=50) Right now, I can add content through Django admin, but it's awkward, because I can't add a cast in the Movie form. I have to go to the Cast form, and a character one by one I've searched about customizing admin forms and whatnot, but I get a little confused. Is there to create a form … -
Django - Exclude URL from Django REST API Documentation? Using drf-yasg
How do I remove the path below from my API documentation with my current code? path('users/reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view()), I don't want this path to be generated. I’m using drf_yasg to generate re-doc and swagger documentation. Below is some of what's under the hood of settings.py. Any help is gladly appreciated! Thanks! settings.py from rest_framework.documentation import include_docs_urls from rest_framework.schemas import get_schema_view from rest_framework import permissions from allauth.account.views import ConfirmEmailView, EmailVerificationSentView from dj_rest_auth.views import PasswordResetConfirmView from drf_yasg import openapi from drf_yasg.views import get_schema_view API_TITLE = ‘Test API API_DESCRIPTION = ‘Test ‘Description schema_view = get_schema_view( openapi.Info( title=“title-test”, default_version='v1', description=“blah blah.”, ), public=True, permission_classes=(permissions.IsAuthenticated,), ) urlpatterns = [ # AllAuth Authentication path('accounts/', include('allauth.urls')), # Django REST API Paths path('api/', include('api.urls')), path('api-auth/', include('rest_framework.urls')), # ConfirmEmailView Needs to be defined before the registration path path('api/dj-rest-auth/registration/account-confirm-email/<str:key>/', ConfirmEmailView.as_view()), path('api/dj-rest-auth/', include('dj_rest_auth.urls')), path('api/dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('api/dj-rest-auth/registration/account-confirm-email/', EmailVerificationSentView.as_view(), name='account_email_verification_sent'), # path('api/dj-rest-auth/reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view()), # API Documentation Paths path('docs/', include_docs_urls(title="GameStation API", description=API_DESCRIPTION)), # path('schema/', schema_view), path('swagger<format>/', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ## This path is what I’m trying to remove path('users/reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view()), ] -
IntegrityError when Adding Social Application in Django: Null Value in Column "provider_id"
IntegrityError when Adding Social Application in Django: 'Null Value in Column "provider_id" violates non-null constraint' I am encountering an IntegrityError in my Django application when attempting to add a social application using Django Allauth. The error specifically points to a null value in the provider_id column, and I'm seeking assistance to resolve this. The error occurs when I try to add a new social application through the Django admin panel. Here's the detailed error message: ($ symbols are to block for privacy IntegrityError at /admin/socialaccount/socialapp/add/ null value in column "provider_id" violates not-null constraint DETAIL: Failing row contains (8, google, google, 888982092733-51qdar9ln6i5onjoli2blj9bb6$$$$$$$.apps.googleusercon..., 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, , null, null). provider to Google, which is the only drop down option all migrations have taken place in the code Google OAuth via django details Authorised redirect URIs are linking to port urls. Publishing status is in production. Resources being consulted. Akamai DevRel. “Set up Google Sign-in for Faster Django Login Experience Feat. Tech with Tim.” YouTube, YouTube Video, 12 Dec. 2022, https://youtu.be/yO6PP0vEOMc?feature=shared&t=1386. Accessed 11 Nov. 2023. all steps have been followed to implement a google oauth with this tutorial, the issue arises around 23:06 when adding a social account. “Django.” Django Project, 2023, https://docs.djangoproject.com/en/4.2/topics/auth/. Accessed 11 … -
get last 3 object of model from database in Django
I'm working on blog project & I have 'Last posts' section for posts in car category i want to get last 3 object of my model from db and send with context to template. 'car_post' : post.objects.filter(category__name = 'car')[:3] I tried this code but i think it shows first 3 post in db what can i do? -
How do i install django spirit forum package to my django application with its own custom usermodel?
I have a django application that has its own user model, authentication pages etc. When i install the spirit forum package with pip and create the app as a new project in a separate empty project to inspect the package and what the forum will look like (by running it), i see that it requires a username to login, create account and it has it own profile pages. My custom user model doesnt use username, only email adress and it has its own profile pages. How do i smoothly install the package and do i need to modify my current custom user model? I did as explained above, install the package in an empty project to inspect it but here i worry that it will not automatically adjust to my custom user model. -
How to implement "create link" function in django?
I am coding real time chat application that has rooms with hash as a pk. On the index page, there is input field that takes a link and let user join to specific chat Room. On the chat room page, there is create link button and it is only visible if you are owner of this chat room Link should always be unique and expire after some amount of Time. Maybe you know this function from Discord Any ideas on how to implement this? My thought is to create Link and Room models. Room has a foreign key to Link model and Link model has URLField ( URL field can be none ). And just to hash a hash of the Room? I just don't want users to join chat room via URL on the top of the browser -
TypeError at / object HttpResponse can't be used in 'await' expression
Code doesn't run after running it in the venv. I use django for backend, vue for frontend and tailwind for css. Error goes like this: Traceback (most recent call last): File "C:\Users\docto\OneDrive\Desktop\bms\backend\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\docto\OneDrive\Desktop\bms\backend\venv\Lib\site-packages\whitenoise\middleware.py", line 124, in __call__ return self.get_response(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\docto\OneDrive\Desktop\bms\backend\venv\Lib\site-packages\asgiref\sync.py", line 240, in __call__ return call_result.result() ^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\concurrent\futures\_base.py", line 449, in result return self.__get_result() ^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\concurrent\futures\_base.py", line 401, in __get_result raise self._exception ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\docto\OneDrive\Desktop\bms\backend\venv\Lib\site-packages\asgiref\sync.py", line 306, in main_wrap result = await self.awaitable(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Exception Type: TypeError at / Exception Value: object HttpResponse can't be used in 'await' expression [TypeError Message] (https://i.stack.imgur.com/NsCIP.png) Code which the error was raised: class LandingPageView(TemplateView): template_name = 'public_pages/landing.html' def __init__(self, **kwargs): super().__init__(**kwargs) seasons = Season.seasons.all()[:2] self.is_landing = 'active' self.previous_season = seasons[1] if seasons.count == 2 else seasons.first() self.season = seasons.first() self.main_image = MainImage.images.all().first() self.news = News.images.all().first() self.unupdated_accounts = get_activation_requests().first() def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: return {'self': self} Tried searching for the await expressions, checked the middlewares, even the whitenoise. Didn't find anything -
Fail to map ports from docker container
I managed to start a Docker container with a trivial django application. But I do not know why can't I access it from my browser? I used this command: docker run -p 8000:8000 --name c1 django:1 screenshot of my terminal But I still can't access django app from the web-browser. enter image description here Here is my Dockerfile: FROM python:3-slim ENV PYTHONUNBUFFERED=1 #RUN addgroup app && adduser -S -G app app #USER app WORKDIR /app/ COPY requirements.txt . RUN pip install -r requirements.txt COPY . . ENV API_URL=http://api.myapp.com EXPOSE 8000 CMD ["python", "manage.py", "runserver"] Could you please tell me what I am doing wrong so I can't access django app from the terminal please? I tried searching and troubleshooting but no effect. -
Cannot access django-admin panel on port
Expecting to be able to access django admin panel and add social accouunt opening admin panel by adding standard admin/ extension to local preview port URL. This is expected to lead to classic django admin panel. going to the admin url instead leads to an error message the website is otherwise displaying fine. A simple google oath signin is currently being implemented. Error message: DoesNotExist at /admin/login/ Site matching query does not exist. Request Method: GET Request URL: http://8000-lmcrean-project4-avaw7dd1zq8.ws-eu106.gitpod.io/admin/login/?next=/admin/ Django Version: 3.2.23 Exception Type: DoesNotExist Exception Value: Site matching query does not exist. Exception Location: /workspace/.pip-modules/lib/python3.9/site-packages/django/db/models/query.py, line 435, in get Python Executable: /home/gitpod/.pyenv/versions/3.9.17/bin/python3 Python Version: 3.9.17 Python Path: ['/workspace/Project-4', '/home/gitpod/.pyenv/versions/3.9.17/lib/python39.zip', '/home/gitpod/.pyenv/versions/3.9.17/lib/python3.9', '/home/gitpod/.pyenv/versions/3.9.17/lib/python3.9/lib-dynload', '/workspace/.pip-modules/lib/python3.9/site-packages', '/home/gitpod/.pyenv/versions/3.9.17/lib/python3.9/site-packages'] Server time: Sat, 11 Nov 2023 15:17:58 +0000 traceback details in full Currently trying to fix with this tutorial “Set up Google Sign-in for Faster Django Login Experience Feat. Tech with Tim.” Akamai DevRel, YouTube Video, 12 Dec. 2022, https://youtu.be/yO6PP0vEOMc?feature=shared&t=1328. Accessed 11 Nov. 2023. have followed correctly with all working up to 22 minutes in migration was recently made after setting up urls, views and templates for google oauth as per the tutorial, there were no obvious issues with this before that django-admin panel seemed to … -
Save the images of ckeditor fields to local media and not s3
I'm working on a django project and I have used s3 cloud storage to save my media files. The challenge that I have faced is that I want the images of ckeditor fields to be saved on local and not s3. How should I do that? I haven't found any solution for my problem in any community -
revoking celery task, redis broker
I'm trying to revoke, terminate, abort or getting currently active tasks from celery in a django project; all methods are sent to worker after the currently running task has been finished, look at logs here: [2023-11-11 17:50:01,299: INFO/MainProcess] Task NPS.tasks.keys[8e4136d8-f9f8-45bf-9f29-5e0dbf11235d] succeeded in 98.43799999996554s: {'count': 10683923 } [2023-11-11 17:50:01,339: DEBUG/MainProcess] pidbox received method active(safe=None) [reply_to:{'exchange': 'reply.celery.pidbox', 'routing_key': '4bb6ba45-6e90-346d-89f9-01731fee3fa4'} ticket:c822c5ec-37b0-44a8-a721-675a328532ca] [2023-11-11 17:50:01,340: DEBUG/MainProcess] pidbox received method reserved() [reply_to:{'exchange': 'reply.celery.pidbox', 'routing_key': '1a5ee3c4-a5df-3642-a853-6a6fcba4a215'} ticket:ca112a23-39b4-4978-bdee-36b7cb13cc4d] [2023-11-11 17:50:01,343: DEBUG/MainProcess] pidbox received method revoke(task_id='c6bf8ad6-787a-4a76-ab4a-edb804fc8cdd', terminate=True, signal='SIGTERM') [reply_to:None ticket:None] [2023-11-11 17:50:01,345: INFO/MainProcess] Task NPS.tasks.keys[c6bf8ad6-787a-4a76-ab4a-edb804fc8cdd] received [2023-11-11 17:50:01,345: INFO/MainProcess] Discarding revoked task: NPS.tasks.redis_keys[c6bf8ad6-787a-4a76-ab4a-edb804fc8cdd] [2023-11-11 17:50:03,330: DEBUG/MainProcess] Timer wake-up! Next ETA 1.0 secs. active, reserved and revoke method has been called during the process of task, but none of them executes on time. what should I do? and whats the solution? -
login to a seperate user group in django
I have created a distinct user registration in django. class Trainer(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) bio = models.TextField(blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = TrainerManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] groups = models.ManyToManyField(Group, related_name='trainer_groups', blank=True) user_permissions = models.ManyToManyField(Permission, related_name='trainer_user_permissions', blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" i have created a user signup from and its working. I am facing challenges while trying into logging in to the user. Its always showing "Please enter a correct username and password. Note that both fields may be case-sensitive." any idea on how to specify the trainer user model while logging in? The new User model is under TRAINERS app have tried logging in using the below code def trainer_login(request): if request.method == 'POST': form = AuthenticationForm(request, data=request.POST) if form.is_valid(): email = form.cleaned_data.get('username') # Use email as the username field password = form.cleaned_data.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) messages.success(request, 'Login successful.') # Redirect to the desired page after login return redirect('dashboard') # Change 'dashboard' to your desired URL name else: messages.error(request, 'Invalid email or password.') else: form = AuthenticationForm() return render(request, 'trainer_login.html', {'form': … -
Lost local file main.css after commit & push
I've finished my project and was trying to commit and push changes. I trought it was successfully, but when I went to the site I saw that there are no styles. Everything was committed successfully except main.css. It was replaced from last commit to my local pc and full-done css file was delated respectively PS. Commit and push were done by PyCharm PS2. Pycharm Local History - Show History not available for main.css I tried git reflog, but nothing heppened. Here's my tries: PS D:\PyProjects\ElectricCarsStore> git reflog 9b2ccd3 (HEAD, origin/master) HEAD@{0}: checkout: moving from c6f4aa2b2196603cd1af12e0e06ae9e6767b8b1a to 9b2ccd3 c6f4aa2 HEAD@{1}: checkout: moving from afcf0469d2369145e0296eac5b7e693a0508ba29 to c6f4aa2 afcf046 (master) HEAD@{2}: checkout: moving from master to afcf046 afcf046 (master) HEAD@{3}: reset: moving to afcf046 9b2ccd3 (HEAD, origin/master) HEAD@{4}: merge origin/master: Merge made by the 'ort' strategy. c6f4aa2 HEAD@{5}: commit: Ready project v.1.0 afcf046 (master) HEAD@{6}: commit (initial): Initial commit I will be grateful for your advice. -
django doesn't apply all css properties
I want to port my .html file to django project. I edited the file and inserted static tags, transferring .html and .css files into the django project, django did not apply all the styles specified in the .css file that's how page looks in vs code:vs code and how it's looks in django: django so, you can see several blocks that are not in vs code, but they are displayed in django, this is because the style file specifies "display: none" for these classes, but django ignores these how can i fix this problem? -
axios give me error (POST /api/v1/users/token/refresh/ HTTP/1.1" 401 65) , How solve it?
in windows 10 , i'm using react-router-dom 5.2.0 and react-redux 7.2.5 and react 17.0.2. and axios 0.21.4 and WebStorm 2023.1.3 IDE. Consider 1 - axiosInstanse.js: import jwt_decode from 'jwt-decode'; import dayjs from 'dayjs'; import axios from 'axios'; import {updateAccessToken} from '../actions/userActions'; const baseURL = 'http://127.0.0.1:8000'; const axiosInstance = (userInfo , dispatch) => { const instance = axios.create({ 'mode': 'cors', baseURL, headers: { 'Content-Type': 'application/json', Authorization:`Bearer ${userInfo?.access}`, } }); instance.interceptors.request.use(async req=> { try { const user = jwt_decode(userInfo.access); const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 5000; if (!(isExpired)) { return req } const response = await axios.post( '/api/v1/users/token/refresh/' , {refresh:userInfo.refresh}, ); dispatch(updateAccessToken(response.data)) req.headers.Authorization = `Bearer ${response.data.access}`; return req; } catch (error) { console.log(error) } }); return instance } export default axiosInstance; Consider 2 - userActions.js: export const userFurtherInformationAction = (image, gender) => async (dispatch, getState) => { try { dispatch({ //USER FURTHER INFORMATION REQUEST type: USER_FURTHER_INFORMATION_REQUEST, }); const {userLogin: {userInfo}} = getState(); const formData = new FormData(); const image_url = URL.createObjectURL(image) formData.append('userPicture', image); formData.append('sex', gender); // var object = {}; // formData.forEach(function(value, key){ // object[key] = value; // }); // var json = JSON.stringify(formData); // const config = { // 'mode': 'cors', headers: { // // 'Content-type': 'multipart/form-data', 'Authorization': `Bearer ${userInfo.token}` // } … -
token authentication in django rest framewok is not working with digitalocean, but it is working perfectly in my local
i have deployed a django rest framework in digitalocean,eveything is working perfectly when make a post and get request with postman software,but when make a post request to this TestView which is bellow, it is showing this error : "Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x7f10fecb2ed0>." in this line : score = Score.objects.get(user=request.user.id). this is the TestView : class TestView(APIView): authentication_classes = [TokenAuthentication] def get(self, request): questions = Question.objects.all() questions_serializer = QuestionsSerializer(questions,many=True,context={'request': request}) return Response(questions_serializer.data) def post(self, request): question_id = request.data.get('id') user_answer = request.data.get('answers') correct_answer = Answer.objects.filter(question=question_id, is_correct=True).values_list('answer', flat=True).first() if correct_answer is not None: if user_answer == correct_answer: try: score = Score.objects.get(user=request.user.id) print(self.user) score.score += 1 score.save() except Score.DoesNotExist: score = Score.objects.create(user=request.user, score=1) score_serializer = ScoreSerializer(score) return Response({'message': 'your answer was correct', 'score': score_serializer.data}, status=status.HTTP_200_OK) else: return Response({'message': 'your answer was incorrect'}, status=status.HTTP_400_BAD_REQUEST) else: return Response({'message': 'correct answer not found for this question'}, status=status.HTTP_404_NOT_FOUND) if hard coded the user id in this line of code like this: instead of this : score = Score.objects.get(user=request.user.id) changed to this : score = Score.objects.get(user=1) then it works. i also printed the print(request.user),print(request.user.id) and print(request.auth) they are null, but in my local print(request.user) is printing the user. i also contact …