Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending information through Django channels from a view function
I am currently trying to set up a user interface for my app with Django. Basically, I want to send the user updates about what is going on in the backend when he starts a task (do like a loading bar or display the number of steps remaining, for instance) and thought of using Django channels for that. I set up my rooting.py, consumers.py files as well as asgi.py file, and everything is working correctly. However, I want to be able to send the user information through a function in views.py and I am not sure how I can do that, since I don't know how to identify the socket the user is currently connected to from the views.py and how to send information through it. I might be completely wrong using Django channels, maybe there's another (simpler) way of doing so, so I would like to have your advice on that! Thank you! -
selenium tests in django webapp don't work
I'm doing some tests on my django webapp. I install firefox(geckodriver) webdriver in /home/nicola/selenium_drivers/geckodriver, set execution permission and so on. Here is my test from django.test import TestCase from django.test import LiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from pygiustizia.models import Users from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.firefox.options import Options from datetime import datetime, date class ViewsTopicsTestCase(LiveServerTestCase): USERNAME = None PASSWORD = None BASE_URL = None def setUp(self): self.BASE_URL = self.live_server_url self.USERNAME = 'nicolapaganotti1@gmail.com' self.PASSWORD = '$2b$12$Xv0W8PCBnGTqNpo96gxS/e3olh685kMyxE2tFM028Ex7bz/7Y3nMS' d = datetime(2022, 7, 20, 10, 10, 10, 342380) options = Options() #options.binary_location = '/usr/bin/firefox' options.add_argument("binary_location=/usr/bin/firefox") self.driver = webdriver.Firefox(options=options,executable_path=r'/home/nicola/selenium_drivers/geckodriver') #self.driver = webdriver.Firefox() # create user self.user = Users.objects.create_user(username=self.USERNAME, admin=1, firstname="Nicola", lastname="Paganotti", created_at=d, password=self.PASSWORD) def tearDown(self): self.driver.quit() def test_login(self): self.driver.get(self.BASE_URL + '/pygiustizia/login') username = self.driver.find_element_by_name("username") username.send_keys(self.USERNAME) password = self.driver.find_element_by_name("password") password.send_keys(self.PASSWORD) btn_login = self.driver.find_element_by_name("submit_login") # Login btn_login.click() # Check home page WebDriverWait(self.driver, 5).until( EC.presence_of_element_located((By.CSS_SELECTOR, '.selAddField'))) When I launch python3.9 manage.py test I get this output in terminal: Traceback (most recent call last): File "/var/www/html/elastic_queries/python/djangosite/giustiziasite/pygiustizia/tests/test_views_topics.py", line 33, in setUp self.driver = webdriver.Firefox(options=options,executable_path=r'/home/nicola/selenium_drivers/geckodriver') File "/usr/local/lib/python3.9/dist-packages/selenium/webdriver/firefox/webdriver.py", line 177, in __init__ super().__init__( File "/usr/local/lib/python3.9/dist-packages/selenium/webdriver/remote/webdriver.py", line 277, in __init__ self.start_session(capabilities, browser_profile) File "/usr/local/lib/python3.9/dist-packages/selenium/webdriver/remote/webdriver.py", line 370, in start_session response … -
Django filter using DateTimeField that can be null
I want to filter a table objects using a DateTimeField => last_user_action_time, this field can be null so I need the cases where its null to be included in the result. Here is what I tried: notification_objects = SinglePushNotification.objects.filter( last_user_action_time__lte=day_start, last_user_action_time__isnull=True, ).select_related("customer") This return an empty querySet knowing there is objects where null=True -
Running pyramid and django side by side
We have a pyramid application that provides API endpoint. Now we want to implement frontend as well but to our surprise, i10n/l10n tooling in pyramid is not as good as in django. So I have been thinking what if we implement the frontend with django instead? So I manage to get the PoC running with this code:- # in pyramid main() entry point def main(global_config: t.Dict[str, str], **settings: str) -> Router: """Return a Pyramid WSGI application.""" # Expand environment variables in .ini files settings = expandvars_dict(settings) settings["ini_path"] = global_config["__file__"] # Configure Pyramid config = Configurator(settings=settings) configure(config) # Up, Up and Away! from myapp.wsgi import application as django_app pyramid_app = config.make_wsgi_app() def wsgi_app(environ, start_response): request_url = environ["PATH_INFO"] if request_url.startswith("/api"): return pyramid_app(environ, start_response) return django_app(environ, start_response) return wsgi_app Basically the idea is that, for any request path that starts with /api, we pass it to pyramid, while everything else will be handled by django. This seems to be working well for a simple pages I'm testing, with all the i10n/l10n stuff also working. I'm wondering if there's any gotchas that I should be aware of, if I'm going this route. -
How to serialize file without host?
I am working on my Django (DRF) app. I have a user avatar class CustomUser(AbstractBaseUser, PermissionsMixin): avatar = models.ImageField(upload_to='avatars/', blank=True) ... I want to serialize avatar field: class CustomUserSerializer(serializers.ModelSerializer): avatar = serializers.FileField(use_url=False, required=False) class Meta: model = CustomUser fields = [ 'avatar', ... ] Current result is "avatar": "avatars/ZZZ.png" How can I get "avatar": "media/avatars/ZZZ.png" ??? (what is the proper way) Saved file location is http://localhost:6060/media/avatars/<file_name>.png -
How to write changes to auditlog from action in admin panel?
I have the model Players and rewritten auditlog. And when I'm trying to change some field from admin panel for example status - changes writing to the auditlog. But when I'm do changes using action (action change the value on the selected objects on the field status) - nothing is happened, no changes writing to the auditlog. What is the reason? And how to resolve it? -
Django Static doesn't load but is accessible. NGINX and Docker
I have connected my Django (DRF) to Gunicorn and Nginx and put it all in docker. When I load mysite.com/admin/ it looks bad, just plain text. So it seems like it does not load any static file. However, in Browser Console there are zero errors. Moreover, I see that all the static files have been successfully loaded from server (all the /static/ requests are HTTP 200) and I can open them right in my browser by putting url: mysite.com/static/admin/css/base.css. And this file will successfully open. But admin site does not want to apply it. On localhost with Debug=True everything is working fine too. On main web site all the /media/ is working good too, so the problem is only within /static/. nginx.conf events {} http { server { listen 80; server_name mysite.com; server_tokens off; location / { return 301 https://$host$request_uri; } } server { listen 80; server_name api.mysite.com; server_tokens off; location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name mysite.com; server_tokens off; ssl_certificate /etc/nginx/certs/mysite.com-chain.pem; ssl_certificate_key /etc/nginx/certs/mysite.com-key.pem; location / { proxy_pass http://10.0.2.237:3004; # React Frontend } } server { listen 443 ssl; server_name api.mysite.com; server_tokens off; ssl_certificate /etc/nginx/certs/api.mysite.com-chain.pem; ssl_certificate_key /etc/nginx/certs/api.mysite.com-key.pem; location /media/ { autoindex on; alias … -
Django form is not showing up on template
I am trying to show two forms (UserRegisterForm and TeacherRegisterForm) in one template. But, only the UserRegisterForm is showing up in the rendered HTML. teacher-register.html <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} {% crispy user_form %} {% crispy teacher_form %} <div class="form-group mt-3"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> urls.py urlpatterns = [ path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'), path('register/', register, name='register'), path('TeacherRegister/', register_teacher, name='teacher-register'), path('logout/', sign_out, name='logout'), path('profile/', sign_out, name='logout'), ] views.py def register_teacher(request): if request.user.is_authenticated: return redirect('dashboard') if request.method == 'POST': user_form = UserRegisterForm(request.POST) teacher_form = TeacherRegisterForm(request.POST, request.FILES) if user_form.is_valid() and teacher_form.is_valid(): user = user_form.save(commit=False) user.is_student = False user.is_teacher = True user.save() profile = teacher_form.save(commit=False) profile.user = user profile.save() messages.success( request, f'Your account has been created!') return redirect('login') else: user_form = UserRegisterForm() teacher_form = TeacherRegisterForm() context = { 'user_form': user_form, 'teacher_form': teacher_form, } return render(request, 'accounts/teacher-register.html', context) forms.py class TeacherRegisterForm(forms.ModelForm): image = forms.ImageField( label='Profile Picture', help_text='Upload a recent clear image.', required=False, ) birth_date = forms.DateField( label='Birth Date', widget=forms.widgets.DateInput(attrs={'type': 'date'}), ) facebook = forms.URLField( label='Facebook Profile URL' ) class Meta: model = Teacher fields = [ 'image', 'birth_date', 'facebook', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Div( Div('image', css_class="col-sm-6"), Div('birth_date', css_class="col-sm-6"), css_class='row', … -
How to show possible OrderingFilter fields in graphql documentation explorer in graphene-django
I have a model class ProductOnRetailerOfOrganization(models.Model): name = models.CharField(max_length=200, blank=True, null=True) product_id = models.CharField(max_length=100, blank=true, null=true) and a graphql node like class ProductNode(DjangoObjectType): class Meta: model = Product interfaces = (graphene.relay.Node,) connection_class = connections.ExtendedConnection filterset_class = ProductFilter And filterset class ProductFilter(FilterSet): class Meta: model = Product fields = { "name": ["exact", "contains"], "product_id": ["exact", "contains"], } order_by = OrderingFilter( fields=( ( "name", "product_id", ) ) ) and query, schema import graphene from django.contrib.auth.mixins import LoginRequiredMixin from django.http import JsonResponse from graphene_django.views import GraphQLView class Query(graphene.ObjectType): products = DjangoFilterConnectionField(nodes.ProductNode) schema = graphene.Schema(query=Query) class PrivateGraphQLView(LoginRequiredMixin, GraphQLView): raise_exception = True def introspection_schema_view(request): data = {"data": schema.introspect()} return JsonResponse(data) when I enter into localhost:8000/graphql Documentation Explorer, I can't identify which fields can be passed with orderBy argument. Its just shows orderBy: String! unlike other filter fields which is listed as exact lookup arguments. eg. (nameIcontains: String !, name: String!) Is there a way to show the OrderingFilter fields just like showing filter and other arguments in documentation explorer ? -
local variable 'name' referenced before assignment in Django
My views.py def index(request): if request.method=="POST": name=request.POST.get('name') email=request.POST.get('email') phone=request.POST.get('phone') message=request.POST.get('message') contact=Contact(name=name, email=email, phone=phone, message=message) contact.save() return render(request, 'home/index.html') Error C:\Django venv\CodingSchool\home\views.py, line 12, in index contact=Contact(name=name, email=email, phone=phone, message=message) -
How can i solve missing 1 required positional argument: 'request' in django
here is my views @login_required(login_url='login') def updateUser(request): form = updateUser() if request.method == 'POST': form = updateUser(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form':form} return render(request,'base/update_user.html',context) and my forms.py class updateUser(ModelForm): class Meta: model=Responsible fields = '__all__' what im trying to do is update an name and department in a company class Responsible(models.Model): name = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) dept = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True) -
Django Rest Framework is requiring both a session and token to make authenticated request
I'm in the process of creating a REST API using Django Rest Framework for a web application made by a third party. I'm trying to configure the REST API so that it is available using SessionAuthentication or TokenAuthentication and that the Swagger documentation (generated using drf-yasg) is available unauthenticated. The problem I am running into at the moment is that when I send a request to my API it is requiring both a sessionid and token to be sent in the request. If I remove the token I get: {"detail":"Invalid token."} and if I remove the session, it redirects me to the login page of the main application. If I send it with both in the request then I get a valid response from my REST API. My settings.py file looks like the following: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', #'rest_framework.authentication.SessionAuthentication', ], } As can be seen above, even with SessionAuthentication disabled for the REST API, it still requires the session to be set. Does anyone know why it is doing this? My initial thoughts are that it's using django.contrib.auth and applying that to all views but i'm not sure, i'm a bit of a Django … -
react conversion using django redirect
I have two react projects (localhost:3000, localhost:3001) and a Django server (localhost:8000) running in my local environment. I want to use the API that calls port 3001 using the function below in react 3000 port as django's redirect function. localhost:3000 button function redirect calling localhost:3001 in ReactAPP const getProject = () =>{ console.log('go localhost:3001') axios.post('http://localhost:8000/user/Dashboard') .then(res => { setauth(true) }) } View from "http://localhost:8000/user/Dashboard" in django def getDashBoard(request): return redirect('http://localhost:3001') settings.py ALLOWED_HOSTS = ['localhost','127.0.0.1'] CORS_ALLOWED_ORIGINS = ["http://localhost:8000" "http://localhost:3001", "http://localhost:3000", "http://127.0.0.1:3000", "http://'127.30.1.47':3000"] CORS_ORIGIN_WHITELIST = ['localhost'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' The withCredentials option is essential because I want to proceed with the project using Cookie's Token in the future. But The following error appears. Access to XMLHttpRequest at 'http://localhost:3001/' (redirected from 'http://localhost:8000/user/Dashboard') from origin 'http://localhost:8000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include' . The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. I want to change 'Access-Control-Allow-Origin' when calling 3001 in ReactAPP, but I can't think of a way. Please help if I am trying the wrong … -
How to use captcha for user login in django rest framework?
I want to pass the captcha when the user wants to enter his account If he does not enter the captcha correctly, display the appropriate message Captcha must be a number and 4 digits views.py class LoginApiView(generics.GenericAPIView): """login user""" serializer_class = LoginSerializer renderer_classes = [CustomizeJSONRenderer] def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class LoginSerializer(serializers.ModelSerializer): username = serializers.CharField(max_length=255) password = serializers.CharField(max_length=68, min_length=8, write_only=True) email = serializers.EmailField(max_length=255, min_length=3, read_only=True) tokens = serializers.CharField(max_length=255, read_only=True) class Meta: model=User fields = ['username', 'password', 'email', 'tokens'] def validate(self, attrs): username = attrs.get('username', '') password = attrs['password'] user = authenticate(username=username, password=password) if not user: raise exceptions.AuthenticationFailed('Invalid credentials, try again') if not user.is_active: raise exceptions.AuthenticationFailed('Account disabled, contact admin') return { 'username':user.username, 'email': user.email, 'tokens':user.tokens } -
Group by users in django ORM
I've a StudentAnswer model which stores the answer id given by the student(User) in a quiz. If the answer is correct then 1 marks else 0. I'm also ranking the users based on their marks in a particular quiz. The model looks like this: class StudentAnswer(models.Model): user = models.ForeignKey(User, related_name='user_question_answer', on_delete=models.SET_NULL,null=True, blank=True) answer = models.ForeignKey(QuizQuestionAnswer, related_name='user_answer', on_delete=models.CASCADE) quiz = models.ForeingKey(Quiz, on_delete=models.CASCADE) marks = models.IntegerField() This is the query I'm using to rank my users: StudentAnswer.objects.filter( quiz__start_date__month=date.today().month).annotate( rank=Window(expression=DenseRank(), order_by=[F('marks').desc(),]) ) A user will have multiple entries in table(number of questions he attempted in a month). I want to group by each user, add their marks and then rank them for that particular month and send the response. How can I do this? Thanks in advance. -
django-two-factor-auth's user.is_verified() returns False on subdomains
I am facing this strange issue, I have posted it here already but didn't get any response yet. I am using django-two-factor-auth in my Django application, Everything works fine in the local environment but getting an issue on the production server. My application is tenant-based and I am using subdomains for each tenant, for example on the production server, My application => xyz.com User with tenant name "a" after login gets redirected to => a.xyz.com User with tenant name "b" after login gets redirected to => b.xyz.com When redirected to a subdomain I am getting this issue that user.is_verified() always returns False even if 2fa is enabled for the user. I am using user.is_valrified() for showing enable/disable 2fa buttons. If I remove the subdomain redirection, it works fine and returns True if 2fa is enabled for a user. My Environments Browser and version: Google Chrome Version 103.0.5060.114 Python version: 3.8.10 Django version: 2.2.0 django-otp version: 0.9.4 django-two-factor-auth version: 1.12.1 Note: I have debugged this enough that I know this is happening due to sub-domains -
Seeing 'SignupForm' object has no attribute 'instance' on Django Form
I am on Django 4.0.x and running over and over into the same issue when validating a form. Always seeing: 'SignupForm' object has no attribute 'instance' Here is my view: def signup(request): if request.method == "POST": signup_form = SignupForm(request.POST) if signup_form.is_valid(): email = signup_form.cleaned_data['email'] else: signup_form = SignupForm() return render(request, 'signup.html', {'signup_form': signup_form}) and the according forms.py: class SignupForm(forms.Form): email = forms.EmailField(label=_("E-Mail Address"), validators=[EmailValidator()]) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput()) password_confirm = forms.CharField(label=_("Confirm Password"), widget=forms.PasswordInput()) def clean_email(self): data = self.cleaned_data['email'] if forms.ValidationError: self.add_error('email', forms.ValidationError) return data def clean_password(self): data = self.cleaned_data['password'] try: validate_password(data, self.instance) except forms.ValidationError as error: self.add_error('password', error) return data cleaned_data also delivers nothing here. -
I am new to Django and working on a project. In my project I need to call a same API from multiple places with different "permission_classes"
I am new to Django and I am working on project for a Blood bank. in my project I have created an API and provided a custom permission class. However I need to call the same API in my project but at different location (in different app). So do I need to create another API for that or I can call the same with a different permission class. So the API I have created in an app named "Form_Hospital > views.py" and this is the code:- class RequisitionFormAV(APIView): ''' to post a "Requisition Form" and get list. ''' permission_classes = [IsAuthenticatedActiveHospitalStaff] # permission_classes = [IsAdminUser] def get(self, request): search = request.query_params.get('search') page = request.query_params.get('page') qty = request.query_params.get('qty') snippet= RequisitionForm.objects.all() if search: snippet = snippet.filter( Q(requisition_no__icontains=search) | Q(requested_name__icontains=search) | Q(organization_name__icontains=search) | Q(contact_no__exact=search) ) output = RequisitionFormSerializer(snippet, many=True).data if page and qty: output = paginations.page(output, qty, page) return Response({'data': output}, status=status.HTTP_200_OK) def post(self, request): data = request.data # getting the organization name of logged in user data['organization_name'] = request.user.organization.value # getting the last DonorRegistrationForm object. try: snippet = RequisitionForm.objects.all().last().requisition_no _str = snippet[5:] _num = int(_str) + 1 _len = len(str(_num)) if _len == 1: _str = "000" + str(_num) if _len == … -
How to **dynamically display** different pages using one html page
I know I have asked this question before but I am really struggling on this issue. I am currently making a shopping website using django and I want to dynamically display the data. The 'shoppingpage' lists the categories and subcategories of clothes. If I click on 9-6 wear, only the images of 9-6wear clothes should come. For example, as shown in the image above when I click on 9-6wear, I get images of 9-6 wear,but the issue is that when I click on other categories(like Fusion wear bridal wear desi swag), I get the same clothes as I got in 9-6 wear. How do I make sure that I get clothes belonging to 'bridal wear' when I click bridal wear and so on using django and html and displaying the data dynamically? below are the functions ,urls ,html pages url path('category/',views.category,name="category") function def category(request): prod = Products.objects.filter(isactive=True) return render(request,'polls/category.html',{'products':prod}) category.html {% for product in products %} <li class="product-item wow fadeInUp product-item rows-space-30 col-bg-4 col-xl-4 col-lg-6 col-md-6 col-sm-6 col-ts-6 style-01 post-24 product type-product status-publish has-post-thumbnail product_cat-chair product_cat-table product_cat-new-arrivals product_tag-light product_tag-hat product_tag-sock first instock featured shipping-taxable purchasable product-type-variable has-default-attributes" data-wow-duration="1s" data-wow-delay="0ms" data-wow="fadeInUp"> <div class="product-inner tooltip-left"> <div class="product-thumb"> <a href="{% url 'polls:productdetails' product.id … -
AttributeError at /accounts/register/ Manager isn't available; 'auth.User' has been swapped for 'stackapp.CustomUser'
from django.db.models import Count "imorting the packges" from django.shortcuts import render, HttpResponse from django.core.paginator import Paginator from django.contrib import messages from .models import * from .forms import AnswerForm, QuestionForm, ProfileForm from django.contrib.auth.forms import UserCreationForm from .forms import ProfileForm from django.conf import settings User = settings.AUTH_USER_MODEL # Home Page def home(request): "creating a function for paginator" if 'q' in request.GET: q = request.GET['q'] quests = Question.objects.filter(title__icontains=q).order_by('-id') else: quests = Question.objects.all().order_by('-id') paginator = Paginator(quests, 10) page_num = request.GET.get('page', 1) quests = paginator.page(page_num) return render(request, 'home.html', {'quests': quests}) # Detail def detail(request, id): "creating a function for question details" quest = Question.objects.get(pk=id) tags = quest.tags.split(',') answers = Answer.objects.filter(question=quest).order_by('-id') # comments = Comment.objects.filter(answer=answer).order_by('-id') answerform = AnswerForm if request.method == 'POST': answerData = AnswerForm(request.POST) if answerData.is_valid(): answer = answerData.save(commit=False) answer.question = quest answer.user = request.user answer.save() messages.success(request, 'Answer has been submitted successfully') return render(request, 'detail.html', { 'quest': quest, 'tags': tags, 'answers': answers, 'answerform': answerform, }) # User Register def register(request): form=UserCreationForm if request.method=='POST': regForm=UserCreationForm(request.POST) if regForm.is_valid(): regForm.save() messages.success(request,'User has been registered!!') return render(request,'registration/register.html',{'form':form}) views.py "importing package" from dataclasses import field from django.forms import ModelForm from .models import Answer, CustomUser, Question class AnswerForm(ModelForm): "creating answerform" class Meta: model = Answer "fetch all field" fields = ('detail',) … -
Graphene-file-upload handling the multipart/form-data
I am trying to upload an image from my react/nextJS front end to my django backend using graphQL and graphene-file-upload. This is the frontend - the important functions here are handleSelectedLogo and submitVendor const CreateVendorForm = () => { // redux state const user = useSelector(selectUser); const token = useSelector(selectToken); const [step, setStep] = useState(1) const inputRef = useRef(null) const [companyName, setCompanyName] = useState('') const [companyAddress, setCompanyAddress] = useState<any>({label: ''}) const [companyLatLng, setCompanyLatLng] = useState<any>({lat: 40.014, lng: -105.270}) const [companyPhone, setCompanyPhone] = useState('') const [companyEmail, setCompanyEmail] = useState('') const [companyWebsite, setCompanyWebsite] = useState('') const [companyLogo, setCompanyLogo] = useState() const [companyDescription, setCompanyDescription] = useState('') const [published, setPublished] = useState(false) const [type, setType] = useState(['Customer Care', 'Information Technology','Market Research', 'Marketing and Communications', 'Renewable Energy', 'Technical Engineering', 'Other']) const [selectedTypes , setSelectedTypes] = useState<string[]>([]) const [showtext, setShowText] = useState(false) const [file , setFile] = useState() useEffect(() => { console.log(token,user) }, []) const toggleType = (type: string) => { if (selectedTypes.includes(type)){ setSelectedTypes(selectedTypes.filter(t => t !== type)) } else { setSelectedTypes([...selectedTypes, type]) } console.log(selectedTypes) } const changeStep = (nextStep: number) => { if(nextStep > 0) { if(step < 4) { setStep(step + 1) } } if (nextStep < 0) { if (step > 1) { … -
SplitDateTimeField default value is not localized
So I have this field in a form: date_time = forms.SplitDateTimeField(required=False, localize=True, label=_("Change the date and time"), ) and initially, the page looks like this: even though I have localize set to True. After I select another date from the datepicker, the date will be localized properly. I'd like the date to be localized from the start. How can I do that? Thanks. -
How to create a user group in django?
I want to create a user group through API, when I created a view to create a group, it shows error like this. Creating a ModelSerializer without either the 'fields' attribute or the 'exclude' attribute has been deprecated since 3.3.0, and is now disallowed. Add an explicit fields = 'all' to the GroupSerializer serializer MySerializer from django.contrib.auth.models import Group class GroupSerializer(ModelSerializer): class Meta: model = Group field = '__all__' MyView class GroupView(APIView): def post(self, request, tenant, format=None): tenant = get_tenant(tenant) serializer = GroupSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=status.HTTP_201_CREATED, safe=False) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST, safe=False) -
How to change template and then continue writing function?
So... I have a function to send email to user and then user has to input the body of that email. My views.py: def signup(request): if request.method == "POST": context = {'has_error': False, 'data': request.POST} email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') code = request.POST.get('code') letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9",] characters = letters + numbers length = 5 token = "".join(random.sample(characters, length)) body = render_to_string('authentication/email/email_body.html', { 'username': username, 'token': token, }) send_mail( "Email Confirmation", # f"Hello {username}! Your code to confirm your email is : {token}", body, 'tadejtilinger@gmail.com', [email] ) return render(request, 'authentication/email/email_confirmation.html', context={'token': token}) return render(request, 'authentication/signup.html') So here I tried to change template from signup.html to email_confirmation.html. I succeeded so now I want to tell python what it should do with email_confirmation.html but I don't know how to do it. If I try writing code under return render(request, 'authentication/email/email_confirmation.html', context={'token': token}) it won't work. Where should I actually write my code then? Thanks for help I hope I wrote question understanding!:) -
How to write test case for a Django model which has all the fields as foreignkey in DRF?
I have a model which has all the fields as a foreign key to other models. How can we create test case in Django rest framework in that case?? I have a model as follows: class Example(models.Model): package = models.ForeignKey( Destination, related_name="packages", on_delete=models.CASCADE ) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name="user_packages", ) tour = models.ForeignKey( Tours, on_delete=models.CASCADE, null=True, related_name="tour_packages", ) In a model, when there is just one field in a Django model, it can be done in the following way: class NewsLetter(models.Model): NewsLetterID = models.AutoField(primary_key=True) Email = models.CharField(max_length=255) Connected = models.BooleanField(default=False) UserID = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table = 'NewsLetter' @classmethod def setUpTestData(cls): #Set up non-modified objects used by all test methods user = User.objects.create(<fill params here>) NewsLetter.objects.create(NewsLetterID=1, Email='test@test.com', Connected=False,UserID=user) So even if I have created all the objects for all the foreign-key fields just like this example, the thing is, for the related field models, they themselves have foreign key fields. How can we approach this?? For example in my Example model, the Destination model is itself related to other foreign key fields. So how to create unit test for create api for this Example model??