Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django invalid form
I am creating an update modelformset form, it renders the data correctly but when I click the submit button nothing happens and in the terminal I can see the message invalid data. Here's the Views.py def post(request): tform = TeamForm() pform = modelformset_factory(Player, form=PlayerForm, extra = 1) pform = pform(request.POST or None, queryset = Player.objects.filter(id__isnull = True)) if request.method == 'POST': t = Team() tform = TeamForm(request.POST, instance=t) if tform.is_valid() and pform.is_valid(): tform.save() instances = pform.save(commit=False) for i in instances: player = Player() player.pname = i.pname player.hscore = i.age player.age = i.hscore player.save() t.player.add(player) t.save() return redirect('/exams/dashboard/') else: print('invalid data') return render(request, 'team/team_create.html', {'exform': tform, 'exformset': pform}) def update(request, pk = None): team = Team.objects.get(id = pk) tform = TeamForm(instance = team) pform = modelformset_factory(Player, form=PlayerForm, extra=1) pform = pform(request.POST or None, queryset=Team.objects.get(id = pk).player.all()) if request.method == 'POST': tform = TeamForm(request.POST, instance=team) if tform.is_valid() and pform.is_valid(): tform.save() instances = pform.save(commit=False) for i in instances: player = Player() player.pname = i.pname player.hscore = i.age player.age = i.hscore player.save() t.player.add(player) t.save() return redirect('/exams/dashboard/') else: print('invalid data') return render(request, 'team/team_create.html', {'exform': tform, 'exformset': pform}) I have added post function too so that I can show that there is no problem in that … -
This site can’t be reached www.127.0.0.1’s server IP address could not be found. (Error in djnago)
The code was perfectly working. Suddenly, when i gave command, py -3 manage.py runserver, www.127.0.0.1:8000 came instead of 127.0.0.1:8000. I tried using local host also but not working. www.127.0.0.1:8000 is written on the title as well.enter image description here -
How to pass an id of specific item
I am trying to pass an id to page where I would be able to change the data of that item. I have a page, where I am displaying all instances of specific item: {% for copy in bikeloan.bikeinstance_set.all %} <hr> <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'm' %}text-danger{% else %}text-warning{% endif %}"> {{ copy.get_status_display }} </p> {% if copy.status != 'a' %} <p><strong>Due to be returned:</strong> {{ copy.due_back }}</p> {% endif %} <p><strong>Frame number:</strong> {{ copy.imprint }}</p> <p class="text-muted"><strong>Id:</strong> {{ copy.id }}</p> <a href="{{ copy.get_absolute_url }}">Loan</a> {% endfor %} I get a couple of results and I wanna be able to click on button loan and pass the id of that particular instance to new page. I have that in my models: class BikeInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular bike across whole stock') bike = models.ForeignKey('BikeLoan', on_delete=models.SET_NULL, null=True) frame_number = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) borrower = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) def get_absolute_url(self): return reverse("core:loan-user", args=[str(self.pk)]) and my urls: path('loan-user/<int:pk>', loan_bike, name='loan-user'), views.py: def loan_bike(request, pk): bikeloan = get_object_or_404(BikeInstance, pk=pk) return render(request, 'loan_user.html', context={'bikeloan': bikeloan}) When I enter a page, where all the instances are displayed I get that error: … -
Why isn't the related_name working for models?
There are question and answer tables related to each other. Each question has one answer. I need to check the answer field in the CompanyGeneralInfoAnswers model. class CompanyGeneralInfoQuestion(models.Model): rfi = models.ForeignKey(Rfis, models.DO_NOTHING) question = models.CharField(max_length=512) class Meta: db_table = 'company_info__questions' class CompanyGeneralInfoAnswers(models.Model): question = models.OneToOneField('CompanyGeneralInfoQuestion', models.DO_NOTHING, related_name='answer_to_question') answer = models.CharField(max_length=4096, blank=True, null=True) class Meta: db_table = 'company_info_answers' To do this, I make this request. round = kwargs.get('rfiid') exist_company_question = CompanyGeneralInfoQuestion.objects.filter(rfi=round) if exist_company_question: for q in exist_company_question: print(q.answer_to_question.answer) But got an error RelatedObjectDoesNotExist: CompanyGeneralInfoQuestion has no answer_to_question. -
Return can close Loop for? (python/django)
Does return on python close the Loop for? I'm asking that because I wrote a code that will search for me someone in a list and if know that person it will return me his age if not it will tell me "Person not found". If the person is in the first place of the Array if find it but if it is in the second he doesn't why? def lerDoBanco(name): lista_names = [ {'name': 'Joaquim', 'age': 20}, {'name': 'João', 'age': 25}, {'name': 'Ana', 'age': 27} ] for person in lista_names: if person['name'] == name: return person else: return {'name': 'Person not found', 'age': 0} def fname(request, name): result = lerDoBanco(name) if result['age'] > 0: return HttpResponse('The person was found, has ' + str(result['age']) + ' years old') else: return HttpResponse('Person not found') I ask that because if I comment the else statement it shows me all the people in the Array correctly. -
Pycharm Can't retrieve image ID from build stream
Want to connect pycharm docker interpreter. Here is my windows docker status and here is pycharm status how can I fix the issue -
How can i remove the name's field on the screen?
I have 2 question on the same subject if someone can help me please: 1.I display a form with django and i wanted to to remove the name of my field: Here is what the screen display : display and i want to remove "Columns:". Here is my form: class Features(forms.Form): columns = MultipleChoiceField(choices=FEATURES_CHOICES, widget=forms.CheckboxSelectMultiple) and here is my template: <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save"> </form> and here my view: def ChoiceView(request): context = {'form': forms.Features()} return render(request, 'data/home.html', context) Where I recover my result of selections or where go the results ? In which variable of which file (models, views,..) will go the results ? -
Token authentication for django channels
im trying to integrate React , django and django channels together , however im facing some trouble trying to authenticate the socket connection. There are some posts over here: first link enter link description here But they do not talk about how to utilize it over the front end portion. There are some posts which recommends to put the token within the URL , for example : WebSocket('wss://example.com/my-ws-endpoint/?token=' + token, ...) But there seems to be lots of security red flags in doing so. Therefore is there a simple easy way to resolve the token authentication issue for channel websockets here? -
Css not loading in Django
My css file is not getting loaded in the webpage. I have css and image file in the same location. The image is getting loaded but not the css.Also I have included the directory in staticfile_dirs. Setting.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(9szxe#x0q67)^wc6us01*i$=1)!&f7)530%73=pvzzhwp23gp' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'technicalCourse.apps.TechnicalcourseConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ r'C:\Users\Kesavan\PycharmProjects\Django web development\website\technicalCourse\template' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'website.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE … -
Router not displaying correct URL in Django RestFramework?
This is how I defined urls.py file of my app router = DefaultRouter() router.register('hello-viewset', views.HelloViewSet, base_name='hello-viewset') router.register('profiles', views.UserProfileViewSet) router.register('schema', views.SchemaViewSet) router.register('creddefination', views.CredDefViewSet) router.register('overalltable', views.OverallViewSet) urlpatterns = [ path('', include(router.urls)), ] urls.py of Project: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('DIAPI.urls')), ] I am not getting correct address for creddefination. But when i manually go to http://127.0.0.1:7000/api/creddefination/ it is working. It is just not displaying correctly. What might be reason for this -
Get overview of SQL query count for every test in a test suite
I have a large Django application with tons of tests that need SQL query optimizations. I don't want to add assertNumQueries or django-assert-num-queries for each test individually, but instead produce an overview about how many SQL queries each one of all of the tests are triggering, to know which code needs the most optimization, like this: test | number of queries ------------------------------------------------ test_a.py::test_my_function1 | 5 test_a.py::test_my_function3 | 2 test_a.py::test_my_function5 | 7 Is it possible to configure a pytest hook in conftest.py which counts the number of SQL queries for each (DB) test and shows them in result - without the need to modify the source of my tests (like adding decorators)?