Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does my content-security-profile (django-csp) not work properly for a view/template loaded in a bootstrap modal? Works fine otherwise
I didn't include the template code because it is irrelevant. This is the script tag in the template: <script nonce="{{ CSP_NONCE }}" src="{% static 'js/mmImport.js' %}" defer data-mmimporturl="{% url 'mmImport' %}"> </script> Settings.py MIDDLEWARE = [ 'csp.middleware.CSPMiddleware' ....] # Content Security Policy', CSP_DEFAULT_SRC = ("'self'") CSP_IMG_SRC = ("'self'") CSP_STYLE_SRC = ("'self'") CSP_SCRIPT_SRC = ("'self'") CSP_INCLUDE_NONCE_IN = ('script-src')` So two scenarios... I load this view/template in a modal that is in the homepage. If I include 'unsafe-inline, no issues. It works. Form/view/template behaves normally. Without unsafe-inline and just the above policies, it gives the following error: [Error] Refused to execute a script because its hash, its nonce, or 'unsafe-inline' does not appear in the script-src directive of the Content Security Policy. (mmHomepage, line 0) I load the view as its own page/template; not a modal. Straight forward Django template. With CSP policies as above, the page works normally. No errors. I suspect it is the way a view/template is handled by bootstrap modals. Not sure where to look. I am new to Django-csp so not familiar with this. Just started familiarizing myself with the spec. I also tried bringing this js code into the template, so not calling a separate file. … -
Django Project "failed to install application dependencies" On Elastic Beanstalk
My coworker and I are attempting to upload a website we have been working on to AWS Elastic Beanstalk. We have tried using both console & command line techniques to create the instance and in both cases it ends with the 4 errors: Instance deployment failed to install application dependencies. The deployment failed. Instance deployment failed. For details, see 'eb-engine.log'. [Instance: i-0deb02382df3b0fd9] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. Create environment operation is complete, but with errors. For more information, see troubleshooting documentation. Neither of us have experience with working with AWS before, and we spent several hours attempting to find solutions to this and nothing has worked. Our Django project has a Requirements.txt file, and a .ebextensions folder with a django.config file inside. enter image description here Contents of the django.config file: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: GMIFY.wsgi:application Contents of the requirements.txt file: (made by doing pip freeze > requirements.txt) asgiref==3.7.2 awsebcli==3.21.0 botocore==1.35.34 cement==2.10.14 certifi==2024.8.30 charset-normalizer==3.3.2 colorama==0.4.6 Django==5.0.3 django-extensions==3.2.3 idna==3.10 jmespath==1.0.1 numpy==2.0.0 pandas==2.2.2 pathspec==0.10.1 psycopg2-binary==2.9.9 pypiwin32==223 python-dateutil==2.9.0.post0 pytz==2024.1 pywin32==307 PyYAML==6.0.2 requests==2.32.3 semantic-version==2.10.0 setuptools==75.1.0 six==1.16.0 sqlparse==0.4.4 termcolor==2.5.0 tzdata==2024.1 urllib3==1.26.20 wcwidth==0.2.13 whitenoise==6.6.0 We have tried accessing the logs, but there was no clear line(s) indicating what … -
How to get data from another model in DetailView
I'm trying to get objects from two models using DetailView. First, I set urls.py: from django.urls import path from . views import RetiroListView, RetiroDetailView from . import views urlpatterns = [ path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/', views.post, name='post-post'), ] Here are my models: from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Comment(models.Model): post = models.OneToOneField(Post, on_delete=models.CASCADE, primary_key=True) comment=models.CharField(max_length=100) class Tags(models.Model): post = models.OneToOneField(Post, on_delete=models.CASCADE, primary_key=True) comment=models.CharField(max_length=100) and the detail view: class PostDetailView(DetailView): model = Post Now, in my template, I can use: {{ object.title }} To access my post information but, I need to get some info from the other tables, in this view. I know I have to overwrite the get_context_data method, but I don't know how. -
Django Rest Framework TokenAuthentication not working "Invalid Token"
I'm successfully creating a token upon a user's login (using a CustomUser model that replaces the username field with email), but when using this token in subsequent requests, the response is "Invalid token". Below are excerpts from the relevant files: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'goals', 'rest_framework', 'rest_framework.authtoken', ] ... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } Views to register and login users in users/views.py class UserRegistrationView(generics.CreateAPIView): serializer_class = UserSerializer permission_classes = [permissions.AllowAny] class UserLoginView(APIView): def post(self, request): user = authenticate(username=request.data['email'], password=request.data['password']) if user: token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) else: return Response({'error': 'Invalid credentials'}, status=401) The view I'm testing in goals/views.py: @api_view(['POST']) @permission_classes((IsAuthenticated, )) def create_topic(request): data = JSONParser().parse(request) serializer = TopicSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) else: return Response(serializer.errors, status=400) The test that fails in goals/tests.py class SerializerTests(TestCase): def setUp(self): email = "normal@user.com" pw = "foo" self.user = CustomUser.objects.create_user(email=email, password=pw) self.user_data = {'email':email, 'password':pw} login_response = self.client.post('/users/login/', data=json.dumps(self.user_data), content_type="application/json") print(login_response.data) self.token = login_response.data['token'] self.headers = {'Authorization': 'Token {self.token}'} def test_create_topic(self): self.topic = {'name':'topic_1', 'created_by':self.user.pk} response = self.client.post('/goals/topic/create/', data=json.dumps(self.topic), content_type="application/json", headers=self.headers) #should this be replaced by some DRF components? self.assertEqual(201, response.status_code) Unfortunately response.data simply states {'detail': ErrorDetail(string='Invalid token.', code='authentication_failed')}. This … -
Django custom function taking a long time to run for the view
I have a function below that generates a navigation so it can be using in the view. It is pulling in the articles, article category, and article subcategory. The main issue is that with about 15 category and 46 subcategory and 33 articles it is taking like 7-10 seconds to finish loading this function. What is the best approach for handling this so that it loads faster? def generate_navigation_list(request): articles = Article.objects.all() article_category = ArticleCategory.objects.all() articles_sub_category = ArticleSubCategory.objects.all() # Create a navigation list structure navigation_list = [] # Iterate over categories for category in article_category: category_dict = { 'id': category.id, 'title': category.name, 'subcategory': [] } # Filter subcategories for the current category filtered_subcategories = articles_sub_category.filter(category=category) # Iterate over filtered subcategories for subcategory in filtered_subcategories: subcategory_dict = { 'id': subcategory.id, 'title': subcategory.name, 'articles': [] } # Filter articles for the current subcategory filtered_articles = articles.filter(sub_category=subcategory).order_by('order') # Add articles to the subcategory dictionary if there are articles if filtered_articles.exists(): # Check if there are any articles for article in filtered_articles: article_dict = { 'title': article.title, 'slug': article.slug } subcategory_dict['articles'].append(article_dict) # Append subcategory dictionary to category dictionary category_dict['subcategory'].append(subcategory_dict) # Append category dictionary to navigation list if it has subcategories with articles if category_dict['subcategory']: … -
xhtml2pdf position header and content
how to position top content after a header, if header height is auto depending the content of header. If the top position of the content is not automatic, it will overlap if there is a change in size. style.css @page { size: a4 portrait; @frame header_frame { -pdf-frame-content: header_content; left: 2cm; width: 17cm; top: 1.5cm; height: auto; #keep changing } @frame content_frame { left: 2cm; width: 17cm; top: 10cm; #here height: 14cm; } } <div id="header_content"> header content height is changing depends on header content </div> <div id="content_content"> content of pdf </div> i have try to change top position to auto but cant change -
Django Admin Grappelli Adding Custom Navigation in Header
I want to be able to remove the whole header which includes the grp-navigation and grp-context-navigation found in the inspect element and add a custom navigation bar. This custom navigation bar is being used on my non-admin front facing application. I am using Django 4.2.7 and Grappelli 3.0.8 . Whats the best approach? -
How do I apply a colorscale to Plotly's histogram using the y values?
The histogram displays a number of items per month, but it appears to be using the wrong axis (or something else entirely) for the colorscale. I cannot find any information about this issue anywhere online. Here is my current histogram: Here is the relevant code: import plotly.graph_objects as go import plotly.colors as pcolors graph_dates = [ # list of datetime.datetime objects, one per item ] graph_counts = [ # list of distinct month counts ] figure = go.Figure() figure.add_trace(go.Histogram( x = graph_dates, marker = { 'colorscale': [[0, '#0000ff'], [1, '#ff0000']], #pcolors.sequential.Bluered, 'color': [0, 1], 'showscale': True, 'colorbar': { 'title': "Colors", }, 'cmin': 1, 'cmax': max(graph_counts), #'autocolorscale': False, # does nothing #'cauto': False, # does nothing #'colorsrc': 'y', # does nothing 'line': { # almost anything I put in here does nothing } }, xbins = { 'size': 'M1', # group by month }, )) figure.update_xaxes( range = [min(graph_dates), datetime.datetime.now(tz=datetime.timezone.utc)] ) graph = figure.to_html(include_plotlyjs=False, full_html=False) context['graph'] = graph Note: Please avoid using plotly.express and pandas. -
Django GIS: initGEOS_r symbol not found on MacOS
I'm experiencing an issue with Django GIS on my MacOS machine. When I try to run my Django application, I get the following error: Traceback (most recent call last): File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/manage.py", line 22, in <module> main() File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django_eventstream/models.py", line 7, in <module> class EventCounter(models.Model): File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/db/models/base.py", line 143, in __new__ new_class.add_to_class("_meta", Options(meta, app_label)) File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/db/models/base.py", line 371, in add_to_class value.contribute_to_class(cls, name) File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/db/models/options.py", line 231, in contribute_to_class self.db_table, connection.ops.max_name_length() ^^^^^^^^^^^^^^ File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/utils/connection.py", line 15, in __getattr__ return getattr(self._connections[self._alias], item) ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^ File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/utils/connection.py", line 62, in __getitem__ conn = self.create_connection(alias) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/db/utils.py", line 193, in create_connection backend = load_backend(db["ENGINE"]) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/db/utils.py", … -
Access to the searched word in Filters through the Table class
Friends, I have a table (django-tables2) and a search filter called 'comment'. (django-filters) I want to access the searched word inside the Table class. For example, inside the qs() event or somewhere else, I pass it to the request, so that I can access it on the other side in the Table class. class CommentFilter(FilterSet): class Meta: model = Comments fields = ['comment'] @property def qs(self): parent = super().qs # here I want to pass it search_key=self.data.get('comment') return parent The table class : class CommentTable(tables.Table): def render_comment(self, record): return record.comment -
two word param search
my instance's name is "hello world",just imagine in an urgent situation, i am going to search with param as "helloworld". how to handle without space cases if q: normalized_q = q.replace('_', ' ').replace('-', ' ').replace('/', ' ').strip() programs = programs.annotate( search=SearchVector( Replace(Replace(Replace('marketing_title', Value('_'), Value(' ')), Value('-'), Value(' ')), Value('/'), Value(' ')), Replace(Replace(Replace('slug', Value('_'), Value(' ')), Value('-'), Value(' ')), Value('/'), Value(' ')), Replace(Replace(Replace('name', Value('_'), Value(' ')), Value('-'), Value(' ')), Value('/'), Value(' ')) ) ) search_query = SearchQuery(normalized_q) programs = programs.filter( Q(search=search_query) | Q(name__icontains=normalized_q) | Q(program_duration__icontains=normalized_q) ) -
Error initializing the from_config() function in teh embedchain package
I am facing an issue in initializing the from_config() function of embedchain package: Here is my code: from embedchain import App from openai import OpenAI import yaml def initialize_bots(config_filename='config.json'): global news_bot, email_bot, link_inserter_bot, image_inserter_bot, article_bot # Load the JSON configuration directly # Determine the base directory based on whether the script is running as a standalone executable or as a script if getattr(sys, 'frozen', False): # Running as an executable base_directory = sys._MEIPASS # Temporary folder where the executable's data is unpacked else: # Running as a script base_directory = os.path.dirname(os.path.abspath(__file__)) config_file_path = os.path.join(base_directory, config_filename) # Debug statement: if os.path.exists(config_file_path): print(f"{config_filename} is present in the base directory.") else: print(f"{config_filename} is NOT present in the base directory.") # Check if the configuration file exists if not os.path.exists(config_file_path): raise FileNotFoundError(f"The configuration file {config_file_path} does not exist.") # Load the configuration file with open(config_file_path, 'r') as file: config_data = json.load(file) # Retrieve models and selected option from the configuration models = config_data.get('Models', {}).get('models', None) selected_option = config_data.get('Settings', {}).get('selected_ai_option', None) # Ensure models is not None if models is None: raise ValueError("Models configuration is missing or incorrectly set in the configuration file.") # Initialize news_bot config_path = os.path.join(base_directory, 'config', 'openai.yaml') # -------- Debug statement … -
how to display data from two Django model classes in a template by id?
I am new in django. I am try to make my first app called blog.This application contains two classes (with articles) finnews and fingram, I need to display all articles finnews and fingram on one template (I got it). I also need that from this template, the user clicks on the title of the article to go to the template with the full text of the article - and here with this I have problems. I'm reading the documentation and can't figure out how to fix the problem. Clicking on the finnews header results in a 404 error, and clicking on the fingram header results in a 'blogid() got an unexpected keyword argument 'id'' error. So far I'm reading the documentation and can't figure out how to fix it. urls.py for all project urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py for blog app def blogmain(request): all_fingrams = Fingram.objects.order_by('-id') all_finnewss = Finnews.objects.order_by('-id') data = { 'all_fingrams': all_fingrams, 'all_finnewss': all_finnewss, } return render(request,'blog/financial-news.html', data) def blogid(request): single_fingram = get_object_or_404(Fingram, pk=id) single_finnews = get_object_or_404(Finnews, pk=id) data = { 'single_fingram' : single_fingram, 'single_finnews' : single_finnews, } return render(request,'blog/financialarticle.html', data) urls.py for blog app urlpatterns = [ path('', views.blogmain, name='blogmain'), … -
Which Python library should I use to convert my HTML along with css into Docx file using Django?
I'm developing a Django app where users submit a NOC form. The information is stored in the database, and based on that data, I need to generate a visa application that should be downloadable in .docx format. I tried using pypandoc to convert HTML into DOCX, but the problem is that the CSS is not rendering in the output document. Here is my current approach: #Code for Generating the DOCX File: @login_required(login_url='login') def generate_noc_doc(request, noc_id): print("Generating NOC DOCX") # Fetch the NOC instance noc_instance = get_object_or_404(NOC, id=noc_id) grade = noc_instance.grade.strip() if noc_instance.grade else "" # Fetch employee ID and visa type from NOC instance employee_id = noc_instance.applicant_id visa_type = noc_instance.type_noc.lower() additional_travelers = noc_instance.additional_travelers.all() # Prepare family members text if there are additional travelers if noc_instance.no_of_travelers > 0: travelers_list = [f"({traveler.relationship_with_traveler}) named {traveler.additional_passport_name} bearing Passport No. {traveler.additional_passport_no}" for traveler in additional_travelers] family_members_text = ", ".join(travelers_list) else: family_members_text = "" # Fetch employee data based on applicant_id employee = Employees.objects.get(EmployeeID=noc_instance.applicant_id) # Determine pronouns based on gender if employee.Gender.lower() == 'male': pronoun_subjectC = 'He' pronoun_subjectS = 'he' pronoun_object = 'him' pronoun_possessive = 'his' elif employee.Gender.lower() == 'female': pronoun_subjectC = 'She' pronoun_subjectS = 'she' pronoun_object = 'her' pronoun_possessive = 'her' else: pronoun_subjectC = 'They' … -
Self-referential relationship or Different Model (Django referral system)
The first example implements Self-referential relationship: class User(models.Model): username = models.CharField(max_length=50, null=True) referrer = models.ForeignKey("self", related_name='referrals', null=True, blank=True) referrer_bonus = models.IntegerField(default=0) referral_bonus = models.IntegerField(default=0) The second option uses an intermediate model: class Referral(models.Model): referrer = models.ForeignKey(User, on_delete=models.PROTECT, related_name="referrals") referral = models.OneToOneField(User, on_delete=models.PROTECT, related_name='referral') referrer_bonus = models.IntegerField(default=0) referral_bonus = models.IntegerField(default=0) The question is that one referral can have one referrer. But a referrer can have many referrals. What approach will be better if I need to use anotation to calculate the total bonus and the number of referrals. And which option will be optimal for performance? -
Updating Request Headers in Django Middleware
Before I start complaining about my problem, I have to admit, that I'm not sure if my approach is the best way to handle my problem. I'm using Nuxt as my Frontend and I want to check/renew the JWT access token if it is expired, but the refresh token is still valid. Hey, I'm currently trying to write a middleware in Django, which is responsible for updating the JWT access token. However, the test says that I'm not authorized, even though I've updated the header. class JWTRefreshMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request: HttpRequest): if request.headers.get("Authorization"): try: AccessToken( str(request.headers.get("Authorization")).split(" ")[1], verify=True ) except TokenError: if refresh_token_cookie := request.COOKIES.get("refresh_token"): try: refresh_token = RefreshToken(refresh_token_cookie, verify=True) user = CustomUser.objects.get( id=refresh_token.payload.get("user_id") ) new_access_token = str(AccessToken.for_user(user)) request.META["HTTP_AUTHORIZATION"] = ( f"Bearer {new_access_token}" ) except TokenError: pass response: HttpResponse = self.get_response(request) return response The endpoint which I'm trying to call looks like the following: from ninja_jwt.authentication import JWTAuth router = Router() @router.get("/profile", response={200: UserProfileResponse}, auth=JWTAuth()) def get_user_profile(request): # Some Code I've also tried to override request.headers["Authorization"], but... TypeError: 'HttpHeaders' object does not support item assignment -
Elegant way to add a list view test case in drf
I have one concern in writing the test code for list view. For DRF's list view, it responds to multiple data. What should I do if I assume that the response.data object is a model with many fields? response.data --> [{"id": 1, "field1": "xxx", "field2": "yyy"....}, {"id": 2, ...}, ...] Too much input is required to compare with static data when a returns a lot of field data. def test_xx(self): self.assertEqual(response.data, [{"id": 1, "field1": "xxx", ..., "field12": "ddd", ...}, ...]) Currently, the way I came up with is as follows. I created an example model called Dog. class Dog(models.Model): ... hungry = models.BooleanField(default=False) hurt = models.BooleanField(default=False) As an example, let's say there is a class called Dog and there is logic in View to get a list of hungry dogs. I'm going to make a test about the logic of get a list of hungry dogs. class ... def test_dog_hungry_list(self): response = client.get("/api/dog/hungry/") expected_response = Dog.objects.filter(hungry=True) self.assertEqual(response.data, expected_response) The two values that I want to compare with assertEqual, response and expected_response, are of different types. response --> Response expected_response --> Queryset In the case of response.data, Serializer is applied, so when it's in dict form, I want to compare it … -
Prepend Text in Crispy Forms - Django
I have a form that works generally as expected, but I am trying to prepend some text on one of the fields to make it more user-friendly. In this case, all entries in the "RFP Control Number" field should start with "RFP-" so I want to use crispy forms to prepend that text. I have followed the setup in the crispy forms documentation to the best of my ability, but am not having any luck getting the prepended text to show up. Any ideas? The documentation is linked below: https://django-crispy-forms.readthedocs.io/en/latest/layouts.html and a simplified version of my form is included below as well. Greatly appreciate any help! Please let me know if you have any questions, or if any additional information is needed. class ProposalForm(forms.ModelForm): class Meta: model = Proposal fields = [ 'organization', 'rfp_control_number', ] def __init__(self, *args, **kwargs): super(ProposalForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.layout = Layout( 'organization', PrependedText('rfp_control_number', 'RFP-'), Submit('submit', 'Submit', css_class='btn btn-primary'), ) I tried the few different syntaxes listed in the documentation website included in my post to no avail. I have looked online for articles and watched YouTube videos about Crispy Forms, but I have not found anything that covers this directly. … -
(fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples
I created this model below and I was working fine for almost the whole week. Closed the server and restarted it again and it threw me the (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples error. Used django documentation exactly, still no solution. `class Inspection(models.Model): RESULT_CHOICES = [ ("PR" "Passed"), ("PR" "Passed with minor Defects"), ("PR" "Passed with major Defects"), ("FR" "Failed due to minor Defects"), ("FR" "Failed due to major Defects"), ("FR" "Failed"), ] vin_number = models.ForeignKey(Vin, on_delete=models.CASCADE, related_name='inspections') inspection_number = models.CharField(max_length=20) year = models.CharField(max_length=4) inspection_result = models.CharField(max_length=30, choices=RESULT_CHOICES) ag_rating = models.CharField(max_length=30) inspection_date = models.DateField() link_to_results = models.CharField(max_length=200) def __str__(self): return self.inspection_number` I tried to: YEAR_IN_SCHOOL_CHOICES = { "FR": "Freshman", "SO": "Sophomore", "JR": "Junior", "SR": "Senior", "GR": "Graduate", } but still didn't work. Can even migrate due to the error -
How to make function, after specific time/minute the status of post change status using django?
i want to create a function in views or html file after 15 seconds , the status of post from pending to activa using django? tried to look for solutions but didnt understand. Also looked to ai to see what type of answer gave , but wanted to use traditional help to understand better -
How to run react code to render a webpage and display to user?
Say I have some generated react code that I want to display to the user for them to click through and comment on. The user isn't the one coding the website, I just want to show them how the generated website looks so they can make some comments on it. An example of the generated code could look like this: import { useState } from 'react'; import { Card, CardHeader, CardContent } from '@/components/ui/card'; import { MailIcon, GithubIcon, LinkedinIcon } from 'lucide-react'; export default function Website() { const [activeTab, setActiveTab] = useState('about'); return ( <div className="min-h-screen bg-gray-100 p-8"> {/* Navigation */} <nav className="bg-white shadow-lg rounded-lg p-4 mb-8"> <div className="flex justify-between items-center"> <h1 className="text-2xl font-bold text-blue-600">My Website</h1> <div className="space-x-4"> <button onClick={() => setActiveTab('about')} className={`px-4 py-2 rounded ${activeTab === 'about' ? 'bg-blue-600 text-white' : 'text-gray-600'}`} > About </button> <button onClick={() => setActiveTab('projects')} className={`px-4 py-2 rounded ${activeTab === 'projects' ? 'bg-blue-600 text-white' : 'text-gray-600'}`} > Projects </button> <button onClick={() => setActiveTab('contact')} className={`px-4 py-2 rounded ${activeTab === 'contact' ? 'bg-blue-600 text-white' : 'text-gray-600'}`} > Contact </button> </div> </div> </nav> {/* Main Content */} <div className="max-w-4xl mx-auto"> {activeTab === 'about' && ( <Card> <CardHeader> <h2 className="text-2xl font-bold">About Me</h2> </CardHeader> <CardContent> <p className="text-gray-600"> Hello! I'm a … -
How to skip django DeleteModel operation
I have deleted a model, Django creates a DeleteModel operation that I'd like to skip because i don't want to drop the table yet, but i also don't want to keep the model around. How can i skip dropping the table in this case but still delete the model? I have tried commenting out the operation in the migration file but the next time you run makemigrations command the operation is recreated. -
Handling Errors in Django Test Cases
I am currently writing test cases using Django and would like to improve the way we handle errors, particularly distinguishing between errors that arise from the test cases themselves and those caused by the user's code. Context: Let’s say a user writes a function to fetch and increment the likes count of a post: def fetch_post(request, post_id): try: post = Post.objects.get(id=post_id) except Post.DoesNotExist: raise Http404("Post not found") post.likes += 1 post.save() return HttpResponse("Post liked") Here’s the test case for that function: from django.test import TestCase from project_app.models import Post from django.urls import reverse from django.http import Http404 class FetchPostViewTests(TestCase): def setUp(self): self.post = Post.objects.create(title="Sample Post") def assertLikesIncrementedByOne(self, initial_likes, updated_post): if updated_post.likes != initial_likes + 1: raise AssertionError(f'Error: "Likes cannot be incremented by {updated_post.likes - initial_likes}"') def test_fetch_post_increments_likes(self): initial_likes = self.post.likes response = self.client.get(reverse('fetch_post', args=[self.post.id])) updated_post = Post.objects.get(id=self.post.id) self.assertLikesIncrementedByOne(initial_likes, updated_post) self.assertEqual(response.content.decode(), "Post liked") def test_fetch_post_not_found(self): response = self.client.get(reverse('fetch_post', args=[9999])) self.assertEqual(response.status_code, 404) Scenario: Now, if a user accidentally modifies the code to increment the likes by 2 instead of 1 and didn't save the post object. # Wrong code that will fail the test case def fetch_post(request, post_id): try: # used filter() method instead of get() method post = Post.objects.filter(id=post_id) except Post.DoesNotExist: … -
AxesBackend requires a request as an argument to authenticate
I need to add a restriction on account login attempts to my django site, I found the popular django-axes library, followed the documentation and code examples, but when I try to log in to my account (whether the password is correct or not) I get the error AxesBackend requires a request as an argument to authenticate even though my code follows the instructions exactly and I'm passing the request. Here is all the code that is somehow related to this: settings.py INSTALLED_APPS = [ ... 'axes', ] MIDDLEWARE = [ ... 'axes.middleware.AxesMiddleware', ] AXES_FAILURE_LIMIT = 4 AXES_RESET_ON_SUCCESS = True AXES_COOLOFF_TIME = 1 AUTHENTICATION_BACKENDS = [ 'axes.backends.AxesBackend', # Axes must be first 'django.contrib.auth.backends.ModelBackend', ] AUTH_USER_MODEL = "users.User" LOGIN_URL = "/user/login/" views.py from django.contrib import auth, messages def login(request): if request.method == "POST": form = UserLoginForm(data=request.POST) if form.is_valid(): username = request.POST["username"] password = request.POST["password"] user = auth.authenticate(request=request, username=username, password=password) if user: auth.login(request, user) redirect_page = request.POST.get("next", None) if redirect_page and redirect_page != reverse("user:logout"): return HttpResponseRedirect(request.POST.get("next")) return HttpResponseRedirect(reverse("main:main_page")) else: form = UserLoginForm() context = {"title": "Вход", "form": form} return render(request, "users/login.html", context) Django==5.0.4 django-axes==6.5.2 I would be very grateful for your help! Indicated above. Here is the exact output in the console that … -
error: PermissionError(13, 'Access is denied', None, 5, None)
I have this error while working with celery [2024-10-06 14:38:15,464: ERROR/SpawnPoolWorker-3] Pool process <billiard.pool.Worker object at 0x0000016C0BBF5A00> error: PermissionError(13, 'Access is denied', None, 5, None) Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 473, in receive ready, req = _receive(1.0) ^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 445, in _recv return True, loads(get_payload()) ^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\queues.py", line 394, in get_payload with self._rlock: File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\synchronize.py", line 115, in __enter__ return self._semlock.__enter__() ^^^^^^^^^^^^^^^^^^^^^^^^^ PermissionError: [WinError 5] Access is denied During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 351, in workloop req = wait_for_job() ^^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 480, in receive raise SystemExit(EX_FAILURE) SystemExit: 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 292, in __call__ sys.exit(self.workloop(pid=pid)) ^^^^^^^^^^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 396, in workloop self._ensure_messages_consumed(completed=completed) File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 406, in _ensure_messages_consumed if self.on_ready_counter.value >= completed: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<string>", line 3, in getvalue PermissionError: [WinError 5] Access is denied [2024-10-06 14:38:15,464: ERROR/SpawnPoolWorker-3] Pool process <billiard.pool.Worker object at 0x0000016C0BBF5A00> error: PermissionError(13, 'Access is denied', None, 5, None) Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 473, in receive ready, req = _receive(1.0) ^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 445, in _recv return …