Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to carry the filters to the next view?
I imagine something like this is possible in Django, but I don't know how to implement it: I have a TableView, which has filters to filter the displayed queryset. I, then, have a DetailView which you can access from the TableView, to see the details of each element in the queryset. The DetailView has a form, which uses the POST method. I can successfully send the form, and redirect to the TableView after the POST call. My question is, how can I make it so that after the user calls the POST method in the DetailView, and it redirects again to the TableView, the TableView keeps whichever values were on its filters? I imagine I would have to either get access to the full request on the TableView (because it includes the ?param1=?param2= etc.), or be able to send the values in the filters when I call the DetailView. -
Can not create Virtual Enviroment for Django Freamwork
C:\Users\Slavi\Documents\Django>python -m venv env Python I am triing to create virtual enviroment for django freamwork using the cmd in windows. When i try to create it it do not create anything just write Python on the next line and thats it....I am new at the Django and in the Python so please help. -
how can I display just plain text among posted information which have images, tables from CKEditor in Django?
As same as stack overflow does in a homepage, showing questions without images just with tags, I want my blog site to show just a title and a header in a list of blog posts page. the uploaded image ruins css card section and tables display half of it. so I would rather display just plain text. I am currently using Django(3.1.5), CKEditor. My question is; How to get a plain text from ckeditor?, how to catch a image uploaded from CKEditor, if I can, can I save those images into the model(ImageField or FileField)? -
Django forms - Allow a user to create a group for other users
I am trying to let a user create a "club" (basically a group) where the user later on can add users to. Currently it only displays the HTML text and the button, but no text field. Any suggestions would be appreciated since I am fairly new to forms. Model class Club(models.Model): owner = models.CharField(max_length=30) topic = models.CharField(max_length=30) start = models.DateTimeField(verbose_name='start date', auto_now_add=False) end = models.DateTimeField(verbose_name='end date', auto_now_add=False) account = models.ManyToManyField(Account) Views @login_required def add_club(request): if request.method == "POST": form = AddClubForm(request.POST, instance=request.user) print(form) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) else: form = AddClubForm(instance=request.user) return render(request, 'page/club.html', { "form": form, }) Form class AddClubForm(forms.Form): owner = forms.CharField(required=True) topic = forms.CharField(required=True) start = forms.DateField(required=True) end = forms.DateField(required=True) class Meta: model = Club fields = ( 'owner', 'topic', 'start', 'end', ) Template <form method="POST" action=""> {% csrf_token %} <div class="col-md-6"> <label class="labels">Create a club</label> {{ form.owner }} <input class="btn" type="submit" value="Add club"> </div> </form> -
How to log a django view
I'm learning to log and I'm not sure what I'm supposed to do with the logger in my view since what I've read around doesn't seem to work or I'm just not understanding something. This are my settings for the logging: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'todo': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), 'propagate': True, }, }, } This is the view and the logging part: from rest_framework import generics, filters from todo import models from .serializers import TaskSerializer from django_filters.rest_framework import DjangoFilterBackend import logging logger = logging.getLogger(__name__) def myview(request): logger.error('Something went wrong') class ListTask(generics.ListCreateAPIView): """ API view to retrieve list of tasks or create new tasks """ queryset = models.Task.objects.all() serializer_class = TaskSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['date'] search_fields = ['description'] class DetailTask(generics.RetrieveDestroyAPIView): """ API view to retrieve or delete a task """ queryset = models.Task.objects.all() serializer_class = TaskSerializer -
How to insert a Django template tag + HTML element in a HTML page with Javascript
How can I safely add a piece of HTML with Django template tags in it using Javascript? For example, if I have something like this in my template: <div id="some-element"> <span id="my-tag">{{ my_data }}</span> </div> <!-- rest of the html page --> If I were to use a script to just edit the innerHTML of the div, like the script below, it'd would just read {{ other-data }} as a string. How can I make it become an actual Django template tag? <script> document.getElementById("some-element").innerHTML = ` <h1>This is may new data {{ other-data }} </h1> {% if value %} <p>This is an if statement</p> {% endif %} ` </script> -
How to Stack Multiple Search Parameters in URL with Django and Ajax
I'm trying to create a filter system on a webpage such that the user can bookmark their searches. The page loads from the basic url: path('foobar/counts', views.foobarCount, name='foobar_counts') This URL loads the proper template on top of the base template and includes everything needed. From there, a series of filters are set up, which send an ajax request to the server. The user can select as many or as few filters as they'd like. The Ajax url is set up as follows: path('foobar/counts/filter', views.foobarCountFilter, name='foobar_count_filter') This all works just fine when the user starts at the foobar/counts URL, but when they want to paste in something like: /foobar/counts/filter?startDate=2001-01-12&endDate=2021-01-12&startComp=2021-01-01&endComp=2021-01-31&assigns... The system properly receives the Ajax request and brings back the proper information, but it does not include the other templates needed to load the webpage. It displays as essentially a plaintext version. Is there a minimally invasive way to retroactively load all the necessary templates when pasting in the search URL? -
How to do ModelName.objects.filter in html
I'm trying to eliminate the amount of code I need to put in my view and want to do this in my html file: {% for committee in c %} {% for article in Article.objects.filter(committee=committee) %} <a class="post-link" href="{% url 'update' id=article.id %}">{{article.title}}</a> {% endfor %} {% endfor %} I am passing my article model and list of c as context in my view. But it gives me this error: TemplateSyntaxError at /admin-dash/ Could not parse the remainder: '(committee=committee)' from 'Article.objects.filter(committee=committee)' Request Method: GET Request URL: http://127.0.0.1:8000/admin-dash/ Django Version: 3.1.3 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '(committee=committee)' from 'Article.objects.filter(committee=committee)' Exception Location: C:\Users\benja\anaconda3\lib\site-packages\django\template\base.py, line 662, in __init__ Python Executable: C:\Users\benja\anaconda3\python.exe Python Version: 3.8.3 Python Path: ['C:\\Users\\benja\\Desktop\\mysite\\mysite', 'C:\\Users\\benja\\anaconda3\\python38.zip', 'C:\\Users\\benja\\anaconda3\\DLLs', 'C:\\Users\\benja\\anaconda3\\lib', 'C:\\Users\\benja\\anaconda3', 'C:\\Users\\benja\\anaconda3\\lib\\site-packages', 'C:\\Users\\benja\\anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\benja\\anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\benja\\anaconda3\\lib\\site-packages\\Pythonwin'] Server time: Tue, 12 Jan 2021 19:41:28 +0000 Error during template rendering In template C:\Users\benja\Desktop\mysite\mysite\blog\templates\admin.html, error at line 18 Could not parse the remainder: '(committee=committee)' from 'Article.objects.filter(committee=committee)' 8 <link rel="stylesheet" href="{% static 'css/admin.css' %}"> 9 <link rel="stylesheet" href="{% static 'css/posts.css' %}"> 10 </head> 11 <main> 12 13 14 <div class="admin-panel"> 15 <div class="posted"> 16 <h1 style='font-size: 7rem; margin-bottom: 20px; margin-top: 0;'>Posts:</h1> 17 {% for committee in c %} 18 {% for article in … -
Enforce or test on_delete behavior of all ForeignKey fields using a specific model
Let's say I have a proxy user model as class UserWithProfile(User): profile_description = models.TextField() class Meta: proxy = True ordering = ('first_name', ) I want to make certain that all data which could in the future be associated with a UserWithProfile entry is deleted when this profile is deleted. In other words I want to guarantee the on_delete behavior of all existing and future ForeignKey fields referencing this model. How would one implement either a test checking this, or raise an error when another on_delete behavior is implemented? I know it would be possible to make a custom ForeignKey class, which is what I will be probably doing, ... class UserWithProfileField(models.ForeignKey): def __init__(self, *args, **kwargs): kwargs.setdefault('to', UserWithProfile) kwargs.setdefault('on_delete', models.CASCADE) super().__init__(*args, **kwargs) ... however that couldn't stop future users from using the ForeignKey class with a different on_delete behavior. -
UNIQUE constraint failed: authtoken_token.user_id while performing login using Django Framework
Getting the below error while trying to login using DRF API** IntegrityError at /api/auth/login UNIQUE constraint failed: authtoken_token.user_id Request Method: POST Request URL: http://127.0.0.1:8000/api/auth/login Django Version: 2.2.16 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: authtoken_token.user_id Exception Location: D:\Django\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: D:\Django\venv\Scripts\python.exe Python Version: 3.8.2 Python Path: ['D:\\Django\\UserAPI', 'c:\\program files\\python38\\python38.zip', 'c:\\program files\\python38\\DLLs', 'c:\\program files\\python38\\lib', 'c:\\program files\\python38', 'D:\\Django\\venv', 'D:\\Django\\venv\\lib\\site-packages'] Server time: Tue, 12 Jan 2021 19:12:18 +0000 UNIQUE constraint failed: authtoken_token.user_id while performing login using Django Framework serializer.py from django.contrib.auth import get_user_model from rest_framework.authtoken.models import Token from rest_framework import serializers from django.contrib.auth.models import BaseUserManager,AbstractBaseUser User = get_user_model() class UserLoginSerializer(serializers.Serializer): username = serializers.CharField(max_length=8, required=True) password = serializers.CharField(max_length=6,required=True, write_only=True) class AuthUserSerializer(serializers.ModelSerializer): auth_token = serializers.SerializerMethodField() class Meta: model = User fields = ('id','username', 'password', 'email', 'mobileno','auth_token') def get_auth_token(self, obj): token = Token.objects.create(user=obj) return token.key class EmptySerializer(serializers.Serializer): pass class UserRegisterSerializer(serializers.ModelSerializer): """ A user serializer for registering the user """ class Meta: model = User fields = ('id','username', 'password','email','mobileno') def validate_username(self, value): user = User.objects.filter(username='username') if user: raise serializers.ValidationError("Username is already taken") return AbstractBaseUser.normalize_username(value) views.py from django.contrib.auth import get_user_model,logout from django.core.exceptions import ImproperlyConfigured from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.permissions import AllowAny from rest_framework.response import Response from .import … -
Django Update Existing ImageField not working
I want to give a user the ability to update the image associated to a record. I have an edit form that allows the user to update various elements of a record all of which are updating correctly except for the image fields. The image field when assigned to the record is displaying so adding the image to the record on creation fo the record works fine. I have reviewed similar Q&As and they have not helped. Models.py class ComicInput(models.Model): CoverPic = models.ImageField(upload_to='Comic_Pics', default='Comic_Pics/default.png',blank=True) def __str__(self): return '%s %s %s' % ( self.CoverPic) def __unicode__(self): return '%s %s %s' % ( self.CoverPic) Forms.py class ComicInputForm(forms.ModelForm): class Meta: model = ComicInput fields = '__all__' Views.Py def edit(request, id): record = ComicInput.objects.get(pk = id) return render(request, 'app/edit.html',{"ComicInput":record}) def update(request, id): updaterecord = ComicInput.objects.get(pk = id) if request.method == "POST": form = editform(request.POST or None, request.FILES or None, instance=updaterecord) if form.is_valid(): edit = form.save(commit=False) edit.save() return ComicInventory(request) else : form = editform(instance=updaterecord) messages.error(request,"Error, please try again taking note of validation rules on the right") return render(request, 'app/edit.html', {'form':form,"ComicInput":updaterecord}) def delete(request, id): deleterecord = ComicInput.objects.get(pk = id) deleterecord.delete() return ComicInventory(request) Urls.py path('edit/<int:id>', views.edit, name='edit'), path('update/<int:id>', views.update, name='update'), path('delete/<int:id>', views.delete, name='delete'), Template - edit.html <!DOCTYPE … -
checking if a certain many to many foreign key is present on django-polymorphic models
So in order to create an object model, I have to first see if a supplier has a relation of type many to many from BusinessModel, WarehouseModel or StoreModel to in a django-polymorphic My main idea is to check if BusinessModel, which is connected to Order through BusinessOrderModel, StoreModel, which is connected to Order through StoreOrderModel or WarehouseModel which is connected directly to Order, have FKs on a many to many relationship going to the article that we want to order through a POST request. class ArticleModel(models.Model): id = models.AutoField(primary_key=True) code = models.IntegerField(unique=True) description = models.TextField() def __str__(self): return str(self.code) class OrderModel(models.Model): id = models.AutoField(primary_key=True) order_to = models.ForeignKey('OrderToModel', on_delete=models.CASCADE) article = models.ForeignKey('ArticleModel', on_delete=models.CASCADE) quantity= models.IntegerField() class OrderToModel(Porrodriguez@odoogrp.comlymorphicModel): id = models.AutoField(primary_key=True) class WarehouseModel(OrderToModel): warehouse_num = models.IntegerField(unique=True) name = models.CharField(max_length=100) address = models.TextField() articles = models.ManyToManyField(ArticleModel) def __str__(self): return "Warehouse"+ str(self.warehouse_num) class StoreOrderModel(OrderToModel): reference = models.IntegerField(unique=True) store_num = models.ForeignKey('StoreModel', on_delete=models.CASCADE) def __str__(self): return str(self.reference) class StoreModel(models.Model): store_num = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) address = models.TextField() articles = models.ManyToManyField(ArticleModel) def __str__(self): return str(self.store_num) class BusinessOrderModel(OrderToModel): reference = models.IntegerField(unique=True) business_num = models.ForeignKey('BusinessModel', on_delete=models.CASCADE) def __str__(self): return str(self.reference) class BusinessModel(models.Model): Business_num = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) address = models.TextField() articles = models.ManyToManyField(ArticleModel) def __str__(self): return … -
Specify multi-language description tag when using Django i18n
I recently published a webapp made with django, which serves content in both Italian and English. To accomplish that, I used Django's internalization pack, i18n. The content is currently being served according to user's accept-language header, with Italian being served if the user asks for it language in the header, and English being the default for when the header is absent or containing any other language code. In addition to that, I also have the following tags <link rel="alternate" hreflang="it" href="https://mywebsite.com/it/" /> <link rel="alternate" hreflang="en-us" href="https://mywebsite.com/en-us/" /> <link rel="alternate" hreflang="x-default" href="https://mywebsite.com/en-us/" /> Which I accomplished with the following urls.py config: urlpatterns += i18n_patterns( path('jsi18n/', JavaScriptCatalog.as_view(packages=['appname'], domain="django"), name='javascript-catalog'), ) as suggested in the official docs. I would like my website homepage (which is the only publicly accessible page of the website) to have a meta description tag to be shown to Italian users, and one in English. What's the best way to accomplish this with my current configuration, given that ultimately it's a single page that's being served and not one per language? -
How do i create and use variables in django
New to Django and its templates. I'm trying to set a variable given a specific situation, and that part I think ill be able to do, the code below isn't the exact conditions its just there as a demo. The part im stuck on is how do i create a variable name, and then use that name variable elsewhere. Such as within a div or within a method or anywhere else within the html file, and withing different <Script> tags to run methods and for really any purpose. demo scenario : {% for row in table.rows %} {% if row == 2 %} {% var name = row.name %} {% endif %} {% endfor %} {% if name %} <div>{{name}}</div> {% endif %} my actual code Im trying to implement: <script type="text/javascript"> function map_init_basic(map, options) { var markerClusters = L.markerClusterGroup({ chunkedLoading: true }); {% for row in table.rows %} var x = "{{ row.cells.x }}" var y = {{ row.cells.y }} var m = L.marker([y, x]) m.bindPopup("{{row.cells.first_name}} {{row.cells.last_name}} <br>{{row.cells.chgd_add}}"); m.on("click" , ()=>{ //console.log(`${first_name} ${last_name}`) {% var first_name = {{row.cells.first_name}} %} }) //changed row.cells.chgd_add to row.cells.Chgd_add to make sure its matching the table markerClusters.addLayer(m); {% endfor %} markerClusters.addTo(map); } {% if … -
Django correct list using article_id
views.py def article(request, article_id): return render(request, 'article.html', { 'article': Article.objects.get(id=article_id) }) urls.py from . import views urlpatterns = [ path('articles/', views.articles, name='articles'), path('articles/<int:article_id>/', views.article, name='article'), ] article.html <div class="pagination"> <a href="#">&laquo;</a> <a class="active" href="/articles/{{ article.id }}/">1</a> <a href="/articles/{{ article.id }}/">2</a> <a href="#">3</a> <a href="#">4</a> <a href="#">5</a> <a href="#">6</a> <a href="#">&raquo;</a> </div> Someone can tell me how add to pagination list correct article by correct id and last and end article ID in HTML? Thanks a lot -
Can I get the property of a specific object in a Django template?
I am using django-filters in my project. Let's say I get this address after a search: ?title=my title&ms=8 As you can see, I've searched for 'my title' and for a manuscript which the user sees as 'my manuscript', but whose get parameter (and ID) is 8. Now, I'd like to add to my template a courtesy 'you've searched for' field. How can I show the title of that manuscript, rather than its ID? I already have the ms objects in my view: mstunes = MsTune.objects.all() ms = Manuscript.objects.all() <- manuscripts f = MsTuneFilter(request.GET, queryset=MsTune.objects.all()) return render(request, 'manuscript/mstune_list.html', {'mstunes': mstunes, 'f': f, 'request':request, 'ms': ms}) and I can indeed access them with {{ms.all}}. Is it possible to do something, in pseudo code, like: show the ms.title of the ms object with id = request.GET.ms ? -
Auto fill up Django model
I'm building an application that display tests included in a project. User can set the test result of each tests. My model contain 3 basic classes: Requirement - in this class i want to hold every tests. Something like template table. class Requirement(models.Model): requirement_name = models.CharField(max_length=256, default=None) nist = models.CharField(max_length=10, blank=True, null=True, default=None) cwe = models.CharField(max_length=10, blank=True, null=True, default=None) lvl1 = models.BooleanField(default=True) lvl2 = models.BooleanField(default=True) lvl3 = models.BooleanField(default=True) stand2 = models.IntegerField(default=2) stand3 = models.IntegerField(default=2) stand4 = models.IntegerField(default=2) stand5 = models.IntegerField(default=2) stand6 = models.IntegerField(default=2) stand7 = models.IntegerField(default=4) Project - contain all projects created by users class Project(models.Model): project_name = models.CharField(max_length=256, default=None) date_made = models.DateTimeField( auto_now_add=True) owner = models.ForeignKey(User, default=None, on_delete=models.CASCADE) lvl1_project = models.BooleanField(default=True) lvl2_project = models.BooleanField(default=True) lvl3_project = models.BooleanField(default=True) stand2_project = models.BooleanField(default=True) stand3_project = models.BooleanField(default=True) stand4_project = models.IntegerField(default=1) stand5_project = models.IntegerField(default=0) stand6_project = models.IntegerField(default=2) stand7_project = models.IntegerField(default=4) ReqsProject - in this table i want to store all of requirements that are stored in class Requirements class ReqsProject(models.Model): project_id = models.ForeignKey(Project, default=None, on_delete=models.CASCADE) requirement_id = models.ForeignKey(Requirement, default=None, on_delete=models.CASCADE) status = models.BooleanField(default=True) result = models.BooleanField(default=True) How can I automaticly fill up table ReqsProject when user create own Project. This may be something like this: ID Project ID Requirement ID Status Result 1 1 … -
Why isn't the BooleanField changing value in Django models?
I'm working in an Auction website which let the user list an auction and close it afterwards. The auction models has a boolean field called is_closed that stores if the auction is closed or not. When the user clicks a "Close Auction" button, he will be lead to this view that only changes the value of this field (that is false by default) and then saves the changes. def close_auction(request, auction_id): if request.method=="POST": target_auction = Auction.objects.get(id=auction_id) target_auction.is_closed=True target_auction.save() return HttpResponseRedirect(reverse('auction', kwargs={'auction_id':target_auction.id})) However, the field doesn't change, even though I am redirected to a html page that is loaded when the auction is closed successfully. When I go to the admin/ page the is_closed field indeed is unchanged (still marked as false). If what I did here is illegal, why there is no error message? Here is the Auction model: class Auction(models.Model): title = models.CharField(max_length=64) description = models.TextField(max_length=100, default="") image_url = models.CharField(max_length=100, default="https://elitescreens.com/images/product_album/no_image.png") category = models.ForeignKey(Category, on_delete=models.CASCADE, default="", related_name="auction_category") bid = models.OneToOneField(Bid, on_delete=models.CASCADE, null=True) creation_date = models.CharField(max_length=30, default="-----") owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, default="") is_closed = models.BooleanField(default=False) Any ideas? -
Django admin actions bar missing? Template expecting "action_form" context variable but mine is showing "action_confirm_form"
As the title says, I'm having an issue that I cant seem to find any reference of anywhere else online. I was working on creating a custom Django admin action that provides and intermediate page for additional request data before updating the selected models. I followed these posts to accomplish this: Displaying an Admin Action Popup and Displaying an Admin Action Confirmation Page. I got everything working and then I went back to add some comments and after the server restarted when detecting changes, the admin action bar completely disappeared (see screenshot below). Another thing to note, my Django project has two separate apps, each with their own admin site and the actions drop-down disappeared from both sites for all model's change list view. Admin Actions Missing When inspecting the context of the admin site using the debug_toolbar I see this: {'action_confirm_form': <ActionForm bound=False, valid=Unknown, fields=(action;select_across)>, 'actions_on_bottom': False, 'actions_on_top': True, 'actions_selection_counter': True, 'available_apps': ... And when looking at the admin site context of a different clone of the repo with the admin actions working as expected I see this: {'action_form': <ActionForm bound=False, valid=Unknown, fields=(action;select_across)>, 'actions_on_bottom': False, 'actions_on_top': True, 'actions_selection_counter': True, 'available_apps': ... It appears that the context variable action_form was … -
like button for a blog post in Django
Looked over a few posts on Stack, but don't appear to see an answer. I am trying to get the blog post to send the like button as a notification. I currently have the comments working fine, i can comment on a blog and that will send a notification to the user who wrote the blog. I just cant appear to get the like button to notify. The blog post can be accessed by the title, to show you the post-detail screen of the individual post. On there we have a like button which i would like to be pressed and notify correctly. Thank you, i am a little experienced but still trying to gain a better understanding. Models.py from typing import cast from django.contrib.auth.decorators import user_passes_test from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields.related import ForeignKey from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.db.models.signals import post_save, post_delete from notifications.models import Notification class Category (models.Model): named = models.CharField(max_length=100) def __str__(self): return self.named def get_absolute_url(self): return reverse('home') # Create your models here. cat_new_choice = Category.objects.all().values_list('named', 'named') # first BLOG table - TEST this is how you create it! class Post(models.Model): title = models.CharField(max_length=100) … -
Wagtail - How to save a record which uses InlinePanel containing M2M
I have a model which uses an InlinePanel to reference another model (ClubTimetable) which itself contains an M2M relationship to DayOfTheWeek. It seems as though I am unable to save the record because ClubTimetable is not yet saved and cannot create the M2M relationship to DayOfTheWeek, causing the following error: "<ClubTimetables: Club Timetable (str) 18:00:00>" needs to have a value for field "id" before this many-to-many relationship can be used. What can I do to solve this issue? My models look like this # ClubManager @register_snippet class ClubManager(ClusterableModel): name = models.CharField('Club name', max_length=255, help_text='The name of the club.') panels = [ FieldPanel('name'), InlinePanel('club_timetable', heading='Timetable Information') ] # ClubTimetables class ClubTimetables(Orderable, AddressBase): attached_to = ParentalKey( 'club.ClubManager', related_name='club_timetable') weekday = models.ManyToManyField(DaysOfTheWeek) start_time = models.TimeField() end_time = models.TimeField() panels = [ ... ] + AddressBase.panels # DaysOfTheWeek class DaysOfTheWeek(models.Model): weekday = models.CharField(max_length=9) def __str__(self): return self.weekday Visually, it looks like this (Initial) (Adding timetable) -
Missconfigures Django settings, ModuleNotFoundError: No module named 'DeveloperRoad'
I'm making a django blog app and I created a Custom User, modifying the AUTH_USER_MODEL constant in the settings.py file. But the database drop an IntegrityError, so I though it was that the configuration file wasn't being imported, and I did the following command,with virtualenv activated: export DJANGO_SETTINGS_MODULE=DeveloperRoad.settings My project app is named DeveloperRoad and the settings file is settings,so I'm not sure what I'm doing wrong. My project structure is the following: DeveloperRoad ├── blog │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── templates │ │ └── blog │ │ ├── add_category.html │ │ ├── add_post.html │ │ ├── author.html │ │ ├── categories.html │ │ ├── categories_list.html │ │ ├── delete_post.html │ │ ├── details.html │ │ ├── edit_post.html │ │ └── index.html │ ├── templatetags │ │ ├── extra_filters.py │ │ ├── __init__.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── DeveloperRode │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── members │ ├── admin.py │ ├── apps.py │ ├── backends.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ … -
preventDefault doesn't always work and the event is executed
I have encountered such a problem that the cancellation event of the form submission does not always work, namely in 30% of cases the event is not cancelled. I send a request by GET method to Django server and get json from it. In 70% of the cases I get the json and my function is already called which handles that json. But in the other 30% I get the json and it is immediately displayed on the screen and I get this text in the console: "content.js:200 JSON Formatter: Type "json" to inspect." Can you please tell me why this happens and how to fix it? let form=document.querySelector('form') form.onsubmit=(e)=>{ e.preventDefault(); setTimeout(()=>{ fetch(form.action, { method: "GET", }) .then(response => response.json()) .then(function(json) { if (json.status){ caseFormation(json) } }) .catch(function(error) { console.log(error) }); },1000) } -
django reathenticate middleware
as a relative noob to django I have been creating a users app. I would like a logged in superuser to have to reauthenticate if they access the admin area having used the rest of the app. I am trying this custom middleware that I have written. Is there a django integrated solution to this problem already, and are there any issues that you can see with my code? from django.shortcuts import redirect from django.contrib import messages from django.contrib.auth import logout import re class ReauthenticateMiddleware: def __init__(self, get_response): self.get_response = get_response self.pages = [] # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if request.user.is_superuser: match = re.match(r'/admin/', request.path) if len(self.pages) and self.pages[-1] is not None and match is not None: referred = re.match(r'/admin/', self.pages[-1]) if referred is None and match is not None: messages.add_message(request, messages.INFO, 'You must reauthenticate') logout(request) self.pages = [] return redirect('/admin/login/') if request.path[-1] == '/': self.pages.append(request.path) response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response I have the custom middleware on the python path and have added it to settings … -
'relation "django_site" does not exist' only when running Django tests in GitHub Actions
I have a Django 3.1 project with an Admin class like this really simple example: from django.contrib import admin from .models import Book class BookAdmin(admin.ModelAdmin): def book_title(self, obj): return obj.title admin.site.register(Book, BookAdmin) And I test that class: from django.contrib.admin.sites import AdminSite from django.test import TestCase from myapp.admin import BookAdmin from myapp.models import Book class BookAdminTestCase(TestCase): def test_book_title(self): book = Book(title="Hello") book_admin = BookAdmin(Book, AdminSite()) self.assertEqual(book_admin.book_title(book), "Hello") This works fine when I run tests (./manage.py test) on my local development site. But when I run tests in a GitHub Action step... - name: Run Tests run: | pipenv run ./manage.py collectstatic --verbosity=0 --noinput pipenv run ./manage.py test env: DJANGO_SETTINGS_MODULE: config.settings.tests # etc ...while other tests all work fine, tests using the AdminSite() call fail with: psycopg2.errors.UndefinedTable: relation "django_site" does not exist 196 LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... These tests use the same Django settings as when run locally. If I run migrations in the GitHub Actions step before I run the tests... - name: Run Tests run: | pipenv run ./manage.py collectstatic --verbosity=0 --noinput pipenv run ./manage.py migrate --verbosity=0 --noinput pipenv run ./manage.py test env: DJANGO_SETTINGS_MODULE: config.settings.tests # etc ...this error doesn't occur, so I can get round this, but …