Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is Django Machina query altered with nonexistent table name
I have a django-machina forum where I can't delete posts because of an error where the delete process apparently looks for a table "forum_conversation_forumpost" This is not a table name in the package. There is a table "forum_conversation_post." I have another test forum installed and I am not getting this error when I delete a post. While I have overridden some sections of the standard machina install in the site with a problem, I still get the error when I revert back to the standard install. I can't figure out where the query is being overridden or why. Error: ProgrammingError at /forum/moderation/queue/31/disapprove/ (1146, "Table 'site.forum_conversation_forumpost' doesn't exist") Request Method: POST Request URL: http://localhost:8000/forum/moderation/queue/31/disapprove/ Django Version: 3.2.23 Exception Type: ProgrammingError Exception Value: (1146, "Table 'site.forum_conversation_forumpost' doesn't exist") Exception Location: /Users/user1/.local/share/virtualenvs/labororg-RtI6P7d4/lib/python3.9/site-packages/MySQLdb/connections.py, line 265, in query Python Executable: /Users/user1/.local/share/virtualenvs/labororg-RtI6P7d4/bin/python Python Version: 3.9.6 Python Path: ['/Users/user1/Documents/labororg', '/Users/user1/.pyenv/versions/3.9.6/lib/python39.zip', '/Users/user1/.pyenv/versions/3.9.6/lib/python3.9', '/Users/user1/.pyenv/versions/3.9.6/lib/python3.9/lib-dynload', '/Users/user1/.local/share/virtualenvs/labororg-RtI6P7d4/lib/python3.9/site-packages'] Server time: Sat, 04 Jan 2025 18:45:46 +0000 Traceback: Environment: Request Method: POST Request URL: http://localhost:8000/forum/moderation/queue/31/disapprove/ Django Version: 3.2.23 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'haystack', 'mptt', 'widget_tweaks', 'ckeditor', 'ckeditor_uploader', 'compressor', 'crispy_forms', 'crispy_bootstrap4', 'allauth', 'allauth.account', 'allauth.socialaccount', 'captcha', 'machina', 'machina.apps.forum_conversation.forum_attachments', 'machina.apps.forum_conversation.forum_polls', 'machina.apps.forum_feeds', 'machina.apps.forum_moderation', 'machina.apps.forum_search', 'machina.apps.forum_tracking', 'machina.apps.forum_member', 'machina.apps.forum_permission', 'apps.forum', 'apps.forum_conversation', … -
Having issues getting django-simple-captcha to work on my Contact Us page
I'm having trouble getting the captcha to work on my Contact Us page in my website. I've followed the instructions shown in the docs but keep getting errors. Can anyone help? Here's my forms.py: # main/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User # For the Captcha from captcha.fields import CaptchaField # For the Contact Us page from django.core.validators import EmailValidator class CustomUserCreationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self): user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data["email"] user.save() return user class ContactForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) # phone = forms.CharField(max_length=15) # subject = forms.CharField(max_length=100) message = forms.CharField(widget=forms.Textarea) captcha = CaptchaField() Here is my urls.py: # main/urls.py from django.contrib import admin from django.urls import path, include from main.views import dashboard, register, about, blog app_name = 'main' urlpatterns = [ path('blog/', include('blog.urls')), path('admin/', admin.site.urls), path('projects/', include('projects.urls')), path('captcha/', include('captcha.urls')), ] Here is my views.py: # main/views.py from django.contrib.auth import login as auth_login from django.shortcuts import redirect, render from django.urls import reverse from main.forms import CustomUserCreationForm from captcha.fields import CaptchaField from django.core.mail import EmailMessage from main.forms import ContactForm from django.conf import settings from django.http import HttpResponse # Create … -
How can I use FilteredSelectMultiple widget in a django custom form?
I'm trying to use Django's FilteredSelectMultiple widget in a custom form. This widget is used in the Django admin for fields like Permissions (e.g., http://127.0.0.1:8000/admin/auth/group/add/), where there are two boxes: one for available options and another for selected options. However, when I try to use it, it only renders as a regular multi-select box. That’s my current code: View: class SupervisorUpdateView(modal.BaseModalUpdateView): permission_required = 'management.change_supervisor' template_name = 'management/supervisors/update_supervisor.html' model = models.Supervisor form_class = forms.SupervisorForm success_message = 'Supervisor updated' Form: from django import forms from django.contrib.admin.widgets import FilteredSelectMultiple class SupervisorForm(BSModalModelForm): class Meta: model = models.Supervisor fields = '__all__' labels = {'supervisor': 'Supervisor', 'technicians': 'Technicians'} widgets = { 'supervisor': forms.HiddenInput(), 'technicians': FilteredSelectMultiple('Technicians', is_stacked=False), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['technicians'].queryset = get_agparts_users() Template: {% extends 'core/_modal_form.html' %} {% block header %}Update Supervisor{% endblock header %} {% block button %} <button class="btn btn-primary submit-btn">Update</button> {% endblock button %} Despite this, the widget only renders as a basic multi-select dropdown without the dual-box UI. What am I missing? How can I properly use FilteredSelectMultiple outside of the Django admin? -
CERT_PATH points to the wrong directory even though I set it correctly in my Django project
I'm working on a Django project and trying to configure SSL with the certificate. I have set the CERT_PATH variable like this in my code: import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent CERT_PATH = os.path.join(BASE_DIR, "certs", "DigiCertGlobalRootG2.crt.pem") However, when the code runs, it is looking for the certificate in the wrong directory: in core/certs/ instead of certs/. aParent ├── certs │ └── DigiCertGlobalRootCA.crt.pem └── core └── livenews └── services.py -
SimpleJWT: Re-apply Blacklist Token Migration: "Table 'token_blacklist_blacklistedtoken' doesn't exist"
I have, rather sillily, run "python manage.py migrate" when I added Django SimpleJWT's token blacklist functionality to my program. This means whenever I try to generate tokens or use any functionality, I run into the error... (1146, "Table 'token_blacklist_outstandingtoken' doesn't exist") I have tried unapplying and redoing the migrations for "token_blacklist", but I get the same error... python manage.py migrate token_blacklist zero Operations to perform: Unapply all migrations: token_blacklist Running migrations: Rendering model states... DONE Unapplying token_blacklist.0012_alter_outstandingtoken_user... OK Unapplying token_blacklist.0011_linearizes_history... OK Unapplying token_blacklist.0010_fix_migrate_to_bigautofield... OK Unapplying token_blacklist.0008_migrate_to_bigautofield...Traceback (most recent call last): return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fiona\AppData\Roaming\Python\Python312\site-packages\django\db\backends\mysql\base.py", line 76, in execute return self.cursor.execute(query, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\MySQLdb\cursors.py", line 179, in execute res = self._query(mogrified_query) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\MySQLdb\cursors.py", line 330, in _query db.query(q) File "C:\Python312\Lib\site-packages\MySQLdb\connections.py", line 265, in query _mysql.connection.query(self, query) MySQLdb.ProgrammingError: (1146, "Table 'token_blacklist_blacklistedtoken' doesn't exist") ... I have tried uninstalling and re-installing the package, djangorestframework-simplejwt, but that also hasn't worked. How do I resolve this? Thank you for any help -
Hi, How to make sure that only tags translated in a given language are displayed on the page translated in that language?
class Insight(Page): .... tags = ClusterTaggableManager(through='insight.InsightTag', blank = True) @register_snippet class InsightTag( TranslatableMixin, TaggedItemBase ): # panels = [FieldPanel("name")] free_tagging = False content_object = ParentalKey( to='insight.Insight', related_name='tagged_items', on_delete=models.CASCADE ) def get_preview_template(self, request, mode_name): return "base.html" def get_preview_context(self, request, mode_name): return {"insighttag": self.body} class Meta(TranslatableMixin.Meta): verbose_name = "insight Tag" verbose_name_plural = "insight Tags" -
Images not displaying in Django webapp deployed on Vercel
I've deploy my app successfully locally, but when deployed on vercel I can't get the images to display. vercel.json: { "builds":[{ "src":"XPense/wsgi.py", "use":"@vercel/python", "config":{ "maxLambdaSize":"15mb", "runtime":"python3.10" } }], "routes":[ { "src":"/(.*)", "dest":"XPense/wsgi.py" } ] } settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' problem child: <div id="profile-picture-selection" class="grid grid-cols-3 gap-4"> {% for image in profile_pictures %} <input type="radio" name="profile_picture" id="{{image}}" value="{{image}}" style="display: none;"> <img src="/media/profile_pictures/{{image}}" alt="{{image}}" class="profile-image-preview rounded-lg cursor-pointer transition transform hover:scale-110" onclick="selectImage('{{image}}', this)"> {% endfor %} </div> The images are located XPense/media/profile_pictures/ with XPense being root. I've tried relocating the images to a public folder and using <img src="/{{image}}"... but noting worked so far, I've tried hard coding an image url and that doesn't work either so yeah... Help please! The website is deployed and you can check it out, if you go to register a new user text I've tried relocating the images to a public folder and using <img src="/{{image}}"... but noting worked so far, I've tried hard coding an image url and that doesn't work either so yeah... Help please! -
django multi-level template extending
I have 3 templates in my code. first one is the base.html, second one is toolbar.html and the third is toolbar_content.html. so I wanted to include the toolbar inside base and use the third inside content blocks by extending base.html. here is an example: my base.html: <div class="d-flex flex-column flex-column-fluid"> {% include 'components/toolbar.html' %} </div my toolbar: <div class="d-flex align-items-center gap-2 gap-lg-3"> {% block toolbar_content %}{% endblock %} </div> and my toolbar content: {% extends 'base.html' %} {% block toolbar_content %} <a href="#" class="btn btn-sm fw-bold btn-primary" data-bs-toggle="modal" data-bs-target="#concept_create">Create New Concept</a> {% endblock %} I both tried to test this example and also I tried to extend the toolbar page instead of base in my toolbar content template but its not working. toolbar is successfully included in base but the content is not showing. could you help me work this out? -
Unable to get form data in database and getting type object 'UserRegister' has no attribute 'USERNAME_FIELD' error
Form.py from django import forms from .models import UserRegister from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError form.py from django import forms from .models import UserRegister from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError class UserRegisterForm(UserCreationForm): username = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'input-group'})) email = forms.EmailField(max_length=70, required=True, widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'input-group'})) password1 = forms.CharField(max_length=128, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'input-group', 'id': 'password'})) password2 = forms.CharField(max_length=128, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password', 'class': 'input-group', 'id': 'password'})) class Meta: model = UserRegister fields = ['username', 'email', 'password1', 'password2'] def clean_email(self): email = self.cleaned_data.get('email') if UserRegister.objects.filter(email=email).exists(): raise ValidationError('This email address is already in use.') return email def clean_username(self): username = self.cleaned_data.get('username') if UserRegister.objects.filter(username=username).exists(): raise ValidationError('This username is already in use.') return username def clean(self): cleaned_data = super().clean() password1 = cleaned_data.get('password1') password2 = cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError("Passwords do not match.") return cleaned_data model.py from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth.hashers import make_password class UserRegister(models.Model): username= models.CharField(max_length=50,unique=True) email = models.EmailField(unique=True,max_length=70) password = models.CharField(max_length=128) class Meta: verbose_name = "User Register" verbose_name_plural = "User Register" def save(self,*args,**kwargs): self.password = make_password(self.password) super(UserRegister,self).save(*args,**kwargs) def __str__(self): return self.username views.py Create your views here. from django.shortcuts import render from django.http import HttpResponseRedirect ,Http404 … -
django.db.utils.OperationalError: no such column: home_student.schoolYear
models.py ''' class Person(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) othernames = models.CharField(max_length=40) dateOfBirth = models.DateField() gender = models.CharField(max_length=20) birthGender = models.CharField(max_length=20) email = models.EmailField(max_length=100) class Student(Person): studentId = models.IntegerField() admissionDate = models.DateField() enrolmentStatus = models.BooleanField() studentExamCode = models.IntegerField() schoolYear = models.IntegerField() ''' forms.py ''' class studentF(ModelForm): class Meta: model = Student fields = ['firstname', 'lastname', 'othernames', 'dateOfBirth', 'gender', 'birthGender', 'email', 'studentId', 'admissionDate', 'enrolmentStatus', 'studentExamCode', 'schoolYear'] ''' I am getting the error in the title, how do I fix it? -
How to reference an inner class or attribute before it is fully defined?
I have a scenario where a class contains an inner class, and I want to reference that inner class (or its attributes) within the outer class. Here’s a concrete example using Django: from django.db import models from django.utils.translation import gettext_lazy as _ class DummyModel(models.Model): class StatusChoices(models.TextChoices): ACTIVE = "active", _("Active") INACTIVE = "inactive", _("Inactive") status = models.CharField( max_length=15, choices=StatusChoices.choices, verbose_name=_("Status"), help_text=_("Current status of the model."), default=StatusChoices.ACTIVE, null=False, blank=False, ) class Meta: verbose_name = _("Dummy Model") verbose_name_plural = _("Dummy Models") constraints = [ models.CheckConstraint( name="%(app_label)s_%(class)s_status_valid", check=models.Q(status__in=[choice.value for choice in DummyModel.StatusChoices]), ) ] In this case, the constraints list in the Meta class tries to reference DummyModel.StatusChoices. However, at the time this reference is evaluated, DummyModel is not fully defined, leading to an error (neither StatusChoices is accessible in that line). I would like to solve this without significantly altering the structure of the code—StatusChoices must remain defined inside DummyModel. How can I resolve this issue while keeping the inner class and its attributes accessible as intended? -
show chekbox in django marked when instantiating a form
I have the following code: view.py def actualizar_rutina(request, id_rutina): if not request.user.es_entrenador: messages.error(request, 'Usted no tiene permisos para acceder a esta pagina') return redirect('mostrar_rutina') if request.method == 'GET': rutina = get_object_or_404(Rutina, id=id_rutina) rutinaform = RutinaForm(instance=rutina) contexto = { "rutinaform": rutinaform, } return render(request, 'core/crear_rutina.html', contexto) else: return HttpResponse('no se pudo actualizar') form.py class RutinaForm(forms.ModelForm): class Meta: model = Rutina exclude = ('dias_descanso',) dias_entrenamiento = forms.MultipleChoiceField( choices=DIAS_SEMANA, widget=forms.CheckboxSelectMultiple(), required=False ) What happens is that when I instantiate the form that shows the html, the boxes (chekbox) are not checked, they remain blank and what I want is for only those boxes to be checked that are supposed to be instantiated with the instance that the user send Keep in mind that the training day it saves is something like this: training_days=['MON','TUE'] etc and WEEK_DAYS = [('MON', 'Monday'),('TUE', 'Tuesday'), ('WED', 'Wednesday'),('THU', 'Thursday'),('FRI', 'Friday'),('SAT', 'Saturday'),('SUN', 'Sunday'),] How could I achieve that?? thank you What I want is for only those boxes to be checked that are supposed to be instantiated with the instance that the user sends. -
Do I need public S3 bucket for Zappa to work?
I followed this and this tutorials on hosting assets on the bucket generated by Zappa. Following this question I also applied the bucket policy and used ACLs enabled. However, if bucket public access is blocked (default S3 behaviour), then I am not able to access them (for example, I am not able to get CSS for the /dev/admin page). As soon as I make the bucket public, I can retrieve them. Question: is this expected by design? If so, I am concerned about the security implications of having a public S3 bucket. -
Facebook Login - Feature Unavailable
I am trying to implement Facebook login for my application. It was working well in development mode, but when I try to switch to live mode I see this message: Feature Unavailable Facebook Login is currently unavailable for this app, since we are updating additional details for this app. Please try again later. here is the exact error I get I do not have any required actions in developer console. I have searched for an answer, I have already set advanced access to email and public profile, and I got advanced access to other permissions as well. Business verification is complete and I have verified my Business as a tech provider as well. Here is the code that handles the Facebook login (I am using Django framework): def facebook_login(request): facebook_auth_url = "https://www.facebook.com/v21.0/dialog/oauth" if "test" in request.get_full_path(): redirect_uri = request.build_absolute_uri('/test/home/facebook_login/facebook_callback/') redirect_uri = "http://localhost:8000/home/facebook_login/facebook_callback/" else: redirect_uri = request.build_absolute_uri('/home/facebook_login/facebook_callback/') scopes = "pages_show_list,business_management,read_insights,ads_read,pages_read_engagement,ads_management" state = generate_state() request.session['oauth_state'] = state params = { 'client_id': settings.META_APP_ID, 'redirect_uri': redirect_uri, 'scope': scopes, 'response_type': 'code', 'state': state, } auth_url = f"{facebook_auth_url}?{urlencode(params)}" return JsonResponse({'authorization_url': auth_url}) def facebook_callback(request): error = request.GET.get('error') if error == 'access_denied': prefix = 'test/' if os.getenv('PROD') == 'blue' else '' cancel_redirect_url = ( "http://localhost/" + prefix + … -
Django's contrib auth + allauth's MFA - 2FA Setup
I added a feature called 2FA to my django project using django-allauth[mfa]. I also setuped the social account login process using google. login form is from django.contrib.auth 2FA form is from allauth.mfa authentication/views.py - my custom django contrib auth view class CustomLoginView(LoginView): form_class = UserLoginForm template_name='authentication/login.html' redirect_authenticated_user=True mfa_enabled = False def dispatch(self, request, *args, **kwargs): if self.redirect_authenticated_user and self.request.user.is_authenticated: if self.mfa_enabled: return HttpResponseRedirect(resolve_url('account_login')) else: redirect_to = self.get_success_url() if redirect_to == self.request.path: raise ValueError( "Redirection loop for authenticated user detected. Check that " "your LOGIN_REDIRECT_URL doesn't point to a login page." ) return HttpResponseRedirect(redirect_to) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): user = form.get_user() if self.has_mfa(user): self.mfa_enabled = True print("2FA enabled") else: auth_login(self.request, user) return super().form_valid(form) def has_mfa(self, user): return is_mfa_enabled(user) and this code is not working at all. After login successed, it redirected to homepage. I want to redirect to 2FA form if user account is 2fa activated. path('accounts/2fa/authenticate/', views.Custom2FAAuthenticateView.as_view(), name='account_login'), this is my customized 2FA auth form. It worked with social account like google, it redirect to 2FA form if account is 2FA activated. this is my 2FA auth customized view file # 2FA authentication view for social login class Custom2FAAuthenticateView(Base2FAAuthenticateView): template_name = "authentication/mfa/authenticate.html" I tried many ways. when … -
How to make Django Manager and Model's interactions follow the Open/Closed Principle?
I am designing models for my Django App and am concerned with decoupling the caller's logic from the model's implementation, so that future changes to the model itself do not require changes downstream in the codebase. In short adhering to the Open/Closed Principle (OCP). I am wondering what is a best practice to implement this while leveraging Django's framework best. Conceptually, I believe it would make sense to do the following: from django.db import models class FooManager(models.Manager): def is_active(self): return self.filter(is_active=True) class Foo(models.Model): _bar = models.CharField(max_length=100, db_column="bar") is_active = models.BooleanField(default=True) objects = FooManager() @property def bar(self): return self._bar @bar.setter def bar(self, value): if not self._bar: self._bar = value else: #some setter logic pass Custom Manager for Query Logic For each model, a custom Manager is defined and is responsible for handling all sorts of filtering logic on the model. E.g. instead of calling Foo.objects.filter(is_active=True), caller would call Foo.objects.is_active(). In the future, if the implementation logic of is_active changes, the caller won't need to change it's logic, keeping things OCP. Encapsulation of model fields For each field in a model, @property are defined for getters and setters allowing to change the underlying model fields. Minimal coupling Coupling is only kept on … -
Freeradius server won't allow multiple aaa users with same auth ip
So I have been assigned to the freeradius problem, I can see the tenants in proxy.conf. Problem is arising when I am trying to register multple users from frontend with same Auth IP. It will accept same accounting IP but not same Auth IP. How can i configure so that it can allow multiple user types from same Auth IP? I tried exploring queries.conf, proxy.conf, clients.conf and django backend logic thats creating the AAA users. Nowhere I found a specific logic restricting the duplicate IP for same users. I was told its some limitation of the server. Was looking for ways to reconfigure or bypass to solve the problem. -
Django - HTML table issue (probably with for loop)
I want to use dataTables in my HTML template in Django. .html file: <!DOCTYPE html> <html lang="en"> <head> <title>FPL projections - Team list</title> <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.css"> <script type="text/javascript" src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.js"></script> <style> section{ width: 70%; margin: 30px auto; } #teamTable th, #teamTable td{ border: 1px solid #ccc; text-align: left; } #teamTable thead { background: #f2f2f2; } </style> </head> <body> <section> {% extends "fantasy_menu.html" %} {% block content %} <h1>Team List</h1> <table id="teamTable" width="100%"> <thead> <tr> <th><strong>Name</strong></th> <th>Home for</th> <th>Home ag</th> <th>Away for</th> <th>Away ag</th> <th>opp1</th> <th>opp2</th> <th>opp3</th> <th>opp4</th> <th>opp5</th> </tr> </thead> <tbody> {% for team in team_list %} <tr> <td><a href="{% url 'fantasy:team' team.ref_id %}"><strong>{{team.name}}</strong></a> ({{team.ref_id}}) </td> <td>{{team.avg_goal_for_home}}</td> <td>{{team.avg_goal_ag_home}}</td> <td>{{team.avg_goal_for_away}}</td> <td>{{team.avg_goal_ag_away}}</td> <td>{{team.opp1}}</td> <td>{{team.opp2}}</td> <td>{{team.opp3}}</td> <td>{{team.opp4}}</td> <td>{{team.opp5}}</td> </tr> {% endfor %} </tbody> </table> <script> $(document).ready( function () { $('#teamTable').DataTable(); } ); </script> <br /> <br /> <p><a href="{% url 'fantasy:player_list' %}">Player projections</a></p> <p><a href="{% url 'fantasy:index' %}">Back to main page</a></p> {% endblock %} {% block footer %} {% endblock %} </section> </body> </html> The JavaScript (that would affect the headers of the table) doesn't seem to run because the headers are not clickable (for sorting for instance). Current weblink of what's being displayed (before it gets fixed...): http://texouze.pythonanywhere.com/fantasy/teams/ When … -
What is a GenericForeignKey?
I have read Django's documentation on GenericForeignKeys and found it to be extremely confusing. I don't understand what the variables I am giving it is, and therfore I have no idea how it works, and therefore I have no idea what it is - and everything I see only makes me more confused, because I still can't find anything clearly explaining, at its root, what is it and how does it works. Can someone please start from the beginning and explain what a GenericForeignKey is, and how it works? -
How to dynamically generate and execute unit tests for multiple programming languages as strings?
I am working on a system where solutions to problems are validated using predefined unit test cases. The system supports multiple programming languages, and the generated test cases need to be converted into strings for execution by an API. The Problem: To test submitted solutions, I need to dynamically generate unit test cases for each programming language. The generated tests should: Include predefined base test cases for each problem (e.g., validating a palindrome function). Allow dynamic addition of custom test cases (e.g., user-defined edge cases). The generated tests must then be converted to a string and sent to Judge0 for execution. Current Approach: For Python: I use unittest to define base test cases in a file (e.g., test_palindrome.py). Custom test cases are dynamically added as new test methods. Both base and custom test cases are combined into a single string. The following code will already be existing with the is_palindrome.py file but new custom test cases will need to be added on. import unittest class TestPalindrome(unittest.TestCase): def test_base_cases(self): self.assertTrue(is_palindrome("radar")) self.assertFalse(is_palindrome("hello")) for example, for the given the user input: [ { "input": "'level'", "expected_output": "True" }, { "input": "'world'", "expected_output": "False" } ] I would need to generate a string of … -
Django migrations failing in Docker container after adding new model
I am running a Django project inside a Docker container, and I am facing an issue with migrations after adding a new model to models.py. When I try to apply the migrations, the system looks for the old migrations, but since I rebuild the app via Docker, those migrations are missing. When I try to force Django to ignore the old migrations, it attempts to create tables that already exist, and the process fails because of that. If I allow it to run the migrations normally, it tries to re-apply the migrations that have already been executed, which leads to errors. I need a way to: • Skip old migrations during the rebuild. • Ensure the new tables are created without conflicting with existing ones. • Prevent Django from reapplying migrations that are already done. How can I resolve this migration issue in Docker? Any help would be appreciated! Here’s what I have in my Dockerfile (now there is that problem with creating existing tables): FROM python:3.11 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . # Vyčistíme migrace a vytvoříme nové při buildu image RUN rm -rf api/migrations/* && \ touch api/migrations/__init__.py # Instalace netcat … -
Django: NameError with instance of model with Generic Foreign Field in, created by post_save signal
I have 3 models that I am dealing with here: SurveyQuestion, Update, and Notification. I use a post_save signal to create an instance of the Notification model whenever an instance of SurveyQuestion or Update was created. The Notification model has a GenericForeignKey which goes to whichever model created it. Inside the Notification model I try to use the ForeignKey to set __str__ as the title field of the instance of the model that created it. Like so: class Notification(models.Model): source_object = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() source = GenericForeignKey("source_object", "object_id") #more stuff def __str__(self): return f'{self.source.title} notification' I am able to create instances of SurveyQuestion and Update from the admin panel, which is then (supposed to be) creating an instance of Notification. However, when I query instances of Notification in the shell: from hotline.models import Notification notifications = Notification.objects.all() for notification in notifications: print (f"Notification object: {notification}") NoneType --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) 1 for notification in notifications: ----> 2 print (notification) File ~/ygzsey/hotline/models.py:27, in Notification.__str__(self) 26 def __str__(self): ---> 27 return f'{self.source.title} notification' AttributeError: 'NoneType' object has no attribute 'title' When I query instances of SurveyQuestion: from hotline.models import SurveyQuestion surveys = SurveyQuestion.objects.all() for survey in surveys: … -
How to allow the admin to change the uses's password in the Django admin panel?
I want to allow the admin to change any user's pasword, but th admin panel doesn't have that option anymore. I had to extend the abstract user class to add some fields to my users when they are created. I wanted to know what I can do to allow my admin users to change the user's passowrds. This is my User class: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): numero_de_empleado= models.CharField(max_length=100, unique=True, default="0", verbose_name="Puente") class Meta: permissions = [ ("view_retiro", "Ver retiro"), ("make_changes","Crear dotaciones y arqueos"), ("create_user","Crear un usuario"), ("view_all","Ver toda la información") ] And this is my admin.py from my user app: from django.contrib import admin from .models import User # Register your models here. admin.site.register(User) I am not an expert in django and i don't lnow why it's doing this, Thanks in advance. -
How to Disable Re-authentication in Django's allauth MFA's TOTP
I am trying to customize the reauthentication form of the mfa. I aslo customized the TOTP activate and deactivate form and it works, but now i am struggling to customize the reauthentication form with my defined route name in django. and is there any way to disable this reauth of the allauth mfa - 2fa settings/urls.py path('mfa/reauthenticate/', views.CustomReauthenticateView.as_view(), name='mfa_reauthenticate'), settings/views.py class CustomReauthenticateView(BaseReauthenticateView): template_name = "settings/mfa/reauthenticate.html" # Ensure the correct template is used def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['custom_message'] = 'This is a custom message for reauthentication.' return context def form_valid(self, form): response = super().form_valid(form) return response but it always rendering to localhost:8000/accounts/reauthenticate/?next=... and not my defined url. I also tried another way by customizing the allauth.account.decoders - reauthentication_required but not work Please someone help, that i want to redirect to my customize reauth form -
How to add dict to QuerySet
I have a result from the DB which I want to enriche with a row. A queryset is a dict right? So I created a new dict and wanted to merge those two. But it told me you cant merge a dict and QuerySet. How can this be done?