Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to link pages depending on foreign key using django
I tried to link countries to continents depending on the foreign key "ckey". I tried using filter and .raw but it didn't work. I tried to use it directly on HTML but it said it cannot praise it. I need to know if there is another way of linking pages like "continents -> countries -> cities -> ...." using Django. models from django.db import models # Create your models here. class Continents(models.Model): ckey = models.CharField(max_length=10, primary_key=True) continentName = models.CharField(max_length=50) class country(models.Model): countryNum = models.IntegerField(primary_key=True) countryName = models.CharField(max_length=15) countryBrief= models.TextField(max_length=500) currency = models.CharField(max_length=15) cost = models.FloatField(max_length=10) cultures = models.TextField(max_length=300) rulesBrief = models.TextField(max_length=200) location = models.TextField(max_length=500) ckey = models.ForeignKey('Continents', on_delete=models.PROTECT) views.py from django.shortcuts import render from django.http import HttpResponse from .models import Continents, country # Create your views here. def home(request): return render(request,"guide/home.html") def continents(request): continentdata = Continents.objects.all() return render(request,"guide/Continents.html",{'Continents':continentdata}) def countrylist(request): countries = country.objects.all() first_person = country.objects.filter(ckey='as45914') context = { "first_person":first_person, "countries":countries, } return render(request,"guide/countrylist.html",context=context) html code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {{first_person}} </body> </html> strange message I got when I run the code How do I link pages like that? For example "Europe > United kingdom > all … -
How delete a record on button click using Django?
I am trying to delete a record in a database when a yes button is clicked using django. views.py def deleteServer(request, server_id): server = Server.objects.get(pk=server_id) print(request.POST) if request.POST.get('yesBtn'): server.delete() return HttpResponseRedirect('homepage') elif request.POST.get('noBtn'): return HttpResponseRedirect('homepage') return render(request, 'deleteServer.html', {'value': request.POST}) deleteServer.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>Cancella server</title> </head> <body> <button onclick="document.getElementById('id01').style.display='block'" class="w3-button">Cancella server</button> <!-- The Modal --> <div id="id01" class="w3-modal"> <div class="w3-modal-content"> <div class="w3-container"> <span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-display-topright">&times;</span> <p>Vuoi davvero cancellare il server selezionato?</p> <a href="{% url 'homepage' %}" type="button" name="yesBtn" class="btn btn-success">SI</a> <a href="{% url 'homepage' %}" type="button" name="noBtn" class="btn btn-danger">NO</a> </div> </div> </div> </body> </html> When I click on the yes button the record is not deleted. I thought the problem is in the deleteServer function in the file views.py. -
CSS and HTML (django)
Hey so i have this CSS .welcome_box{ background-color: aqua; min-height: 50px; min-width: 50px; padding: 20px }` and in the html <div class="welcome_box" > <div class="center" > <a href="{% url 'login'%}"> <button class="button">Log In</button> </a> </div> <div class="center"> <a href="{% url 'signup'%}"> <button class="button"> Sign Up</button> </a> </div> </div> and the rel <link rel="stylesheet" href="{% static 'welcomepage/styles/css/mycss.css' %}"> however the CSS does not seem to take effect on the page, for some reason its only this class as the rest are working. I don't do much html and css so it may be something very basic. Edit: Inline CSS seems to work fine but again, the other classes from the same css file do take effect -
AssertionError: False is not True in Django when testing for valid forms
I am writing a test for my views to check if the POST data is validated but the test failed with this error, self.assertTrue(form.is_valid()) AssertionError: False is not true Below are my codes tests.py from .models import Customer from .forms import CustomUserCreationForm from django.contrib.auth import get_user_model from django.urls import reverse from django.http import HttpRequest # Create your tests here. class CreateAccountTest(TestCase): email = "example@gmail.com" def test_signup_page_status_code(self): response = self.client.get('/accounts/signup/') self.assertEqual(response.status_code, 200) def test_signup_url_by_name_and_uses_correct_template(self): response = self.client.get(reverse ('register')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'registration/signup.html') def test_signup_empty_form(self): form = CustomUserCreationForm() self.assertIn('first_name', form.fields) self.assertIn('last_name', form.fields) self.assertIn('password1', form.fields) self.assertIn('password2', form.fields) def test_signup__post_form(self): request = HttpRequest() request.POST = { 'email': self.email, 'first_name': 'Adam', 'last_name': 'Smith', 'password1': 'qazxswedcvfr', 'password2': 'qazxswedcvfr', } form = CustomUserCreationForm(request.POST) self.assertTrue(form.is_valid()) form.save() self.assertEqual(get_user_model().objects.all().count(), 1) -
Multi Value DictKey Error in django while getting files in Django
So, I have this simple django code in which a user uploads a image to change his user image but whenever I am trying to initiate the function it throws a multi value dict key error. Views.py def image(request): email = request.user.email img = request.FILES['image'] users = get_user_model() User = users.objects.get(email=email) User.image = img User.save() return redirect('settings') I am using a custom user model aswell so here is my models.py also class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True,) user_name = models.CharField(max_length=150, unique=False) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) image = models.ImageField(upload_to = 'pics') DOB = models.CharField(max_length =12, default=timezone.now) start_date = models.CharField(max_length =12,default=timezone.now) about = models.TextField( max_length=500, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_buss = models.BooleanField(default=False) phone = models.CharField(max_length=12) otp = models.CharField(max_length=6, null=True) otp_g = models.CharField(max_length=15, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name','first_name'] objects = CustomAccountManager() def __str__(self): return self.user_name class CustomAccountManager(BaseUserManager): def create_superuser(self, email,user_name, first_name,password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('SuperUser must have is_staff as true') if other_fields.get('is_active') is not True: raise ValueError(_('SuperUser must have is_active as true')) if other_fields.get('is_superuser') is not True: raise ValueError('SuperUser must have is_SuperUser as true') return self.create_user(email,user_name, first_name, password, **other_fields) def create_user(self, email,user_name, first_name, password, … -
How Can I query Django Models with Foreign and OneToOneFields for Field Values
I have the following Django Models in my project: Event, Ticket, Pin and Guest so How can I query these tables in order to get the name of an Event Name the logged in guest user has registered for . Below are my code. My Models: class Event(models.Model): event_name = models.CharField(max_length=100) date = models.DateField(auto_now_add=False, auto_now=False, null=False) event_venue = models.CharField(max_length=200) event_logo = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images') added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.event_name}" #Prepare the url path for the Model def get_absolute_url(self): return reverse("event_detail", args=[str(self.id)]) #Ticket Model class Ticket(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) price = models.PositiveIntegerField() category = models.CharField(max_length=100, choices=PASS, default=None, blank=True, null=True) added_date = models.DateField(auto_now_add=True) def __str__(self): return f"{self.event} " #Prepare the url path for the Model def get_absolute_url(self): return reverse("ticket-detail", args=[str(self.id)]) def generate_pin(): return ''.join(str(randint(0, 9)) for _ in range(6)) class Pin(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) value = models.CharField(max_length=6, default=generate_pin, blank=True) added = models.DateTimeField(auto_now_add=True, blank=False) reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) status = models.CharField(max_length=30, default='Not Activated') #Save Reference Number def save(self, *args, **kwargs): self.reference == str(uuid.uuid4()) super().save(*args, **kwargs) def __unicode__(self): return self.ticket class Meta: unique_together = ["ticket", "value"] def __str__(self): return f"{self.ticket}" def get_absolute_url(self): return reverse("pin-detail", args=[str(self.id)]) class Guest(models.Model): guest_name = models.OneToOneField(User, on_delete=models.CASCADE, blank=True) pin … -
Django distinct queryset
I am new in django and maybe someone in here can help me with this.. model.py class Transaction(models.Model): ref_code = models.CharField() buyer = models.ForeignKey(User) product = models.ForeignKey(Product) quantity = models.IntegerField() ref_code is not unique. The Data is something like this: id: 1, buyer: John, product : Book, quantity: 1, ref_code = 111111 id: 2, buyer: Thomas, product : Pencil, quantity: 3, ref_code = 111111 id: 3, buyer: Mary, product : Book, quantity: 2, ref_code = 222222 id: 4, buyer: Bryan, product : Origami, quantity: 2, ref_code = 222222 id: 5, buyer: Anna, product : Eraser, quantity: 5, ref_code = 111111 id: 6, buyer: Lily, product : Notebook, quantity: 1, ref_code = 222222 How can I view buyer, product, and quantitiy in template based on ref_code ? So, it will look like this: REFERAL CODE: 111111 Buyer: John, Product : Book, Quantity: 1 Buyer: Thomas, Product : Pencil, Quantity: 3 Buyer: Anna, Product : Eraser, Quantity: 5 REFERAL CODE: 222222 Buyer: Mary, Product : Book, Quantity: 2 Buyer: Lily, Product : Notebook, Quantity: 1 Buyer: Bryan, Product : Origami, Quantity: 2 Thanks in advanced -
Reset a page after submitting a button
<form method=GET> {% csrf_token %} <ul><h2 style="font-weight: bold;">Список дел</h2><br><details open><summary style="color:#0077DC">свернуть фильтр</summary> <li><p class="name"><i>С какого числа искать:</i>{{ myFilter.form.start_date }}</p></li> <li><p class="name"><i>По какое:</i>{{ myFilter.form.end_date }}</p></li> <li><p style="font-size:16px; color: red;"><i>Наименование суда:</i>{{ myFilter.form.trial }}</p></li> <p style="font-size:16px; color:#f44133;"><i>Судопроизводство:</i>{{ myFilter.form.proceeding }}</p> <p style="font-size:16px; color: red;"><i>Первая подкатегория:</i>{{ myFilter.form.categories__value }}</p> <p style="font-size:16px; color: red;"><i>Вторая подкатегория:</i>{{ myFilter.form.categories__second1_dispute }}</p> <p style="font-size:16px; color: red;"><i>Вторая подкатегория:</i>{{ myFilter.form.categories__second2_dispute }}</p> <p style="font-size:16px; color: red;"><i>Третья подкатегория:</i>{{ myFilter.form.categories__third_dispute }}</p> <br> <button class="btn btn-dark" type="submit" style="width:39%;">Применить</button> <input class="btn btn-dark" type="reset" value="Отменить выбор" style="width:59%;"></a><br> <br> </form> A have the form and if a choose a filtration category I can reset the page, but if I submit the button and I want to reset the page after that nothing changes. -
Get View associated with a URL
I'm looking to know the associated class-based view that is associated with a path. Say I have URL pattern like this : urlpatterns = [ path("hello/<str:name>/", views.HelloView.as_view(), name="hello-page") ] Could I, from a path like "hello/foo/" get back to the HelloView class ? Ideally I'd like to be able to do it like this : the_url = "hello/foo/" url_associated_view = get_view_class_from_path(the_url) print(url_associated_view) >> HelloView It's different from this topic because the suggested answer only gives me the as_view function as a value, while I'm trying to get the HelloView class as return value. -
Django templates path change problem Django 4.1.1
enter image description here i am new in Django i want change my Django Template path . but they are set by dafault a path in setting.py then i import os but it will not working -
not good template loaded in Django generic list view when using filter
I have a strange behavior im my generic views. Below is the classic FBV scheme I want to reproduce in a CBV My FBV def post_list(request, tag_name=None): if tag_name: # filter post according to tag name if provided posts = Post.objects.filter(tag__tag_name=tag_name) else: posts = Post.objects.all() context = {"posts": posts} return render(request, "blog/post_list.html", context) def post_detail(request, post_id): post = Post.objects.get(pk=post_id) context = {"post": post} return render(request, "blog/post_detail.html", context) My CBV class PostList(ListView): model = Post context_object_name = "post_list" template_name = "blog/post_list.html" def get_queryset(self): if "tag_name" in self.kwargs: return Post.objects.filter(tag__tag_name=self.kwargs["tag_name"]) else: return Post.objects.all() class PostDetail(DetailView): model = Post context_object_name = "post_detail" template_name = "blog/post_detail.html" Here are my models from django.db import models # Create your models here. class Tag(models.Model): tag_name = models.CharField(max_length=100) def __str__(self): return self.tag_name class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() tag = models.ManyToManyField(Tag, blank=True) def __str__(self): return self.title And here my urls from django.urls import path from .views import PostList, PostDetail urlpatterns = [ path("", PostList.as_view(), name="blog-index"), path("<tag_name>", PostList.as_view(), name="blog-index"), path("<int:pk>", PostDetail.as_view(), name="post-detail") ] As you can see I want to use the same generic view for the list of my posts with an optional tag provided in url. It is well filtering my articles when I provide … -
Django: How to create a user action log/trace with vizualization
I am looking for a tool to track user actions like: user logged in user changed password user got bill via email user logged user uploaded image user send message ... which I can include into my Django project. Afterwards I want to build queries and ask the system stuff like: how often did a user a message within a month how often did a user login within a month does the user uploaded any images and I would like to have some kind of interface. (Like google analytics) Any idea? I am pretty sure that this is a common task, but I could not find anything like this. -
object has no attribute 'is_vallid'
I wrote a function with which you can change the data you entered during registration. But Django throws the following error : AccountUpdateForm object has no attribute 'is_vallid' here is my code, tell me where I made a mistake def account_view(request): if not request.user.is_authenticated: return redirect("login") context = {} if request.POST: form = AccountUpdateForm(request.POST, instance=request.user) if form.is_valid(): form.save() else: form = AccountUpdateForm( initial={ "email": request.user.email, "username": request.user.username, } ) context['account_form'] = form return render(request,'account/account.html', context) -
Why can't I display my data filtered to active user?
I'm trying to display only data for the logged in user in my table. I can display everything using objects.all() but when I filter to the active user, it doesn't work. I have tried changing my context to refer to the queryset as a whole but I get an error saying that I can't perform get on a tuple. If I have the context as is, I get an error saying 'QuerySet object has no attribute 'user' Models.py: class HealthStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.IntegerField(default=5) run_time = models.TimeField() class Meta: db_table = 'health_stats' ordering = ['-date'] def __str__(self): return f"{self.user} | {self.date}" Views.py: def health_history(request): queryset = HealthStats.objects.filter(user=request.user).values() print(queryset) print(type(queryset)) context = { "user": queryset.user_id, "weight": queryset.weight, "date": queryset.date, "run_distance": queryset.run_distance, "run_time": queryset.run_time, } return (request, 'health_hub_history.html', context) health_hub_history.html: {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 text-center"> <h1>My Health History</h1> </div> </div> </div> <div class="container-fluid"> <div class="row justify-content-center"> <div class="col-auto text-center p-3"> <table class="table table-striped table-hover table-bordered"> <tr> <td>User:</td> <td>Weight (lbs):</td> <td>Date:</td> <td>Run Distance (km):</td> <td>Run Time (HH:MM:SS):</td> </tr> {% for stat in queryset %} <tr> <td>{{ stat.user }}</td> <td>{{ … -
Django Backend architecture for multiple projects with shared class models
We are using Django to develop our product. Our product contains 5 Django projects. Each project uses 50 shared class Models and models are in the developing process. There are two possible ways to handle all these related projects with models in the development and production process: One possible solution is to use models in one project with all migration files and use them in other projects with managed=False in the Django class model. But the problem with this structure is: Each change in original models must apply to other projects This approach makes the production process repeatedly and hard to manage properly New features in each project are connected to model changes By adding new required fields to an existing model, other projects that create new instances from the updated model would face rational problems. Even if they don't use these new fields The other possible solution is gathering all projects as one project with the below diagram: Diagram Now this configuration's problem is: Complicated deploying production Complicated to route the project All deployed services should redeploy with every change in one model All of the projects are in one place My question is: Whether the suggested solutions are … -
How can I connect Firebase DB to Django project in Python
Do you know whether it is possible to connect to the Firebase database through the Django framework in Python instead of SQL, SQLLite3, or PostgreSQL, etc., In the event that it is possible to connect Firebase DB to Django, can anyone please assist me in connecting Firebase DB to Django? -
Is there a way of pulling data.id from your frontend using JS to the views in django ... heres my code .... n I can't seem to find the error [closed]
#form to return to db if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): # store all the billing info data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.street = form.cleaned_data['street'] data.location = form.cleaned_data['location'] data.county = form.cleaned_data['county'] data.city = form.cleaned_data['city'] data.order_note = form.cleaned_data['order_note'] data.order_total = grand_total data.tax = tax data.ip = request.META.get('REMOTE_ADDR') #data.save() # generate order number yr = int(datetime.date.today().strftime('%Y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr, mt, dt) current_date = d.strftime("%Y%m%d") order_number = current_date + str(data.id) data.order_number = order_number data.save() order=Order.objects.get(user=current_user, is_ordered=False, order_number=order_number) context={ 'order':order, 'cart_items':cart_items, 'total':total, 'tax':tax, 'grand_total':grand_total, } return render(request,'orders/payments.html', context) else: return redirect('checkout') #to pull data id function getCookie(name){ let cookieValue = null; if (document.cookie && document.cookie !== ''){ const cookies = document.cookie.split(';'); for (let i=0; i response.json()) .then((data) => { window.location.href = redirect_url+'?order_number='+data.order_number+'&payment_id='+data.transID; //window.location.href = redirect_url +'?order_number='+data.order_number+'&payment_id='+data.transID; }); } }); } }).render('#paypal-button-container'); -
Django search field in the database
is it possible to change my display employe to a search block because when I select the numbers it displays a list which is not practical when I have a lot of numbers in my database. add info to an existing employee -
Django PasswordResetDoneView does not redirect to login
I have a reset password procedure, here are the codes: Password Reset Request: <form method="POST"> {% csrf_token %} <div class="wrap-input100 validate-input input-group" data-bs-validate="Format email valide requis: ex@abc.xyz"> <a class="input-group-text bg-white text-muted"> <i class="zmdi zmdi-email text-muted" aria-hidden="true"></i> </a> <input id="id_email" class="input100 border-start-0 form-control ms-0" type="email" placeholder="Email" name="email" autocomplete="email" maxlength="254"> </div> <button class="btn btn-primary" type="submit">Envoyer le lien de réinitialisation</button> </form> Password Reset Confirmation: <form method="POST"> {% csrf_token %} <div class="wrap-input100 validate-input input-group" id="Password-toggle"> <a class="input-group-text bg-white text-muted"> <i class="zmdi zmdi-eye text-muted" aria-hidden="true"></i> </a> <input class="input100 border-start-0 form-control ms-0" type="password" placeholder="Nouveau mot de passe" id="id_new_password1" name="new_password1"> </div> <div class="wrap-input100 validate-input input-group" id="Password-toggle"> <a class="input-group-text bg-white text-muted"> <i class="zmdi zmdi-eye text-muted" aria-hidden="true"></i> </a> <input class="input100 border-start-0 form-control ms-0" type="password" placeholder="Confirmation du nouveau mot de passe" id="id_new_password2" name="new_password2"> </div> <div class="container-login100-form-btn"> <button class="login100-form-btn btn-primary" type='submit'>Réinitialiser</button> </div> </form> Password Reset View: def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data["email"] associated_users = Account.objects.filter(Q(email=data)) if associated_users.exists(): for user in associated_users: subject = "Demande de changement de mot de passe" email_template_name = "core/email/password_reset_email.txt" c = { "email": user.email, "domain": EMAIL_DOMAIN, "site_name": "XXXXXX.XXXX", "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, "token": account_activation_token.make_token(user), "protocol": EMAIL_PROTOCOL, } email = render_to_string(email_template_name, c) try: send_mail( subject, email, "info@XXXXXX.XXXX", [user.email], fail_silently=False, ) … -
Install Django apps through the Django admin-site like plugins in Wordpress
I want to implement a module-manager in Django where third-party modules can be installed through the django admin interface (without changing the code-base of the main project). These modules should have the same capabilities as a django app. For example, defining models and views, making migrations, and interacting with other apps. Similar to how it works with the plugin-manager of Wordpress. Is there a good way to do this? (and are there reasons why I should not?) -
Maximum recursion depth while applying a Listing filter in django
I am trying to implement Listing Filter from django filters. First "type" is the attribute that I want my filter to be based inside models.py of my app. class detaileditems(models.Model): title = models.CharField(max_length= 255) type = models.CharField(max_length= 45, null=True) pubdate = models.DateTimeField() body = models.TextField() image = models.ImageField(upload_to= 'images/') I have created a separate filters.py inside my application where I have called the filters. import django_filters from .models import detaileditems class ListingFilters(django_filters.FilterSet): class Meta: model = detaileditems fields = {'type': ['exact']} Next here is my function inside views.py file- from .models import detaileditems from .filters import ListingFilters def alldetailed2(request): items = detaileditems.objects listing_filter = ListingFilters(request.GET, queryset=items) context = { 'listing_filter' : listing_filter, 'items': items, } return render(request, 'detailed2/detailed2.html',context) Lastly in my html file "detailed2.html" which is inside the application template folder of "detailed2". <div class = "col-lg-6 col-md-8 mx-auto"> <form method = "get"> {{ listing_filter.form }} <button class="btn btn-sm btn-danger" type="submit">Search</button> </form> </div> <div class = "container"> <div class = "row row-cols-1 row-cols-sm2 row-cols-md-3 g-3"> {% for listing in listing_filter.qs %} <div class = "col"> {% include "detailed2/detailed2.html" %} </div> {% endfor %} </div> </div> I am getting a maximum recursion depth error. -
Alter default django models tables generation
I'm trying to create two related models in django, a custom user model and a company model. where one user belongs to one company and one company has many users. class Company(models.Model): name = models.CharField(max_length=255) class User(AbstractBaseUser): objects = UserManager() id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, unique=True) name = models.CharField(max_length=67) username = models.CharField(max_length=255, unique=True) email = models.EmailField(max_length=255, unique=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) last_login = models.DateTimeField(auto_now=True) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_supuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True By default django generated two tables like this: But I dont want any foreign keys directly on those tables, instead i want a third auxiliary table with the two foreign keys from the models like this: How could I do something like that ? -
Where to store training data files in Django for a Chatbot?
I am trying to display a chatbot that I created on a django site. So I need to load some training data (json, pickle and h5 files) into views.py file. But when I run the server it says: FileNotFoundError: [Errno 2] No such file or directory: 'mysite/polls/intents.json' even though views.py and intents.json are in the same folder. So now I am wondering where I should store these files and how to open/import them into my views.py file. Do I need to put them into my static files folder or something like that? Here is the code from the views.py file: from django.shortcuts import render from django.http import HttpResponse import nltk from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() import pickle import numpy as np from keras.models import load_model import json import random # Create your views here. def index(request): intents = json.loads(open('intents.json').read()) model = load_model('chatbot_model.h5') words = pickle.load(open('words.pkl','rb')) classes = pickle.load(open('classes.pkl','rb')) def clean_up_sentence(sentence): sentence_words = nltk.word_tokenize(sentence) sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words] return sentence_words # return bag of words array: 0 or 1 for each word in the bag that exists in the sentence def bow(sentence, words, show_details=True): # tokenize the pattern sentence_words = clean_up_sentence(sentence) # bag of words - … -
Django rest not showing list error in corresponding index
I have a service that accepts a datetime list. I am deliberately sending a list which has the error its 1. index. Error should be returned as an array which has 1. index, but it returns as shown below. The dates field is a RelatedField and many=True post_data=["2020-01-01","a"] Expected error response; 'dates': { '1': { ['Incorrect format. Expected iso format.'] } } Real error response; 'dates': ['Incorrect format. Expected iso format.'] models.py class EventModel(models.Model): title = models.CharField(max_length=100, null=False, blank=False) address = models.CharField(max_length=255, null=False, blank=False) def __str__(self): return self.title class EventDateTimeModel(models.Model): date_time = models.DateTimeField(null=False, blank=False) event = models.ForeignKey('EventModel', on_delete=models.CASCADE, related_name='dates') def __str__(self): return self.date_time.isoformat() serialziers.py class DateTimeReleatedField(serializers.RelatedField): default_error_messages = { 'incorrect_type': 'Incorrect format. Expected iso format', } def to_internal_value(self, data): try: if not isinstance(data, str): raise TypeError return datetime.fromisoformat(data) # str to datetime object in post data except (TypeError, ValueError): self.fail('incorrect_type', data_type=type(data).__name__) def to_representation(self, value): return str(value) # using "EventDateTimeModel" model's __str__() method class EventSerializer(serializers.ModelSerializer): dates = DateTimeReleatedField(many=True, queryset=EventDateTimeModel.objects.all(), required=True) class Meta: model = EventModel fields = ['id', 'title', 'address', 'dates'] def create(self, validated_data): dates = validated_data.pop('dates', None) with transaction.atomic(): instance = super().create(validated_data) if dates: for date_time in dates: EventDateTimeModel.objects.create(date_time=date_time, event=instance) return instance def update(self, instance, validated_data): dates = validated_data.pop('dates', None) … -
how to retrieve latest data from django model in tamplates
i am trying to retrieve latest single data from Django model and show it in templates instead of all the data the method I trying to use in my view to achieve that def preview(request): readme = Personal_readme.objects.latest('create_date') return render(request, 'preview.html',{'readme':readme}) and in my models create_date = models.DateTimeField(default=timezone.now,editable=False) but when I runserve and refer to a page it TypeError at /preview/ Personal_readme' object is not iterable it work fine when use this readme = Personal_readme.objects.all() but retrieve all the data in it but i want to retrieve single(one) the latest data based on create_date I have no idea why its is show like this