Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the correct way for implementing Hyphenopoly?
I'm having trouble implementing Hyphenopoly (https://github.com/mnater/Hyphenopoly) on a Django project. Sometimes it seems to work fine, sometimes not. Besides, on mobile browser the result are unpleasant, since hyphens appears in a pretty inconsistent fashion (or doesn't at all) on elements with italian language. Further, I cannot understand the documentation provided. My fault. Herein I report part of the directory structure of the project As you can see, and for what I understood, I loaded only few files from the original library, in order to hyphenate italian and english pieces of text (separated or mixed). The main language is still en, since I defined it in the lang attribute of the html element; for each element featuring italian content, I specified the language attribute accordingly (for mixed content, I used spans). In the head element of my base.html: <script src="{% static './hyphens/Hyphenopoly_Loader.js' %}"></script> <script src="{% static 'HyphenConfig.js' %}"></script> The HyphenConfig.js file, instead: $(document).ready(function() { var Hyphenopoly = { require: { 'en-us': 'ALL', 'en': 'ALL', 'it': 'ALL' }, paths: { patterndir: "./hyphens/patterns/", maindir: "./hyphens/" }, setup: { selectors: { '.hyphenate': { compound: "all", leftmin: 0, rightmin: 0, minWordLength: 4 } } } }; }); I also defined the hyphenate class in the … -
Django is unable to send email out even though conf is correct
Django is unable to send email out. But https://www.smtper.net/ was able to send a test email with same exact settings, user, pass. What do I need do more in django to send email out? settings.py ## #environment variables from .env. from dotenv import load_dotenv load_dotenv() NOREPLYEMAIL = os.getenv('NOREPLYEMAIL') NOREPLYEMAILPASS = os.getenv('NOREPLYEMAILPASS') ### Email config EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtppro.zoho.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = NOREPLYEMAIL EMAIL_HOST_PASSWORD = NOREPLYEMAILPASS DEFAULT_FROM_EMAIL = NOREPLYEMAIL view.py # using https://docs.djangoproject.com/en/5.0/topics/email/ @csrf_protect def test(request): testemail = EmailMessage( "Hello", #subject "Body goes here", #message body NOREPLYEMAIL, #from ["mygmail@gmail.com",], #to reply_to=[NOREPLYEMAIL], headers={"Message-ID": "test"}, ) testemail.send() -
Django - the date field in the data entered form is reset during editing
I made a model, form and views. I added some data via form. And then when i want editing, all fields are full but datefield is empty. I want to see date which i added before. But nothing. I use all ai solutions also javascript, jquery, but nothing. How can i solve this problem. I have model like this and class Cilt(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Kullanıcı") birth_place = models.CharField(max_length=200, blank=True, null=True, verbose_name="Birth Place") birth_date = models.DateField(blank=True, null=True, verbose_name="Birth date") def __str__(self): return f"{self.user.username}" forms.py class CiltForm(forms.ModelForm): class Meta: model = Cilt exclude = ['user'] fields = '__all__' widgets = { 'birth_place': forms.TextInput(attrs={'class': 'form-control'}), 'birth_date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}), def __init__(self, *args, **kwargs): super(CiltForm, self).__init__(*args, **kwargs) instance = kwargs.get('instance', None) if instance: initial_date = instance.ucuk_en_son_cikis_tarihi self.fields['birth_date'].initial = initial_date self.fields['birth_date'].widget = forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}) edit views def cilt_duzenle(request, user_id): ciltler = get_object_or_404(Cilt, user__id=user_id) if request.method == 'POST': form = CiltForm(request.POST, instance=ciltler) if form.is_valid(): form.save() return redirect('cilt_detay', user_id=user_id) else: form = CiltForm(instance=ciltler) return render(request, 'cilt/cilt_duzenle.html', {'form': form}) -
Connection Timeout on External API Call on Server but Works Locally
I have a Django 4.2.2 application running on Python 3.11. One of the views is as follows: import requests from django.http import HttpResponse def get_captcha(request): response = requests.get( "https://geoportale.cartografia.agenziaentrate.gov.it/age-inspire/srv/ita/Captcha?type=image&lang=it" ) session_id = response.cookies.get("JSESSIONID") request.session["CAPTCHA"] = session_id content_type = response.headers["content-type"] return HttpResponse(response.content, content_type=content_type) When running the application locally, the API call is executed successfully. However, when running on an Aruba server, it results in a timeout. Here are the steps I've taken to try to resolve this issue, without success: Downgraded OpenSSL to the same version used locally (1.1.1n) Disabled the firewall Changed DNS servers for domain resolution Downgraded the Python version Below is the result of traceroute from the server: traceroute to geoportale.cartografia.agenziaentrate.gov.it (217.175.52.194), 30 hops max, 60 byte packets 1 host2-224-110-95.serverdedicati.aruba.it (95.110.224.2) 0.702 ms 0.744 ms 0.824 ms 2 cr2-te0-0-0-2.it2.aruba.it (62.149.185.196) 0.865 ms 0.919 ms * 3 * * * 4 * * * 5 * * * 6 * 93-57-68-2.ip163.fastwebnet.it (93.57.68.2) 10.095 ms 10.516 ms 7 81-208-111-134.ip.fastwebnet.it (81.208.111.134) 10.482 ms 10.370 ms 10.536 ms 8 * * * 9 * * * 10 * * * 11 * * * 12 * * * 13 * * * 14 * * * 15 * * * 16 * … -
How to order migration files across different apps in django?
I am working on a django project. After some time, I wanted to refactor the code. I wanted to create a new app and move some of my models to that app. Here's an example: Suppose I have an app named CategoryApp and two models in it named Product and Category. class Category(models.Model): ... class Product(models.Model): ... After some time of coding, I realized that I need a separate app for Product. So, I created a new app named ProductApp. And copied the Product model from CategoryApp to ProductApp. I managed all the foreign keys and relationships appropriately. Now, I need to create the migration files. First of all, I created a migration file for the app ProductApp (python3 manage.py makemigrations ProductApp) that just creates a new table productapp_product in the database. The migration file is named 0001.py. I applied this migration and a new table is created. Second, I created an empty migration file in the ProductApp (python3 manage.py makemigrations ProductApp --empty). The migration file is named 0002.py I modified the contents of the empty migration file to run SQL query to copy all the data from categoryapp_product table to productapp_product. I also added reverse_sql in case I need … -
TypeError at /predict/ predict_view() missing 2 required positional arguments: 'user_skills' and 'project_skills'
def predict_view(request, user_skills, project_skills): # Fetch data from the database freelancer_data = freelancer_info.objects.get(skills=user_skills) freelancer_data.save() project_data = project_info.objects.get(required_skills=project_skills) project_data.save() # Convert data to DataFrame freelancer_df = pd.DataFrame(list(freelancer_data)) project_df = pd.DataFrame(list(project_data)) # Add labels freelancer_df['label'] = 'freelancer' project_df['label'] = 'project' # Combine data combined_df = pd.concat([freelancer_df, project_df]) combined_df.columns = ['text', 'label'] # Feature extraction vectorizer = CountVectorizer() X = vectorizer.fit_transform(combined_df['text']) y = combined_df['label'] # Split the data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # Train the Naive Bayes model model = MultinomialNB() model.fit(X_train, y_train) # Make predictions y_pred = model.predict(X_test) # Evaluate the model accuracy = accuracy_score(y_test, y_pred) report = classification_report(y_test, y_pred) # Render the results context = { 'accuracy': accuracy, 'report': report, } return render(request, 'frontend/predict.html', context) This my code for making a prediction using naive bayes algorithum, but I receive. TypeError at /predict/ predict_view() missing 2 required positional arguments: 'user_skills' and 'project_skills' How do I over come this issue? -
Unique Constraint Failed In Upsert When Calling bulk_create with update_conficts
Im facing a unique constraint failed error with django. The objective of the api is, eithering creating or updating marks of the student, based on subject variation, exam_results and in bulk. For that, I've used bulk create with update conflicts flag. Here is the current model class Marks(Common): exam_results = models.ForeignKey( "ExamResults", on_delete=models.CASCADE, related_name="marks" ) subject_variation = models.ForeignKey( "SubjectVariation", on_delete=models.CASCADE, related_name="marks" ) student = models.ForeignKey( "Student", on_delete=models.CASCADE, related_name="marks" ) marks_obtained = models.FloatField() objects = BaseModelManager()class Marks(Common): now, when I do bulk create, it asks for unique fields, and since I only want to update marks if there is same exam results, subject variation and student in another instance. So, i add that to unique fields of bulk create. class MarksUpsertSerializer(serializers.ModelSerializer): class Meta: model = Marks fields = ("exam_results", "subject_variation", "marks_obtained") class BulkMarksUpsertSerializer(serializers.Serializer): marks = MarksUpsertSerializer(many=True) def create(self, validated_data): marks = [Marks(**item) for item in validated_data["marks"]] marks = Marks.objects.bulk_create( marks, update_conflicts=True, update_fields=["marks_obtained"], unique_fields=["exam_results", "subject_variation"], ) return marks but when I do this, it says there is no unique or exclusion constraint matching the ON CONFLICT specification. I assumed its because there's no constraint thats been provided to say that those fields must be unique together, so I added a constraint on … -
Django connection to Postgresql encoding problem
I can not connect Django to PostgreSQL database. It show me an encoding problem: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 86: invalid start byte The problem is in that line: File "C:\Users\Robo\Desktop\Stock\venv\Lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) I have tried to change encoding in Settings option, but with no results. DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "Stocks", "USER": "postgres", "PASSWORD": "password", "HOST": "127.0.0.1", "PORT": "5432", "encoding": "utf-8", } } -
Problem when trying to include Allauth form in django template
I have this custom form templates/account/signup.html {% load i18n %} <h2> custom {% trans "Sign Up" %}</h2> <form class="max-w-[500px]" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form.non_field_errors }} <div class="form-group flex flex-row justify-between w-full mt-2 py-4 px-6 bg-white rounded-xl text-black"> {{ form.username.label_tag }} {{ form.username }} {{ form.username.errors }} </div> <div class="form-group flex flex-row justify-between w-full mt-2 py-4 px-6 bg-white rounded-xl text-black"> {{ form.email.label_tag }} {{ form.email }} {{ form.email.errors }} </div> <div class="form-group flex flex-row justify-between w-full mt-2 py-4 px-6 bg-white rounded-xl text-black"> {{ form.password1.label_tag }} {{ form.password1 }} {{ form.password1.errors }} </div> <div class="form-group flex flex-row justify-between w-full mt-2 py-4 px-6 bg-white rounded-xl text-black"> {{ form.password2.label_tag }} {{ form.password2 }} {{ form.password2.errors }} </div> <button type="submit" class="btn btn-primary mt-4">{% trans "Sign Up" %}</button> </form> when open on its own everything work just as expected, but when i try to include this in base.html <div role="tabpanel" class="tab-content bg-base-100 border-base-300 rounded-box p-6"> {% include "account/signup.html" %} </div> form looks like this: included signup form Any idea how to fix this? When I open the signup.html normaly <a href="{% url 'account_signup' %}">Allauth Signup</a> the form looks OK and I can create new account. I want include this html to … -
can't create, edit or upload ... not enough storage. get 100 gb of storage for ₱89.00 ₱22.25/month for 2 months in Django Python
I have this kind of error in my web application when I reload it appears few seconds during loading, is there any code did I made that shows this error? I've used django framework, and I think there's nothing wrong in the template which I used Vuexy dashboard , i think this is not connected to the google storage and my Pc's storage because I tried it in different Pc but the message still appears Is there any wrong with my development? I appreciated the help -
How do I correctly define the url in Django (error Page not found (404))
(I tried solutions provided in similar questions, but they didn't work). I am learning Django, and building the following project: My project is es. I have 3 apps called event, items_dashboard and item. Each event has one items_dashboard, and zero or more items. When the user is in /event/<event_id>/items_dashboard/index.html, there is a link to add a new item to event <event_id>. This opens a form /item/new/<event_id>. When I fill and submit this form, I get the following error: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/item/new/ Using the URLconf defined in event_site.urls, Django tried these URL patterns, in this order: [name='index'] event/ item/ new/<int:event_id> [name='new'] item/ <int:pk>/ [name='detail'] item/ <int:pk>/delete [name='delete_item'] The current path, item/new/, didn’t match any of these. Question: How do I correctly define the url for this scenario? ================================================================= Support material: My relevant urls.py files are as follows: es/urls.py: urlpatterns = [ path('', include('core.urls')), path('admin/', admin.site.urls), path('event/', include('event.urls', namespace="event")), path('item/', include('item.urls', namespace="item")), # path('', index, name='index') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) item/urls.py: app_name = 'item' urlpatterns = [ # path('new/', views.new, name='new'), path('new/<int:event_id>', views.new, name='new'), path('<int:pk>/', views.detail, name='detail'), ] event/urls.py: app_name = 'event' urlpatterns = [ path('new/', views.new, name='new'), path('<int:pk>/', views.detail, name='detail'), path('<int:event_id>/items_dashboard/', include('items_dashboard.urls', namespace='items_dashboard')), path('<int:event_id>/item/', … -
Django: url transition doesn't work, how to fix it?
Good afternoon! I encountered this bug: when clicking on a link, the url changes, but the transition to another page doesn't work. To be more precise: There is a page that displays information about an article (test is the slug of the article): http://127.0.0.1:8001/articles/article/test/ url to go to the update page: http://127.0.0.1:8001/articles/article/test/update/ Composition of the urls.py file: urlpatterns = [ path('', views.index, name='articles_catalog'), path('article/<slug:slug>/<str:author>/', views.details, name='comment_creation'), path('article/<slug:slug>/update/', views.update_article, name='update_article'), path('article/<slug:slug>/', views.details, name='details'), path('new_article/', views.new_article, name='new_article') ] Link to go to: <a href="{% url 'articles:update_article' slug=article.slug %}" id="update_article" target="_self" rel="noreferrer noopener" class="thq-button-filled thq-button-animated" > UPDATE </a> The view itself: @login_required() def update_article(request, slug): print('OK1') article = Article.objects.get(slug=slug) tags = Tag.objects.all() if request.method == 'POST': print('POST') else: form = ArticleForm(instance=article) return render(request, 'articles/create-update.html', {'form': form, 'tags': tags}) As a result, when I click on the link, the url in the address bar changes, but the page itself - remains the same. Please advise me what I might have missed. -
Session Persistence Issue Between Two Django Projects Using Both JWT and Session Authentication
Background Project A Legacy system Django full-stack server based on a template language Using sessions for authentication Python version 3.8 Django version 3.2 Project B New project JSON-based Django RESTful API server Using both JWT and sessions for authentication Python version 3.11 Django version 5.0 Database: MariaDB Currently, we are migrating from the legacy Project A to Project B. During this process, we have switched the authentication method to JWT, but since the entire legacy system has not been migrated yet, we are maintaining the session method alongside it. Both projects use UserenaAuthenticationBackend and utilize django.contrib.auth.authenticate and django.contrib.auth.login for login. In this state, users might log in using either Project A or Project B, which shares the same database. The following issues arise: AS-IS Logging into A from one browser -> Logging into B from another browser -> User gets logged out from A in the first browser. Logging into B from one browser -> Logging into A from another browser -> User gets logged out from B in the first browser. Logging into A from one browser -> Logging into A from another browser -> User remains logged into A in the first browser. Logging into B from one … -
routers doesn't look like a module path-- django error
First time building a django site and keep running into this error with my index.html file for one of the sites that'll hold a list of plants. The error I keep getting is: routers doesn't look like a module path--. Any tips? Here's the html: <!-- plants/templates/index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>List of Plants</title> </head> <body> <h1>Plants</h1> <ul> {% for plant in plants %} <li>{{ plant.name }}</li> <li>Scientific Name: {{ plant.scientific_name }}</li> <li>Description: {{ plant.plant_description }}</li> <li>Price: ${{ plant.price }}</li> <li>Water Needs: {{ plant.water }}</li> <li>Light Needs: {{ plant.light }}</li> <li>Humidity Needs: {{ plant.humidity }}</li> <li>Temperature Needs: {{ plant.temp }}</li> <li>Toxicity: {{ plant.toxic }}</li> <li>Fun Fact: {{ plant.fun_fact }}</li> <br> {% endfor %} </ul> </body> </html> Here's the view: from django.shortcuts import render from .models import Plant # Make sure to import your model def index(request): plants = Plant.objects.all() return render(request, 'index.html', {'plants': plants}) and here's my model: from django.db import models class Plant(models.Model): objects = models.Manager() plant_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) scientific_name = models.CharField(max_length=200) plant_description = models.CharField(max_length=500) price = models.DecimalField(max_digits=10, decimal_places=2) image_name = models.CharField(max_length=256, blank=True, null=True) water = models.CharField(max_length=500) light = models.CharField(max_length=999) humidity = models.CharField(max_length=999) temp = models.CharField(max_length=999) toxic = models.CharField(max_length=999) fun_fact = models.CharField(max_length=999) … -
How to retrieve object of foreign key in many-to-many
I have a many-to-many relationship class Module(BaseModel): name = models.TextField(unique=True, null=False) groups = models.ManyToManyField(ModuleGroup, db_table='module_group_members') class ModuleGroup(BaseModel): name = models.TextField(unique=True, null=False) I want to retrieve the list of modules and their associated groups, something like this: {[ { 'name' : 'name1' 'groups' : ['group1', 'group2'] }, 'name' : 'name2' 'groups' : ['group6', 'group7'] } ]} Tried this modules = Module.objects.filter(is_active=True) print('values_list', list(modules.values('name', 'groups'))) which gives e [{'name': 'name1', 'groups__name': 'group2'}, {'name': 'name1', 'groups__name': 'group2'}, {'name': 'name2', 'groups__name': 'group6'}, {'name': 'name2', 'groups__name': 'group7'}, ] Is there any way to group the same modules together so that the group names are in a list? -
Why is django-ninja PUT endpoint not using the value from the request body but instead returning the default value for field to be updated?
Goal I'm trying to use a Django Ninja API endpoint (with Django Ninja's ModelSchema) to update the time zone preference (tz_preference*) field on my Django app's user model. *Note: The tz_preference field has a default value and is limited to a list of choices. Problem When I test out the API endpoint using /api/docs, the response keeps returning the tz_preference field's default value ("America/Denver") even though I give it other valid values in the request body ("Pacific/Honolulu", "America/Chicago", etc.). I know that my tz_preference field has a default value of "America/Denver", so this is most likely why the response body is {"tz_preference": "America/Denver"}, but I'm not sure why it's sticking with the default instead of using the value I give it in the request body. Code models.py from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.validators import ASCIIUsernameValidator from django.utils.translation import gettext_lazy as _ from timezone_field import TimeZoneField from zoneinfo import ZoneInfo TZ_CHOICES = [ (ZoneInfo('Pacific/Honolulu'), 'Pacific/Honolulu'), (ZoneInfo('America/Anchorage'), 'America/Anchorage'), (ZoneInfo('America/Los_Angeles'), 'America/Los_Angeles'), (ZoneInfo('US/Arizona'), 'US/Arizona'), (ZoneInfo('America/Denver'), 'America/Denver'), (ZoneInfo('America/Chicago'), 'America/Chicago'), (ZoneInfo('America/New_York'), 'America/New_York'), ] class TerpUser(AbstractBaseUser, PermissionsMixin): username_validator = ASCIIUsernameValidator() username = models.CharField( _("username"), max_length=150, unique=True, db_index=True, validators=[username_validator], error_messages={ "unique": _("A user with that username already exists."), }, ) email = models.EmailField( _("email … -
Django display ValidationError on the page instead of getting a yellow screen
Settings.py has DEBUG=True. Without changing that how can I display the ValidationError on the page instead of getting a yellow death screen? forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length = 30) last_name = forms.CharField(max_length = 30) class Meta: model = User fields = ['email', 'first_name', 'last_name', 'password1', 'password2'] def check_email(self): isemail = self.cleaned_data.get("email") if User.objects.filter(email=isemail).exists(): raise ValidationError({"email":"An account already exists."}) return isemail views.py @csrf_protect def user_register(request): form = UserRegisterForm() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.check_email() Yellow screen message ValidationError at /register {'email': ['An account already exists.']} -
Running separate python code to access Django models
Is there a way I can run a stand-alone Python module to access my Django models? For instance, I might want to initialize some tables, or read tables outside of the Django server -
Django LDAP authentication CONNECT_ERROR
I've been trying to connect my app with LDAP server and have been struggling for around a week. These are my settings.py configs: AUTH_LDAP_SERVER_URI = 'ldap://10.xx.xx.1:389' AUTH_LDAP_BIND_DN = 'cn=djangouser,ou=django,ou=groups,dc=xx,dc=xx' AUTH_LDAP_BIND_PASSWORD = 'xx' AUTH_LDAP_USER_SEARCH = LDAPSearch( "dc=xx,dc=xx", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'dc=xx,dc=xx', ldap.SCOPE_SUBTREE, '(objectClass=groupOfNames)' ) AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr="cn") AUTH_LDAP_MIRROR_GROUPS = True AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail', 'username': 'sAMAccountName', 'password': 'userPassword', } AUTH_LDAP_PROFILE_ATTR_MAP = { 'home_directory': 'homeDirectory' } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTH_LDAP_START_TLS = True AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) import logging logger = logging.getLogger('django_auth_ldap') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) Worth to mention i've tried: AUTH_LDAP_USER_DN_TEMPLATE = "sAMAccountName=%(user)s,dc=xx,dc=xx" And I've also tried mentioning the OU like: AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=store,dc=redesejus,dc=local", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'ou=store,dc=redesejus,dc=local', ldap.SCOPE_SUBTREE, '(objectClass=groupOfNames)' ) In all occasions I get the error below when trying to connect through django's admin Panel: Caught LDAPError while authenticating xx: CONNECT_ERROR({'result': -11, 'desc': 'Connect error', 'ctrls': [], 'info': '(unknown error code)'}) "POST /admin/login/?next=/admin/ HTTP/1.1" My AD is Windows server and this is the Structure: GROUPS -> DJANGO -> DJANGOUSER STORE -> GVIX -> USERS NORTH -> USERS SOUTH -> USERS Also worth mentioning I've tested the binding and the connection and everything … -
How to put apache superset as an application in a django project
How to put apache superset as an application in a django project I tried to install the tool using docker, but I want to use the superset tool with the django project so that it becomes an application among the applications in the django project.. -
Initializing tables with fixtures in Django
I have some tables that contain static data. So I want to be able to initialize them. I created a fixture to do this, but it seems that if I run the fixture more than once, it tries to insert the same data. Is there a way I can clear the table first? Similar to the flask drop_all, command, is there a way to drop and re-create all the tables from scratch? Or at least delete all the records. Also, how can I initialize the join table in a many-to-many relationship? -
Show/Hide the menu on another page while clicking radio button on another html page. I want to do this in Django framework
<ul class="navigation" role="navigation"> <li><a href="#"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li> <li><a href="{% url 'asset_list' %}"><i class="fas fa-box"></i> Assets</a></li> <li><a href="#"><i class="fas fa-chart-bar"></i> Reports</a></li> </ul> In the above html code i want to hide asset_list menu. <thead> <tr> <th></th> <th>Privilege Update</th> <th>Report Download</th> <th>Assign Asset</th> <th>Asset History</th> <th>View</th> <th>Edit</th> <th>Delete</th> <th>Add</th> </tr> </thead> <tbody> <tr> <td>Assets</td> <td> </td> <td> </td> <td> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </td> hide the asset menu when clicking a radio button in another page . Here both dashboard and switch are in two separate html pages.hide the asset menu when clicking a radio button in another page. -
How to express the reverse of a Many-to-One in Django
I realized that Django has Many-to-One and not One-to-Many, but how to you express the opposite relationship? I have a table which has 2 foreign keys to another table. The table Validation_Run has 2 foreign keys to Calibration_Run Django complains that that the reverse relationship has a conflict calibration.ValidationRun.calibration_run_pk: (fields.E304) Reverse accessor 'CalibrationRun.validationrun_set' for 'calibration.ValidationRun.calibration_run_pk' clashes with reverse accessor for 'calibration.ValidationRun.calibration_run_pk_tune_parameters'. HINT: Add or change a related_name argument to the definition for 'calibration.ValidationRun.calibration_run_pk' or 'calibration.ValidationRun.calibration_run_pk_tune_parameters'. How do I define the reverse relationship (from Calibration_Run to Validation_Run), so there is no conflict? -
How to pass the selected value of select2 element as parameter in htmx?
I want to do GET request with query parameter. However, the query parameter need to be taken from select2 elements. How do I pass the selected value of select2 to htmx? Below is the simplified overview of my code. <select id="filter">...</select> <select id="filter2">...</select> ... <button hx-get="{% url 'filter-data'}" hx-trigger="click" hx-include="#filter, #filter2" hx-target="targetDiv" >Filter</button> <script> $(document).ready(function () { $('#filter').select2() $('#filter2').select2() } </script> I've tried to search for similar problem but none were found. Any pointer is appreciated. -
Django subquery with static VALUES expression
Is it possible using the Django ORM to write a subquery which SELECTs from a set of fixed values? SELECT id, name, ( SELECT new_ages.age FROM (VALUES ('homer', 35), ('marge', 34)) AS new_ages(name, age) WHERE new_ages.name = ages.name ) AS new_age FROM ages ; The output from such a query might be something like: person_id name age 1 homer 35 42 marge 34 99 bart null I know that the Django code would look something like this: from django.db.models import OuterRef, Subquery from my_app.models import Person Person.objects.annotate(age=Subquery(...(name=OuterRef("name"))) But what goes in the ...?