Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - LogoutView - cache_control - browser's back button has the logged out user's cache
Django 2.1.7 This is for a simple blog with homepage (post list view), post detail view, and profile (post list view) When a user logs out, LOGOUT_REDIRECT_URL = '/' redirects the user to the homepage. However, when the user clicks the browser's back button, the previous page still shows all the logged out user's data. When I reload the page, it clears the cache. when the user's logged in, shows username] when the user's logged out, shows 'login' I found a similar question and their answer was to use the cache_control decorator. Django - User re-entering session by clicking browser back button after logging out @cache_control(no_cache=True, must_revalidate=True, no_store=True) @login_required Would I have to add these decorators to every single view? I do not want the @login_required decorator. AnonymousUsers should be able to view all pages without logging in. What's the best way to do this? Similar to Twitter's logout flow. (user logs out -> login page -> back button -> previous page but reloaded) urls.py from django.contrib.auth import views as auth_views urlpatterns = [ path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), -
Integrating Razorpay Payment Gateway with Django causing CSRF verification failure
This question was previously asked here but I didn't have 50 reputation points to continue the discussion on that answer itself. Short version Essentially, the problem boils down to - I have an external URL that sends POST data to my Django application. I want to access this POST data but Django is giving 403 error (CSRF Token missing). Detailed version I am trying to add Hosted Payment Gateway of Razorpay to my Django Project. I have passed the URL to the following function in the callback functionality. As specified in the previous answer, I tried using the csrf_exempt decorator and adding the https://api.razorpay.com URL as CSRF_TRUSTED_DOMAINS in the settings.py file, but the issue still remains. I am still getting the 403 error from Django when the payment is successful. @csrf_exempt def course_purchase_callback(request): payment_id = request.POST.get("razorpay_payment_id") order_id = request.POST.get("razorpay_order_id") signature = request.POST.get("razorpay_signature") client = razorpay.Client(auth=(os.getenv("RZP_ID"), os.getenv("RZP_SECRET"))) verify = client.utility.verify_payment_signature({ "razorpay_payment_id": payment_id, "razorpay_order_id": order_id, "razorpay_signature": signature, }) settings.py file .. .. .. CSRF_TRUSTED_ORIGINS = ["https://api.razorpay.com"] .. .. Versions being used: Django = 4.0.3 Razorpay API = 1.3.0 What is the thing I am missing here? -
In views.py ### category_posts = Post.objects.filter(category = cat) ### RETURNS AN EMPTY QUERY SET
I am creating a blog application in django where i encountered this unusual issue. I am not being able to filter and display blog posts category wise. Please find my code below. Thanks in advance. MODELS.py This is the model which i have created for a blog post. class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default="uncategorized") def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): #return reverse('article-detail', args=(str(self.id))) return reverse('homepage') VIEWS.py This is the view that i have created for a category wise blog posts. def CategoryView(request,cats): category_posts = Post.objects.filter(author= 'apaar') return render(request,'categories.html',{'cat':cat,'category_posts':category_posts}) URLS.py The urls.py file. path('category/<str:cat>/', CategoryView, name = 'category'), CATEGORIES.html This will be the final display page where the category_posts is displayed as an empty queryset. The for loop is unable to run because category_posts is an empty queryset. {% extends 'base.html' %} {% load static %} {% block content %} <h1>Categories</h1> <ul> {% for posts in category_posts %} <li> <div class="category"><a href="{% url 'category' post.category|slugify %}">{{ post.category }}</a></div> <a href="{% url 'article-detail' post.pk %}"><h3><b>{{ post.title }} </b></h3> <p class=card-date> <big>{{ post.author }}</big><small> -{{ post.post_date }} </small> </p> <p class="excerpt-text">{{ post.body | slice:"100" … -
Save uploaded file Django Jquery Ajax
I am quite new in Python and Django and because im working on a big porject it's a bit difficult to see what I'm doing wrong. I would like to save the uploaded File in my repository folder. <form action="/action_page.php" enctype="multipart/form-data"> <label for="myfile">Select a file:</label> <input type="file" id="myfile" name="myfile" multiple="multiple" /> <br /><br /> <input id="upload_submit" type="submit" /> </form> This is my views file, I dont really understand how the communication between the modules work here @csrf_exempt def get_text(self, request): rand_int = random.random() return JsonResponse({"text": "Random number: " + str(rand_int)}, status=200) @csrf_exempt def save_uploaded_file(self, request): rand_int = random.random() return JsonResponse({"text": "Random number: " + str(rand_int)}, status=200) My urls look like this urlpatterns = [ path("admin/", admin.site.urls), path("save_uploaded_file/", url_Handler_Wrapper.save_uploaded_file, name="save_uploaded_file"), path("get_text/", url_Handler_Wrapper.get_text, name="get_text"), path("tasks/", url_Handler_Wrapper.run_task, name="run_task"), path("", url_Handler_Wrapper.home, name="home"), ] And this is my javascript $('#upload_submit').on('click', function() { var formData = new FormData(Document.querySelector('#myfile')) $.ajax({ url: '/save_uploaded_file/', type: 'POST', data: formData, success: function (response) { if (response) { formData.write("/") } }, error: function (error) { console.log(error) }, cache: false, contentType: false, processData: false }); return false; }); -
how to make password confirmation with Django form
I have created a (CustomUserForm) like the below: from django.contrib.auth.forms import UserChangeForm from .models import User from django import forms class CustomUserForm(UserChangeForm): username = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter Username'})) email = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter The Email'})) password1 = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter The Password'})) password2 = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control my-2', 'placeholder': 'Confirm Password'})) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] and the corresponding view to create a new user: from django.contrib.auth.models import User from django.contrib.auth.hashers import make_password def register(request): if request.method == 'POST': form = CustomUserForm(request.POST) if form.is_valid(): username=form.cleaned_data['username'] email=form.cleaned_data['email'] password=make_password(form.cleaned_data['password1']) data=User(username=username,email=email,password=password) data.save() messages.success(request, "Registered Successfully") return redirect('/login/') else: #Here GET condition form = CustomUserForm() context = {'form': form} return render(request, 'auth/register.html', context) and this is the register.html {% extends 'layouts/main.html' %} {% block title %} {{ category }} {% endblock %} {% block content %} <section class="vh-100" style="background-color: #eee;"> <div class="container h-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="col-lg-12 col-xl-11"> <div class="card text-black" style="border-radius: 25px;"> <div class="card-body p-md-5"> <div class="row justify-content-center"> <div class="col-md-10 col-lg-6 col-xl-5 order-2 order-lg-1"> <p class="text-center h1 fw-bold mb-5 mx-1 mx-md-4 mt-4">Sign up</p> <form class="mx-1 mx-md-4" action="" method="POST"> {% csrf_token %} <div class="d-flex flex-row … -
Authentication process canceled
I am developing a django project.And I want to add login with facebook.But I tried days and days but everytime I get this error Authentication process canceled.Please can anyone help me? settings.py INSTALLED_APPS 'social_django', MIDDLEWARE 'social_django.middleware.SocialAuthExceptionMiddleware', context_processors 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', AUTHENTICATION_BACKENDS 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.google.GoogleOAuth', 'django.contrib.auth.backends.ModelBackend', and other settings SOCIAL_AUTH_RAISE_EXCEPTIONS = False SOCIAL_AUTH_FACEBOOK_KEY = env("SOCIAL_AUTH_FACEBOOK_KEY") SOCIAL_AUTH_FACEBOOK_SECRET = env("SOCIAL_AUTH_FACEBOOK_SECRET") SOCIAL_AUTH_FACEBOOK_API_VERSION = '2.8' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = env("SOCIAL_AUTH_GOOGLE_OAUTH2_KEY") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = env("SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET") LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' LOGIN_URL="/giris" LOGOUT_URL="/cikis" SOCIAL_AUTH_LOGIN_ERROR_URL = '/giris' SOCIAL_AUTH_BACKEND_ERROR_URL="/giris" LOGIN_ERROR_URL="/giris" SOCIAL_AUTH_LOGIN_REDIRECT_URL="/" SOCIAL_AUTH_LOGIN_REDIRECT_URL="/" -
Salesforce foreign key field name
In our project we use Salesforce library in Django. We have class which include the raw: class SalesforceContact(models.Model): account = models.ForeignKey(SalesforceAccount, models.DO_NOTHING, db_column='AccountId', blank=True, null=True, related_name='contacts') When we get the result all_contacts = SalesforceContact.objects.filter(xxxxxxx).all() the attributes of all_contacts doesn't contain 'account' but 'account_id' field. It's not API so I'm not using serializers. Am I wrong and there is a bug? How can I change the name of attribute? -
How to define columns from dictionary keys with Django tables 2?
I would like to create a table from multiple objects from a Django model called MyModel. The data are stored in a JSONField called weights with datetime as key like this {"2022-05-01T05:00:00Z": 0.123}. The name of the column should comes from a CharField called name. As you can see in the code below I iterate through the objects and create a Pandas Series to extract value and populate a dictionary. But how can I tell tables to take the column name from the dictionary key ? of is there a possibility to pass the columns names dierctly with a list ? view.py class MyappDetailView(SingleTableMixin, generic.DetailView): model = Country def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) dic = dict() for obj in MyModels.objects.filter(one_field=self.object): s = pd.Series(obj.weights)[-15 * 24:] * 100 dic['Datetime'] = s.index.tolist() dic[obj.name] = s.values.tolist() table_2 = WeightTable(dic) context['table'] = table_2 return context table.py import django_tables2 as tables class WeightTable(tables.Table): Datetime = tables.Column() key_1 = tables.Column() # here I would like to declare the name of the columns fom the key key_2 = tables.Column() key_3 = tables.Column() ... -
Django MultipleChoiceField field with filter
what should I write here to filter participants by event ID forms.py participants = forms.ModelChoiceField(queryset=Participant.objects.none(), empty_label=None,), so that I do not write to the queryset, I get all participants from all events. And I need to see those participants who sent an application for this event view.py form = EventForm(request.POST or None, instance=event) form.fields['participants'].queryset = Participant.objects.filter(event_id=Event.pk) would be very grateful for help -
my website is taking so much CPU on my computer
i'm using in this project django with pure css and js and it seems that my website is consuming so much cpu also i'm using a gradient animation with css body { background: linear-gradient(to right, rgb(247, 85, 202), rgb(18, 103, 248)); background-size: 400% 400%; animation: gradient 15s ease infinite; }.nav-link ,.navbar-brand ,.nav-link:hover ,.navbar-brand:hover { background: linear-gradient(to right, rgb(247, 85, 202), rgb(18, 103, 248)); -webkit-background-clip: text; background-size: 400% 400%; color: transparent; animation: gradient 15s ease infinite; } @keyframes gradient { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } } in addition i'm using event listener to whole document using Javascript document.querySelectorAll('.edit').forEach((button) => { . . . }) document.querySelectorAll('.filter-green').forEach(like => {...}) -
how do i solve the following Django serializer error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Article'
Im quite new to django but i cant find the solution in the docs My question: I have a model with 2 OneToOne relations: class Slotting(ICSBaseMixin): # database fields article = models.OneToOneField( "ics_stock.Article", on_delete=models.CASCADE, related_name="slotting", null=False ) article_location = models.OneToOneField( "ics_stock.ArticleLocation", on_delete=models.CASCADE, null=False, related_name="slotting" ) def __str__(self): return str(self.record_id) class Meta: db_table = "ICS_Stock_Slotting" verbose_name = "Slotting" verbose_name_plural = "Slottings" # noqa I want to create and save a new instance through a serializer. serializer: class SlottingCreateUpdateSerializer(serializers.ModelSerializer): def update(self, instance, validated_data): article = validated_data.pop("article") instance.article_id = article article_location = validated_data.pop("article_location") instance.article_location_id = article_location instance.save() return instance def create(self, validated_data): article_id = validated_data.pop("article") article = get_object_or_404( Article, record_id=article_id ) article_location_id = validated_data.pop("article_location") article_location = get_object_or_404( ArticleLocation, record_id=article_location_id ) slotting = Slotting() slotting.article_location = article_location, slotting.article = article slotting.save() return slotting Now when trying to serialize and save i get the following error: raceback (most recent call last): File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'Article' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\core\handlers\base.py", line … -
Django Model.delete() not working in signal
I am trying to delete a model instance from within a signal callback @receiver(m2m_changed) def many_to_many_changed(sender, instance, action, **kwargs): if action == "post_remove": if not instance.invoices.all().exists(): payment = Payment.objects.get(pk=instance.pk) payment.delete() instance.delete() This is my code but neither instance.delete() or payment.delete() deletes anything, I have also tried to put Payment.objects.all().delete() but nothing changed. What could I try to do? Is it possible to do what I am trying to accomplish? -
django rest save api to bd
My task is to accept a post request with a link to a public api, and then save the data from json to my database, and display the last entry (before adding). I do all this in django rest. The problem is that I do not understand how to make a working serializer that accepts a link. Model serializer: class QSerialaizer(serializers.Serializer): color = serializers.CharField() age = serializers.CharField() Function that returns api by url: def j_request(url): response = requests.get(url) data = json.dumps(response.json(), sort_keys=True, indent=4) return(data) And finally, the function that I can't get is the post request in the view: def post(self, request): queryset = Cats.objects.all() data = request.data num = data['url'] for item in jservice_request(url): Question.objects.create( color=item['color'], age=item['age'] ) return Response({'queryset': queryset}) Is it necessary to use a serializer to create an entry in the database, and how to do it? -
is it possible to have two parameters in limit_choices_to in django models?
I'll shorten the code as simple as possible. Supposedly, we do have two models. models.py > Products table CATEGORY = ( ('Hard Disk Drive', 'Hard Disk Drive'), ('Solid State Drive', 'Solid State Drive'), ('Graphics Card', 'Graphics Card'), ('Laptop', 'Laptop'), ('RAM', 'RAM'), ('Charger', 'Charger'), ('UPS', 'UPS'), ('Mouse', 'Mouse'), ('Keyboard', 'Keyboard'), ('Motherboard', 'Motherboard'), ('Monitor', 'Monitor'), ('Power Supply', 'Power Supply'), ('Router', 'Router'), ('AVR', 'AVR'), ('Tablet', 'Tablet'), ('System Unit', 'System Unit'), ('Audio Devices', 'Audio Devices'), ('CPU', 'CPU'), ('Others', 'Others'), ) class Product(models.Model): model_name = models.CharField(max_length=100, null=True, blank=True) asset_type = models.CharField(max_length=20, choices=CATEGORY, blank=True) date = models.DateField(null=True, blank=True) And the other table > Order table class Order(models.Model): product_order = models.ForeignKey(Product, on_delete=models.CASCADE, null=False) employee = models.ForeignKey(User, models.CASCADE, null=False) date = models.DateTimeField(auto_now_add=True) remarks = models.TextField() And we all know that adding this code will limit the foreignkey choices under the Order form. limit_choices_to={"asset_type": "Hard Disk Drive"} limit_choices_to={"asset_type": "Solid State Drive"} My goal here is to show items from Products table whose asset_type is either "Hard Disk Drive" OR "Solid State Drive". I've read the documentation of Django for "limit_choices_to" and can't see any pertaining to some kind of solution in here. Thank you in advance who knows a way to make this possible. -
Getting ProgrammingError: relation "auth_user" does not exist while running test
Lately I faced this problem that is driving me crazy and didn't find any solution on the internet. I don't no when the problem created or what did I do that caused this but now every time I want to run my test in my Django app this errors show up: Traceback (most recent call last): File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/mohammad/Projects/IP_Camera/manage.py", line 22, in <module> main() File "/home/mohammad/Projects/IP_Camera/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/commands/test.py", line 68, in handle failures = test_runner.run_tests(test_labels) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/test/runner.py", line 1000, in run_tests old_config = self.setup_databases( File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/test/runner.py", line 898, in setup_databases return _setup_databases( File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/test/utils.py", line 220, in setup_databases connection.creation.create_test_db( File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/db/backends/base/creation.py", line 79, in create_test_db call_command( File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 198, in call_command return command.execute(*args, **defaults) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File … -
I am facing django api error. manage.py runserver is throwing importError
ImportError: cannot import name 'smart_text' from 'django.utils.encoding' (/home/ubuntu/django/env/lib/python3.8/site-packages/django/utils/encoding.py) -
password1 and password2 doesn't save in django form
I have created a (CustomUserForm) like the below: from django.contrib.auth.forms import UserChangeForm from .models import User from django import forms class CustomUserForm(UserChangeForm): username = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter Username'})) email = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter The Email'})) password1 = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter The Password'})) password2 = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control my-2', 'placeholder': 'Confirm Password'})) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] and the corresponding view to create a new user: from django.shortcuts import render, redirect from django.contrib import messages from store.forms import CustomUserForm def register(request, self): form = CustomUserForm() if request.method == 'POST': form = CustomUserForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Registered Successfully") return redirect('/login') context = {'form': form} return render(request, 'auth/register.html', context) def login_page(request): return render(request, 'auth/login.html') and this is the register.html {% extends 'layouts/main.html' %} {% block title %} {{ category }} {% endblock %} {% block content %} <section class="vh-100" style="background-color: #eee;"> <div class="container h-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="col-lg-12 col-xl-11"> <div class="card text-black" style="border-radius: 25px;"> <div class="card-body p-md-5"> <div class="row justify-content-center"> <div class="col-md-10 col-lg-6 col-xl-5 order-2 order-lg-1"> <p class="text-center h1 fw-bold mb-5 mx-1 mx-md-4 mt-4">Sign up</p> <form class="mx-1 mx-md-4" action="" method="POST"> {% csrf_token %} … -
Dockerfile/Docker-compose for react app that is inside of a django project
I created a django project that contains a folder called 'frontend' (I did python startapp frontend for this). This folder contains my react components and frontend logic. I created a Dockerfile and docker-compose.yml in the main directory with the 'manage.py' file. The directory looks like the following: Image of Directory So far, I have this for my Dockerfile: FROM python:3.8-alpine ENV PYTHONUNBUFFERED=1 WORKDIR /pathfinder COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . . My docker-compose.yml looks like: version: "3.8" services: app: build: . volumes: - .:/django ports: - 8000:8000 image: app:django container_name: django_container command: python manage.py runserver 0.0.0.0:8000 I believe that I need to install the dependencies in the package.json file in my frontend folder, but how would I do that in my docker container? -
why is Django not accepting the file sending from React Native app?
I am using Django for the Backend Server and React Native for a mobile app I am trying to upload an image from there but it is giving a 500 server error. Views.py form Django @api_view(['POST']) def setFakeProfile(request): if request.method=='POST': user = Token.objects.get(key = request.META.get('HTTP_AUTHORIZATION').split(' ')[1]).user profile = Profile.objects.get(user=user) fakeProfiles = profile.fakeProfiles.filter(isProfileReadyToUse=False) print(request.data) print(request.FILES) if fakeProfiles.exists(): fakeProfile = fakeProfiles[0] fakeProfile.displayName = request.data["displayName"] fakeProfile.profilePicture = request.FILES.get('profilePicture') fakeProfile.isProfileReadyToUse = True fakeProfile.save() return Response({'status':'success', 'id':fakeProfile.id}) else: return Response({'status':'failed', "message":"First select the chating platform."}) return Response({ 'status':'success', }) return Response({'status':'failed'}) The error that I am getting is there. I knew about the error and I also tried a lot of ways to resolve it but not still don't know how to fix it. {'_parts': [['displayName', 'name'], ['profilePicture', {'cancelled': False, 'type': 'image', 'uri': 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sumit2232%252FUnknownChats/ImagePicker/584abe5b-7f5e-45cb-81bd-fcb5751e3ed4.png', 'width': 1692, 'height': 1692}]]} app_1 | <MultiValueDict: {}> app_1 | Internal Server Error: /setFakeProfile/ app_1 | Traceback (most recent call last): app_1 | File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner app_1 | response = get_response(request) app_1 | File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response app_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) app_1 | File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view app_1 | return view_func(*args, **kwargs) app_1 | File "/py/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view app_1 … -
Can users switch months on website using python calendar library
i am making web application with django. I am using python calendar library to create HTML calendar. I was wondering if there is a builtin way to allow users switch months while on website or if i have to make it work using JavaScript. Thanks for help. -
TypeError: create_superuser() missing 2 required positional arguments
I am trying to createsuper user when I entered email and password I got this error File "/mnt/c/Users/ZAKARIA/Desktop/project/env/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 232, in handle self.UserModel._default_manager.db_manager(database).create_superuser( TypeError: create_superuser() missing 2 required positional arguments: 'first_name' and 'last_name' my class managers from django.contrib.auth.base_user import BaseUserManager class UserManger(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError("Users must have an email address") if not first_name or last_name: raise ValueError("Users must have a first and last name") user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email,password, first_name, last_name): user = self.create_user( email=self.normalize_email(email), password=password, first_name=first_name, last_name=last_name, ) user.set_password(user.password) #user.is_staff = True user.is_superuser = True #user.is_admin = True user.save(using=self._db) return user I have been seeing a lot of questions similar to this but i still don't understand the answers given, some say add positional arguements, I don't quite understand can any one help me to solve this problem ? -
Django error with User form: AttributeError: 'tuple' object has no attribute '_meta'
i followed the lesson to make a user register using Django, he made this code, like what I have made: class CustomUserForm(UserChangeForm): username = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter Username'})) email = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter The Email'})) password1 = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter The Password'})) password2 = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control my-2', 'placeholder': 'Confirm Password'})) class Meta: model = User, fields = ['username', 'email', 'password1', 'password2'] when run the server this errors displayed: PS E:\osamaStartup> py manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "E:\deep\lib\threading.py", line 973, in _bootstrap_inner self.run() File "E:\deep\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "E:\deep\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "E:\deep\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "E:\deep\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "E:\deep\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "E:\deep\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "E:\deep\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "E:\deep\lib\site-packages\django\urls\resolvers.py", line 480, in check for pattern in self.url_patterns: File "E:\deep\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "E:\deep\lib\site-packages\django\urls\resolvers.py", line 696, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "E:\deep\lib\site-packages\django\utils\functional.py", … -
Styles not loading in Django
I have a site that needs some custom styles in Django and I can't get the static file to load. I have a static folder inside my main folder - The one where manage.py lives, Inside there is a CSS folder that contains a style.css. At the top of base.html, I load {% load static %} Then in the head of my HTML I load <link rel="stylesheet" href="{% static 'css/styles.css' %}"> and in my settings.py file I have loaded in # Static file route STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] When I load I just get a blank CSS file and no styles load, I'm fairly new to Django so please be kind, and thanks in advance. -
Allow empty foreign key selection in admin forms
i created a model(AnalysisFieldTemplate) with a foreign key to AnalysisFieldRule. What i want is to have the possibility to leave the field display_analysis_field_rule blank and save my admin form. class AnalysisFieldRule(models.Model): action_kind: str = models.CharField( choices=ActionKind.choices, default=ActionKind.DISPLAY, max_length=text_choices_max_length(ActionKind), verbose_name=_("action kind"), ) formula: str = formula_field() name: str = models.CharField(max_length=MAX_NAME_LENGTH, verbose_name=_("name")) def __str__(self): return f"{self.name}: {ActionKind(self.action_kind).label}" class Meta: constraints = [ UniqueConstraint(fields=("action_kind", "name"), name="%(app_label)s_%(class)s_is_unique"), ] ordering = ["name", "action_kind"] verbose_name = _("analysis field rule") verbose_name_plural = _("analysis field rules") class AnalysisFieldTemplate(models.Model): display_analysis_field_rule: AnalysisFieldRule = models.ForeignKey( AnalysisFieldRule, blank=True, limit_choices_to={"action_kind": ActionKind.DISPLAY}, null=True, on_delete=models.PROTECT, related_name="display_analysis_field_templates", verbose_name=_("display rule"), ) Now here is the problem. If i try to save my admin form without choosing one a value for display_analysis_field_rule it will result in an Validationerror. It seems that the standard empty value for a foreign key "------" is not a valid choice. @admin.register(AnalysisFormTemplate) class AnalysisFieldTemplateAdmin(admin.ModelAdmin): fieldsets = ( ( None, { "fields": ( "name", "name_for_formula", "ordering", "required", "kind", "display_analysis_field_rule", "highlight_analysis_field_rule", ) }, ), ( _("Text options"), {"fields": ("max_length",)}, ), ( _("Integer options"), {"fields": ("min_integer_value", "max_integer_value")}, ), (_("Amount of money options"), {"fields": ("min_amount_of_money", "max_amount_of_money")}), ) I debugged a little deeper and found that the "to_python" compares the choosen value with pythons standard "empty_values" but of course … -
Djongo + Django + MongoDB not support chainning filter
I have two model: Content and Tag that have ManyToMany realationship Content(models.Model): tags = models.ManyToManyField(Tag, null=False, blank=False, related_name="tags") Tag(models.Model): slug = models.CharField(max_length=255, null=False, blank=False, unique=True) name = models.CharField(max_length=255, null=False, blank=False, unique=True) Notice that I'm using MongoDB and djongo connector to work with my db. Now I want to filter "All of content that have n specific tags", example: all of the content that have tags = ["Movie", "News", "Science"], suppose id of them is: 1, 2, 3 corresponding. I have used chaining filter. content.objects.filter(tags=1).filter(tags=2).filter(tags=3) but it return not found. Yep, of course contents that have id = [1, 2, 3] are available in my database. But when I migrate to MySQL and try again, it work and return a queryset that I expected.