Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Api Root- Detail:Not Found (Django)
I am trying to authenticate user,i can see every detail when i open the api root but i encounter an error called "Detail:Not found" and can't authenticate. Can someone help? class LoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) username = serializers.CharField(max_length=255, read_only=True) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self, data): username = data.get('username', None) password = data.get('password', None) if username is None: raise serializers.ValidationError( 'A username is required to log in.' ) if password is None: raise serializers.ValidationError( 'A password is required to log in.' ) user = authenticate(username=username, password=password) if user is None: raise serializers.ValidationError( 'Username and password was not found.' ) if not user.is_active: raise serializers.ValidationError( 'This user has been deactivated.' ) return { 'username': user.username, 'token': user.token } class LoginAPIView(APIView): serializer_class = LoginSerializer renderer_classes = (UserJSONRenderer) def post(self, request): user = request.data.get('user', {}) serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) urlpatterns = [ url(r'users/login/', LoginAPIView.as_view()), ] I have tried to change things but it didn't work out as i wanted. -
Is there a way override DATA_UPLOAD_MAX_MEMORY_SIZE on one model field only
Is there a way to override the Django DATA_UPLOAD_MAX_MEMORY_SIZE default (2.5mb) on one model field only? I would like to keep the that max value the same everywhere except for one particular field, where it needs to allow for uploading of a much larger file size. I have implemented this solution which works well but I would rather not have to use this custom class for every file upload field in application. I would like to keep DATA_UPLOAD_MAX_MEMORY_SIZE at 2.5mb if possible. -
CMS login redirect to LMS dashboard after add SSL in Open edX
I am trying to add SSL in Open edX (Ironwood). As you know, In the Ironwood version, We can login CMS by using LMS login. Suppose that, LMS URL - https://lms.mydomain.com CMS URL - https://studio.mydomain.com When I click on the CMS login button it redirects to LMS (https://lms.mydomain.com/login?next=https%3A%2F%2Fstudio.mydomain.com%2F) URL. After login, it is redirecting to https://lms.mydomain.com/dashboard. Rather it should have redirected to this URL https://studio.mydomain.com/home It is working properly without using SSL and Domain. -
I got the message 'you have registered' but when I check in database, data is not save in database. When I reload the page the data is gone
Fullcalendar cannot update and save data. I got the message 'you have registered' but when I check in database, data is not save in database. When I reload the (index.html)page the data is gone. When I reload carenda/add_event/, data can be saved in database. In order to get the calendar, I know I need to write something but I don't know what should I write in path:'***' in index.html. I have searched on the internet for few days and tried to manipulate few things but I still cannot get it done. I'm still very new to Django, Javascript, JSON and Sqlite. Please help me. index.html <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'carenda/css/fullcalendar.min.css' %}"/> <link rel="stylesheet" href="{% static 'carenda/css/style.css' %}"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="{% static 'carenda/js/moment.min.js' %}"></script> <script type="text/javascript" src="{% static 'carenda/js/fullcalendar.min.js' %}"></script> <script type="text/javascript" src="{% static 'carenda/lang/ja.js' %}"></script> <script> // ページ読み込み時の処理 $(document).ready(function () { // カレンダーの設定 $('#calendar').fullCalendar({ height: 550, lang: "ja", header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay' }, timeFormat: 'HH:mm', selectable: true, selectHelper: true, navLinks: true, eventSources: [{ path: '***', dataType: 'json', async: false, type : 'GET', error: function() { $('#script-warning').show(); } }], select: function(start, end, resource) { var title = prompt("title:"); var … -
Django dropdown form with multiple/dynamic models
So i got multiple datatables which i transfered to django models. Now i want to build a form(do i need a form for this?) which allows the user to select the desired modelname out of a dropdown menu. Accordingly to the chosen model, the other form fields will adapt accordingly to the model's different attribute fields. Can someone push me in the right direction on how to do this? Do i need forms? Do i load the informations of all the models in the form and change it with javascript? Do i render the page again each time something's picked? I just started with django and webdev so i don't know the best practice -
Django one to many between legacy tables with no PK to FK relation
I am using legacy DB tables that I have no control over the tables design. Table A has an auto_gen ID field as follows: TableA (One Side) id (numeric auto gen, primary key) fld1 (string, unique but not a primary key.) fld2 (String) fld3 (date) TableB (Many side) id (numeric auto gen, primary key) fld1 (string, not unique, but it is the target many side) fld4 (String) fld5 (date) I am trying to use Djano models to establish a one to many relation between Tables A and B using fld1. I have done same in Java, but so far, it seems that Django won't allow it. Django seems to expect that one side must be a PK? I do realize that Django has many to one (instead of one to many) and followed the documentations ... but it is not working. Please advise if there is a way to do this in Django models framework. -
Modifying Sign Up tab created using django framework
I have made a sign up tab that registers new users and log in page that allows the registered users to continue with the site. I want if any registered user (having a registered email) tries to sign up again , an error message should pop up saying 'You are already having an account. Please Log in'. I stored the data(s) of registered user(s) in a table created in models.py named SignedUpUsers. Please help me achieve my task. models.py # Create your models here. class SignedUpUsers(models.Model): email = models.EmailField(max_length=122) name = models.CharField(max_length=122) username = models.CharField(max_length=122) password = models.CharField(max_length=122) date = models.DateField() def __str__(self): return self.name views.py from Home.models import SignedUpUsers from django.contrib import messages from datetime import datetime def login(request): return render(request, 'login.html') def signup(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') cont = SignedUpUsers(name=name,email=email,username=username,password=password,date=datetime.today()) cont.save() messages.success(request,"\t\tYour account has successfully been created . Kindly Log In\t\t") return render(request, 'signup.html') signup.html <!--Form--> <form method="post" action="/signup" style=" position: absolute; top: 260px; left: 500px; font-size: larger; "> {%csrf_token%} <!--Email--> <div class="form-group" > <label for="email">Email address</label> <input type="email" size="25" class="form-control" id="email" name="email" placeholder="name@example.com" style="block-size: 25px; position: absolute; left: 120px;"> </div> <!--Name--> <div class="form-group" > <label … -
How to specify filepath for celery task logs?
I have created some REST APIs using Django and I am using Celery to run some asynchronous jobs. The API is defined in api.py and the asynchronous job functions are in actions.py Here is what my api.py looks like: from myproject import actions def sample_api(request): actions.sample_job.delay() return HttpResponse('success') Here is what my actions.py looks like: from celery.utils.log import get_task_logger from celery.decorators import task logger = get_task_logger(__name__) @task(name="sample_job") def sample_job(): logger.info("start operation") <some operations> logger.info("stop operation") Now the problem is that I don't know where the logs are getting written. I've tried searching in the project directories and I dont see it anywhere. I want to provide a path to the log file where these logs should be written. How do I provide a path to the logfile in celery? (I know there are multiple questions in StackOverflow regarding this. But none really mention how to specify a filepath for the logfile) -
How to get cookie after login on a same domain login system?
I am creating a MiddleWare to authenticate the user (using a 3rd party login system of same domain) before accessing any view. In process_view method I am checking request.cookies to see the cookies and check whether cookie has user_id which will be set after a user login on the 3rd part login system having same domain if yes then I allow it to access the views otherwise I redirect It to the login page. Now the issue is that my Django app redirects to the login page and when I log in the login system, I see developer tools and I notice cookie is being set successfully but no cookie is returned in request. I searched the solution to this problem I got this solution on stack overflow - Python Requests get cookies values after authentication but sadly this only return user_data is authenticated in cookie and that is set to flash even after login into the system successfully.Here is a rough code of my Middleware- import json from django.http import HttpResponseRedirect import requests class UserAuthMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_fund, view_args, view_kwargs): r = requests.get("https://example.com/login/") print(r.cookies) … -
Issue with admin static files in Django 3 (Ubuntu, Nginx, Gunicorn, SSL)
I using Django 3.* for my project and everything works fine since i've installed SSL from Let's Encrypt by Certbot and sinse then i have an iisue with serving static files in my admin. My Nginx config: server { server_name casekam.ru www.casekam.ru; client_max_body_size 100M; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/gleb/casekam/django_shop/django_shop/static/; } location /media/ { alias /home/gleb/casekam/django_shop/django_shop/media/; } location / { include proxy_params; proxy_pass http://unix:/run/casekam.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/casekam.ru/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/casekam.ru/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.casekam.ru) { # return 301 https://$host$request_uri; return 301 https://casekam.ru$request_uri; } # managed by Certbot if ($host = casekam.ru) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name casekam.ru www.casekam.ru; return 404; # managed by Certbot } Can't figureout where am i wrong. Will be appriciate for any hints and tips. -
Django Date Filter with REST with Prefetch / How to make a date range?
Now, in my CoincostFilterSet class, the start date for the result filter is set. And how to set the end date in my code? now i have this url http://example.com/api/v1/CoinCost/?symbol=MNST&timestamp=2020-04-20T09:17:34 but need http://example.com/api/v1/CoinCost/?symbol=MNST&timestamp=2020-04-20T09:17:34&timestamp=2020-04-23T05:17:34 To get the results from April 20 to 23. filters.py class DateTimeGteFilter(filters.IsoDateTimeFilter): def filter(self, qs, value): if value != None: return qs.prefetch_related(Prefetch('coincosts_set', to_attr='filtered_coincosts', queryset=CoinCosts.objects.filter(timestamp__gte=value) ) ) else: return qs views.py class CoinCostFilterSet(filters.FilterSet): timestamp = DateTimeGteFilter() class Meta: model = Coins fields = { 'symbol': ['exact'], } serializers.py class CoinSerializer(serializers.ModelSerializer): class Meta: fields = ('symbol', 'crr', 'costs') model = Coins costs = CoinCostsSerializer(source='filtered_coincosts', many=True) Help.Thanks! -
How to add multiple entry to multiple model which have one to one relationship in django?
So I have these two models class Question(models.Model): question_image = models.ImageField(upload_to="Questions/images", default="") subject = models.CharField(max_length=100) topic = models.CharField(max_length=100) type = models.CharField(max_length=100) exam_type = models.CharField(max_length=100) date_asked = models.DateField(default="") class Option(models.Model): question_id = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=100) text.null = True text.blank = True option_image = models.ImageField(upload_to="Options/images", default="") option_image.null =True option_image.blank =True is_correct = models.BooleanField() You see the question has one two many relationships with the options Now I want to add question and corresponding to that question multiple options in the option table. So if a question with id=1 will have multiple option in option table with question_id = 1. So I have made these two forms from django import forms from practice.models import Question from practice.models import Option from django.forms import ModelForm class QuestionForm(ModelForm): class Meta: model = Question fields = ['question_image', 'subject', 'topic', 'type' , 'exam_type' , 'date_asked'] class OptionForm(ModelForm): class Meta: model = Option fields = ['text' , 'option_image' , 'is_correct'] Now in the HTML template in frontend I want to be able to add as many options I want so I have written this HTML code. The javascript code required to add more options is yet to be done but you get the point I am going … -
Dockerize Django and Celery tasks
I am trying to integrate Celery with an existing Django app using Docker. I have been trying to follow this tutorial (1). However, I keep bumping with the same error no matter what I try. I am using Django==2.2, Celery==4.4.1 Docker==19.03.8 Docker-compose==1.25.4 on Windows 10. My project is structured in the following way (I skip some files for simplicity): ├── .gitignore ├── docker-compose.yml ├── Dockerfile ├── src ├── core │ ├── __init__.py │ ├── urls.py │ └── wsgi.py │ ├── celery.py │ ├── tasks.py │ ├── settings │ │ ├── base.py │ │ └── development.py ├── requirements.txt ├── .env └── manage.py My docker-compose.yml: version: '3' services: python: build: context: . dockerfile: Dockerfile command: python /src/manage.py runserver 0.0.0.0:8000 volumes: - ./src:/src depends_on: - db - redis ports: - 8000:8000 links: - db - redis db: image: postgres:11 environment: - POSTGRES_PASSWORD=postgres ports: - "5432:5432" redis: image: redis ports: - "6379:6379" celery-beat: build: context: . dockerfile: Dockerfile command: celery worker -A core -l debug env_file: - "src/.env" environment: - SECRET_KEY=kobl@t=yw9d*0y%jt2gjnq78=u!z_rrxb&w8e47l!(jz@m79zy depends_on: - redis celery: build: context: . dockerfile: Dockerfile command: celery worker -A core-l debug env_file: - "src/.env" depends_on: - redis Running 'docker-compose logs celery' after building gives the following: celery_1 | Traceback … -
Usage of Django validators in nullable field
I have a model with a field: last_watched_episode = models.PositiveSmallIntegerField( null=True, ) And in this field I want to store either Null or positive integers gte 1 to max one that PositiveSmallIntegerField is able to hold (from 1 to 32767 ). I want to enforce validation on a model level ,so that I included full_clean() to save(): def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.full_clean() super(SeasonModel, self).save( force_insert=False, force_update=False, using=None, update_fields=None ) Problem is when I apply a MinValueValidator or custom validator to this field I get following error message: django.core.exceptions.ValidationError: {'last_watched_episode': ['This field cannot be blank.']} each and every time when saved value is omitted, that is it is NONE. This is quite logical as validator needs to have some input value to validate it Validator I use: def skip_if_none_none_zero_positive_validator(value: int) -> None: if value is None: return None elif value < 1: raise ValidationError( f'{value} must be greater or equal 1' ) Question is how it to overcome this issue? How to save None as a legit value and simultaniously validate that it would be greate or equal 1 in case values is not None? And enforce model level validation of course. -
django URL Trouble with passing parameter twice
I have a template where I pass all projects to and I loop through them and create a table that shows how many tasks are associated with each project. Then I have a button that says "Create new task for . However, I now can't get to my home page because of the error: Reverse for 'createTask' with no arguments not found. 1 pattern(s) tried: ['(?P<projID>[^/]+)/newtask/$'] But I can directly go to /projects and view the projects template. But when clicking on the button I get the same error except with the actual projID in the url. Any idea what I'm doing wrong? Models: name = models.CharField(max_length=30, unique=True, primary_key=True) #task_id = models.CharField(max_length=30, unique=True, primary_key=True) description = models.CharField(max_length=255) date_created = models.DateTimeField(auto_now_add=True) #createdBy = models.ForeignKey(User, on_delete=models.CASCADE, null=True) #project = models.ForeignKey('Project', on_delete=models.CASCADE, related_name='tasks') # do you want to create a task without a project!?!?!?!? project = models.ForeignKey('Project', on_delete=models.CASCADE, null=True) owner = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='taskowner', null=False) user = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='profile', null=True) team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='teams', null=True) #private = models.ForeignKey('Project', on_delete=models.CASCADE, related_name='privatetask', default=False) # open or closed OPEN = 'open' CLOSED = 'closed' INPROCESS = 'inprocess' STATUS = [ (OPEN, 'Open Task'), (CLOSED, 'Closed Task'), (INPROCESS, 'In Process'), ] status = models.CharField(max_length=9, choices=STATUS, … -
AJAX GET request not sending data to Django
I am trying to send data in localStorage via an AJAX GET request to Django, but the Django server never receives it. I am confident that I have data in localStorage("preselection") as console.log shows it. Here is my JavaScript snippet which is inside index.html (am a beginner, so apologies if this is basic and I'm avoiding jQuery for now): var preselection = localStorage.getItem("preselection"); function previous_selection () { if (localStorage.getItem("preselection") != null) { console.log("PRESELECTION IS: ", preselection); const data = new FormData(); data.append("preselection", preselection); const request = new XMLHttpRequest(); request.open('GET', '/'); request.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); request.send(data); request.onload = () => { var url = '/prebasket'; window.location.href = url; }; return false; } } previous_selection(); Below is my view in views.py. I tried request.GET.dict(), request.GET.get(), request.GET.copy(), etc. and my data comes as JSON in case it matters, but Django just gets an empty {} or Null for q_preselection: @login_required def index(request): q_preselection = request.GET.dict() print(q_preselection) # comes back empty context = { #irrelevant } return render(request, "pizza/index.html", context) -
DJANGO 3.0.5 refer to a Field
I have a django project, but when I try to run make migrations, It is failing with an followingerror : $python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: <class 'authorization.admin.UserAdmin'>: (admin.E116) The value of 'list_filter[2]' refers to 'is_active', which does not refer to a Field. and my admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .models import User_u, user_type class UserAdmin(BaseUserAdmin): fieldsets = ( (None, {'fields': ('email', 'password', 'name', 'last_login')}), ('Permissions', {'fields': ( 'is_active', 'is_staff', 'is_admin', 'groups', 'user_permissions', )}), ) add_fieldsets = ( ( None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2') } ), ) list_display = ('email', 'name', 'is_staff', 'last_login') list_filter = ('is_staff', 'is_admin', 'is_active', 'groups') search_fields = ('email',) ordering = ('email',) filter_horizontal = ('groups', 'user_permissions',) admin.site.register(User_u, UserAdmin) admin.site.register(user_type) So I am referring to that field, but system is tellimg that there is not a refer, am I doing it wright? -
Django Python Selenium generates screenshot with wrong size
I need to get screenshots of url. The screnshots itself are working. But there is na error with sizes. When I set width and height of the window and get the screenshot. The screenshot is made with the wrong size. For example I set the size 1000x600. And it gives me 990x470. Here is the view.py: def shots(request): x = datetime.datetime.now() time = x.strftime("%Y-%m-%d-%H-%M-%S") if request.method == 'POST' and 'url' in request.POST: url = request.POST.get('url', '') headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'} width_get = request.POST.get('width', '') height_get = request.POST.get('height', '') if width_get is not None and width_get != '': width = width_get else: width = 1600 if height_get is not None and height_get != '': height = height_get else: height = 1000 if url is not None and url != '': url_parsed = urlparse(url) scheme = url_parsed.scheme netloc = url_parsed.netloc if netloc.startswith('www.'): netloc = netloc.replace('www.', '') image_path = "media/" + netloc + "-" + time + ".png" shot_path = "/media/" + netloc + "-" + time + ".png" path = "C:/WebDrivers/chromedriver.exe" driver = webdriver.Chrome(path) driver.set_window_size(width, height) driver.get(url) driver.save_screenshot(image_path) screenshot = image_path driver.quit() var_dict = { 'screenshot': screenshot, 'shot_path':shot_path, 'netloc':netloc, } return render(request, 'shots.html', var_dict) else: … -
Django: multiple models with one-to-many relation on admin page TabularInline
I have multiple models in an existing database that all have a many-to-one relation to another model. For example: class Collection(models.Model): start = models.DateTimeField() end = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'Program' class ItemA(models.Model): collection = models.ForeignKey( 'Collection', models.CASCADE, db_column='Collection_id') ... class Meta: managed = False db_table = 'ItemA' class ItemB(models.Model): collection = models.ForeignKey( 'Collection', models.CASCADE, db_column='Collection_id') ... class Meta: managed = False db_table = 'ItemB' What I want to do, is show these models in a single TabularInline on the admin page of the Collection model. I also want to be able to filter the models. Is this possible without inheritance in the database? (I don't want to add a general item table). In the documentation, I can only find how you can use TabularInline for a single model. So my question is basically: What would be the best approach to solve this? Is it maybe possible to define some kind of view model dat is not in the database, but that can be used to display all the items in a TabularInline? -
Reverse for 'post_edit' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/edit/$']
i am making blog site but issue is as follows: In my home page i have blogs which i have added but when i am clicking them they are showing 500 error which is stated as : NoReverseMatch at /post/1/. My code body is as follows & My app name is Blog: Models.py from django.db import models from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) Urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.BlogListView.as_view(), name='home'), path('post/<int:pk>/', views.BlogDetailView.as_view(), name='post_detail'), path('post/new/', views.BlogCreateView.as_view(), name='post_new'), path('post/<int:pk>/edit/', views.BlogUpdateView.as_view(), name='post_edit'), ] Views.py: from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView from . models import Post class BlogListView(ListView): model = Post template_name = 'home.html' class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' context_object_name = 'anything_you_want' class BlogCreateView(CreateView): model = Post template_name = 'post_new.html' fields = '__all__' class BlogUpdateView(UpdateView): model = Post fields = ['title', 'body'] template_name = 'post_edit.html' I am using Import Reverse to get back on the same page after adding the blog but it is showing same error too. -
like button in django: refresh pronblem
i was trying to create a like button for my django blog its working fine. the problem i'm facing is whenever i click the like button it refresh and give like. how can i stop it from refreshing page, its looks bad bcoz if i try to give like in user prolife or in post detail it redirect to home page. can anyone help me? models.py class Post(models.Model): title= models.CharField(max_length=100) img = models.ImageField(upload_to='pics') content = models.TextField() likes = models.ManyToManyField(User,blank=True, default=None, related_name='post_likes') date_posted = models.DateTimeField(default=timezone.now) author= models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title @property def num_likes(self): return self.liked.all().count() def get_absolute_url(self): return reverse('User-Posts-Details', kwargs={'pk': self.pk}) Like_Choice = ( ('Like','Like'), ('Unlike','Unlike'), ) class Like(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post,on_delete=models.CASCADE) value = models.CharField(choices=Like_Choice,default='Like',max_length=20) def __str__(self): return str(self.post) views.py def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.likes.all(): post_obj.likes.remove(user) else: post_obj.likes.add(user) like, created = Like.objects.get_or_create(user=user,post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return redirect('Love Travel-User-Posts') urls.py path('user-posts/like/',like_post,name='User-Post-Like'), posts.html <form action="{% url 'User-Post-Like' %}" method="POST" class="ui form"> {% csrf_token %} <input type="hidden" name="post_id" value="{{ post.id }}"> <strong class="Likes ml-3 mr-2">{{ post.likes.all.count }}</strong> {% if user not in post.likes.all %} … -
Pytest doesn't find pytest.ini
I have pytest.ini located in current directory and when invokin pytest /src/foo/bar for some strange reason pytest picks /src/foo as project root even I do have following pytest.ini: [pytest] DJANGO_SETTINGS_MODULE = myproj.settings python_files = tests.py tests_*.py *_tests.py django_find_project = false addopts = --rootdir=$PWD -p no:warnings --no-migrations --reuse-db --junit-xml=unittests.xml norecursedirs = .* static I'm running command within a docker but I assume it doesn't have any implications. -
Django Formtools Form Wizard is not showing data fetched from database
I'm taking first name and last name from user. In done() method, I'm updating the record in database. In get_form_initial() method, I prepopulate first name and last name from database. In this case, initialised form is empty. Notice that if I manually enter first name and last name in database (postgres), then form shows this data while initializing. Why is this happening ?? views.py def get_form_initial(self, step): initial = {} id = self.request.user.id user = User.objects.filter(id=id).values_list('first_name', 'last_name') print(user, end='\n') if step == '0' and user : initial.update({ 'first_name' : user[0][0], 'last_name' : user[0][1] }) return self.initial_dict.get(step, initial) def done(self, form_list, **kwargs): id = self.request.user.id data = [form.cleaned_data for form in form_list] first_name = data[0]['first_name'] last_name = data[0]['last_name'] #Save User details to DB if first_name != '' and last_name != '' : user = User.objects.filter(id=id) user.update(first_name=first_name, last_name=last_name) print('Added User Details') return redirect('morya:customer', id=user_id) -
How to use Django sessions to pass data from one form to another?
I have a view from which I want to pass a session variable into a form. The view looks like this: def admission(request): ... request.session['season_value'] = some_value The form looks like this: class DeterminingForm(forms.Form): season = forms.ModelChoiceField(queryset=Subject.objects.filter(...)) I want the value to be passed into the queryset in the season field. How do I do this? -
Django : Dropdown menu to show only unconfigured values
I have created two models - class DID_Definition_Model(models.Model): # DID to Region-Carrier Mapping region_carrier = models.ForeignKey(Telco_Carrier_Mapper_Model, on_delete=models.CASCADE) did_number= models.CharField(max_length=32, validators=[alphanumeric], primary_key=True) did_cost= models.DecimalField(max_digits=10, decimal_places=2) created_on_date = models.DateTimeField(default=timezone.now) class DID_Number_Assignment_Model(models.Model): #DID Number Assignment did_selector = models.ForeignKey(DID_Definition_Model, on_delete=models.CASCADE, primary_key=True) subscriber_department=models.CharField(max_length=200) usage_assignment=models.ForeignKey(Usage_Assignment_Model, on_delete=models.CASCADE) employee_email=models.EmailField() employee_fullname=models.CharField(max_length=200) created_on_date = models.DateTimeField(default=timezone.now) And created the below view - def did_assignment_form(request, did_selector=0): if request.method =="GET": if did_selector==0: form = DID_Number_Assignment_Model_Form() else: did_assignment_item = DID_Number_Assignment_Model.objects.get(pk=did_selector) form = DID_Number_Assignment_Model_Form(instance=did_assignment_item) return render(request, 'MASTERHANDLER/did_assignment_form.html', {'form':form}) else: if id==0: context = DID_Number_Assignment_Model.objects.values('did_selector') if did_selector not in context: form = DID_Number_Assignment_Model_Form(request.POST) else: did_assignment_item = DID_Number_Assignment_Model.objects.get(pk=did_selector) form = DID_Number_Assignment_Model_Form(request.POST, instance = did_assignment_item) if form.is_valid(): form.save() return redirect('did_assignment_list') Form detail below - class DID_Number_Assignment_Model_Form(forms.ModelForm): class Meta: model = DID_Number_Assignment_Model fields = ('did_selector', 'usage_assignment', 'employee_fullname', 'employee_email', 'subscriber_department' ) labels = { 'did_selector' : 'DID Selector', 'usage_assignment' : 'Number Usage ', 'employee_fullname' : 'Employee Full Name', 'employee_email' : 'Employee Email', 'subscriber_department' : 'Employee Department', } def __init__(self, *args, **kwargs): super(DID_Number_Assignment_Model_Form,self).__init__(*args, **kwargs) # TO SET drop down default text for a field , optional - self.fields['did_selector'].empty_label = "Select" self.fields['usage_assignment'].empty_label = "Select" # TO SET a field which may be optional - self.fields['subscriber_department'].required = False #self.fields['region_assigned'].required = False This form works with no problems but with one little oddity. If …