Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm getting this error when i try to send email with django ,can any body help me?
I'm trying to send an email from django using gmail smtp I've set insecure source ON in my account's setting also this is my settings.py file can anybody help me ? EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com ' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER =' my email' EMAIL_HOST_PASSWORD = 'my password' and I'm getting this error in terminal for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11001] getaddrinfo failed -
redirect to another page with information about the new user after creating this user in Django
I'm creating an appointment application using Django for register and non register user for the non register user the doctor needs to create a temporary user and add his information after that he can book an appointment for this user the best i can get to is this @login_required def create_appointment_non_register_P(request): form_user = UserEditForm() if request.method=='POST' : form_user = UserEditForm() if form_user.is_valid(): new_T_user = form_user.save(commit=False) form_user.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request, 'appointement/add_appointement2.html', {'user_form':form_user, }) @login_required def create_appointment_D(request): if request.method=='POST' : user = User() if request.user.is_doctor() or request.user.is_reception(): appointment = request.POST['type'] if appointment=='register patient': form_appointment = AppointmentForm_2() if form_appointment.is_valid(): form_appointment.save(commit=False) form_appointment.user = request.user form_appointment.end_time = form_appointment.start_time + timedelta(minutes=30) form_appointment.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request, 'appointement/add_appointement1.html', {'user_form':form_appointment, }) else: return HttpResponseRedirect(reverse("create_appointment_non_register_P")) return render(request, 'appointement/add_appointement1.html', {'user_form':form_user, }) else: return HttpResponseRedirect(reverse("create_appointment_P")) return render(request,'appointement/add_appointement_options.html') but the it did not create a new user and how after creating this user and redirect to a new page with the appointment form can book an appointment for him -
Create a model object after creation of related model object using model manager
I have three models as follows, models.py: class Activity(models.Model): # ... objects = models.Manager() activity = ActivityManager() kind = models.CharField(max_length=10, choices=KIND_CHOICES) # ... class ActivtyA(models.Model): # ... activity = models.OneToOneField( Activity, on_delete=models.CASCADE, related_name='A', ) # ... class ActivtyB(models.Model): # ... activity = models.OneToOneField( Activity, on_delete=models.CASCADE, related_name='B', ) # ... and a model manager, managers.py: class ActivityManager(models.Manager): def create_activity(self, validated_data): # ... data = validated_data.pop(kind) act = self.create(**validated_data) if act.kind == 'A': # Create ActivityA(act, **data) elif act.kind == 'B': # Create ActivityB(act, **data) # ... # ... In model manager's create_activity method I wand to create Activty and either ActivityA or ActivtyB based on Activity.kind. How can I achieve this? I tried to do this by using signals but could make it. @receiver(post_save, sender=Activity) def create_activity_details(sender, instance, using, **kwargs): if instance.kind == 'FOOD': ActivityDetailsFood.objects.create(activity=instance, data=????) # Need data to create this object -
FilterView, get_context_data() does not work. No attribute 'object_list' but there is one
I am using django_tables2 with django_filter. When trying to edit context in def post(), so first getting actuall context (context=get_context_data(self)) it shows error: 'FilteredZamTableView' object has no attribute 'object_list' But it does have object_list attribute! This is ridiculous. I printed it inside get_context_data() declaration def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(context) return context It shows: {'paginator': <django.core.paginator.Paginator object at 0x0000024EBAABE7F0>, 'page_obj': <Page 1 of 2>, 'is_paginated': True, 'object_list': <QuerySet [---CONTENT---]>... Here's my class based view with post method. class FilteredZamTableView(LoginRequiredMixin, SingleTableMixin, FilterView): table_class = ZamTable template_name = 'home.html' paginate_by = 10 filterset_class = ZamFilter def post(self, request, *args, **kwargs): if request.POST.get('accept'): try: context = get_context_data(self) <--------------------------- ERROR return redirect('home') except Exception as e_msg: print(e_msg) return redirect('home') It honestly looks like an error in django_filters. -
how create multiple choice plus with custom choice in django
i'am trying to creating model which one will be for product. it must create information for example. [Male(static)][Female(static)] [Enter how you want to describe(editable)] but when i want to add choice to charfield my choicefield is dublicated. from django.db import models class Pricetab(models.Model): choice = models.CharField(max_length=200,default='test') content = models.TextField() button = models.CharField(max_length=100,default='test') MONTH_YEAR_CHOICE = ( (True, 'male'), (False, 'female') ) gender = models.Charfield(maxl_length=100, choices=MONTH_YEAR_CHOICE,default=True) def __str__(self): return self.title -
OperationalError at / no such column:core_item.brands_id
I am having a tricky database problem. I have a set of categories that display on the nav bar, once you click on those categories, there is a filter called brand, and this brand filter is supposed to take you to a page where they have products under that category (e.g. makup) and display those items. So I tried to have two foreign keys in my items module as below. Models.py class Category(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:category", kwargs={ 'slug': self.slug }) class Brand(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:brand", kwargs={ 'slug': self.slug }) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.PROTECT, null=True, related_name='category') brands = models.ForeignKey(Brand, on_delete=models.PROTECT, null=True, related_name='brands') label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() stock_no = models.CharField(max_length=10) description_short = models.CharField(max_length=50) description_long = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def … -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' for a django project
this is my first submession here, so whenever i try to run python manage.py runserver for a django project it didn't and it give an error i never saw before Any ideas about what is this and how to fix it? it give me the following error: The Error i get Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "D:\GitHub\herafi\manage.py", line 22, in <module> main() File "D:\GitHub\herafi\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 96, in handle self.run(**options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 618, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 603, in start_django reloader.run(django_main_thread) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 318, in run self.run_loop() File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 324, in run_loop next(ticker) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 364, in tick for filepath, mtime in self.snapshot_files(): File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 380, in snapshot_files for file in self.watched_files(): File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 278, in watched_files yield from iter_all_python_module_files() File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 105, … -
How to get the result of a textfield in django?
i am making a python editor, and i have a model called NewJax. In this model, i have a field called space. The space field executes the python code i typed in there. for example, if i did print('hello') in the space field, it should take me to a detail page, and return the result. Which is hello. but when it takes me to the details page for now, it results in None. Could you someone please let me know, how this should execute? models.py class NewJax(models.Model): title = models.CharField(max_length=60) description = models.TextField(max_length=140) space = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_created'] verbose_name_plural = "New Jax" def __str__(self): return str(self.title) forms.py class CreateNewJaxForm(forms.ModelForm): class Meta: model = NewJax fields = ('title', 'description', 'space') widgets = { "title": forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'name your jax' } ), 'description': forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'add a brief description for jax', 'rows': 4, } ), 'space': forms.Textarea( attrs={ 'class': 'form-control', } ) } views.py def create_new_jax(request): if request.user.username == "Assasinator": logout(request) return redirect('banned_user') if request.method == "POST": form = CreateNewJaxForm(request.POST or None) if form.is_valid(): title = form.cleaned_data.get('title') description = form.cleaned_data.get('description') space = form.cleaned_data.get('space') obj = form.save(commit=False) … -
Django+Rest and later React without Docker?
I would like to ask an advice... I did the project with Django+Rest... But never thought about adding to them React... But I would like to do React... I did it, but it runs as a local version... So I have Django which runs as https and React which runs as http://localserver:3000... Which is not really good... I went through about 6 or 7 tutorials... But they all using Docker... To use Docker I have to restructure the project completely... When I structured project first time I didn't think about React. Now generally the structure is like this: -files and folders for Djago -frontend files and folders for React -in the root of the server: /etc... files and folders for gunicorn and nginx So the question is: Is it possible to serve React, only by tuning gunicorn and nginx, without changing the site itself... So url will be something like this: https://address/home/django_url https://address/home/React_url Similar to Rest api, which I run like so:https://address/home/api/Rest_url Or so React will be as frontend based on the Django as backend... I'm kind of confused about if I can do it and how... -
Django m2m workaround relationship reverse relation
So I have three models like this. class Member(models.Model): class Meta: constraints = [ models.UniqueConstraint( fields=('user', 'locker'), name='unique_locker_member_check' ), ] locker = models.ForeignKey( to='uploads.Locker', verbose_name=_('locker'), on_delete=models.CASCADE, editable=False ) user = models.ForeignKey( to=settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE, editable=False ) class Role(CoreModel): class Meta: ordering = ('position', 'locker') permission_flags = ( 'ADD_STARS', 'DOWNLOAD_FILES', 'SEND_UPLOADS', 'MANAGE_UPLOADS', 'MANAGE_ROLES', 'MANAGE_LOCKER', 'MANAGE_INVITES', 'KICK_MEMBERS', 'BAN_MEMBERS' ) default_flags = ( 'ADD_STARS', 'DOWNLOAD_FILES', 'SEND_UPLOADS', ) def __str__(self): return self.name is_default = models.BooleanField( verbose_name=_('default'), help_text=_("whether the role is default"), default=False ) locker = models.ForeignKey( to='uploads.Locker', verbose_name=_('locker'), on_delete=models.CASCADE ) permissions = BitField( verbose_name=_('permissions'), help_text=_("permission bit set"), flags=permission_flags, default=default_flags ) REQUIRED_FIELDS = (name, locker) class MemberRole(CoreModel): class Meta: verbose_name = _('member role') default_related_name = 'member_role_set' constraints = [ models.UniqueConstraint( fields=('user', 'role', 'locker'), name='unique_member_role_check' ), ] def __str__(self): return self.role.name role = models.ForeignKey( to='roles.Role', verbose_name=_('role'), on_delete=models.CASCADE ) user = models.ForeignKey( to='users.User', verbose_name=_('user'), on_delete=models.CASCADE ) locker = models.ForeignKey( to='uploads.Locker', verbose_name=_('locker'), on_delete=models.CASCADE ) Members can have multiple Roles of their own, with the through model being MemberRole. So normally, there would be a m2m field on Member through MemberRole. However, I want the role data to persist even after a member is created. Since locker and user are unique identifiers for the member, My model structure is … -
open_note() missing 1 required positional argument: 'docid'
I appreciate that this question has been asked multiple times before, and I have looked at basically all of the answers and the official documentation for django, but I still can not figure out why I am getting the Exception Value of: open_note() missing 1 required positional argument: 'docid'. I am trying to get the page to display the selected document from the database, when it loads it should show the title and the content, along with an edit and delete button (neither of which function yet, but they're not important right now). The request url is http://localhost:8000/notes/open-notes/?docid=1, and it leads to the error mentioned above. If I change my urls.py path to path('open-notes/<int:id>/', views.open_note, name='open-notes'), then the error I get instead is Reverse for 'open-notes' with no arguments not found. 1 pattern(s) tried: ['notes/open\\-notes/(?P<id>[0-9]+)/$'] which I assume is because the id isn't actually an int and needs converting in the views.py, or I need to use a different converter in the urls.py. Or equally entirely possible, I've misunderstood the other answers in which case I apologise for asking the same question that already has an answer I should be able to implement. I am relatively new to django and … -
How to use for loop counter with a nested if loop?
I created a for loop with a nested if statement for counting specific types of customers in my Django project. What I need is the final number of the for loop counter. I try: {% if forloop.last %} {{ forloop.counter }} {% endif %} But it displays nothing. But when try just {{ forloop.counter }} it displays 2 number. One of them is what I want but the other one is all for loops I think. How can I solve this problem? list.html {% for customer in customer_list %} {% if customer.country.country_name == country %} {% if customer.risk_rating == "Low Risk" %} {% if forloop.last %} {{ forloop.counter }} {% endif %} {% endif %} {% endif %} {% endfor %} views.py def test_customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company) countries = Customer.objects.values_list('country__country_name', flat=True).distinct() country_links = Country.objects.filter() context = { 'customer_list': customer_list, 'countries': countries, 'country_links': country_links } return render(request, 'test.html', context) -
NoReverseMatch error on password reset. The error only occurs on remote server and NOT on the local server
I am getting the following error when trying to reset a password. The error occurs only on the remote server (i.e. heroku). I can change the password just fine in my local server. Reverse for 'password_reset_confirm' with keyword arguments '{'uidb64': 'MTI', 'token': 'ak0pf1-d978cc8242a65cef3803f25c240c6996'}' not found. 1 pattern(s) tried: ['user_accounts/reset/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] from urls.py url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html'), name='password_reset_confirm'), What exactly could be causing this? If the problem is in the code then how come I can reset the password in my local environment. I am bit confused here, any help will be appreciated. -
How can I resolve this type error in my project blogpost object not iterable?
This is my views.py. I suspect that i need to create a another model to handle entries. But which i think will not neccesary. from django.shortcuts import render, redirect from . models import BlogPost def index(request): return render(request, 'blogs/index.html') def posts(request): '''displays all blogs''' all_posts = BlogPost.objects.order_by('-date_added') context = { 'posts': all_posts } return render(request, 'blogs/all_posts.html', context) def post (request, posts_id): single_post = BlogPost.objects.get(id = posts_id) context = { 'single_post':single_post } return render(request, 'blogs/post.html', context) This is my html file {% extends "blogs/base.html" %} {% block body %} <h1>Posts</h1> {% for posts in single_post %} <h3>{{posts.title}}</h3> <p>{{posts.text}}</p> <p>{{posts.date_added}}</p> {% endfor %} {% endblock body %} and this is my urls.py from django.urls import path from . import views app_name = 'blogs' urlpatterns = [ path('all_posts/<int:posts_id>/', views.post, name = 'post'), path('all_posts/', views.posts, name = 'all_posts'), path('', views.index, name = 'index'), Here is my model definition for the project. The various fields have be defined correctly from django.db import models class BlogPost(models.Model): title = models.CharField(max_length = 150) text = models.TextField() date_added = models.DateField(auto_now=False, auto_now_add=True) def __str__(self): return f'{self.title}' class Meta: db_table = 'Blog_Post' managed = True verbose_name = 'BlogPost' verbose_name_plural = 'BlogPosts' -
Order by for a method in django
I would like to show the top 10 of clients with balance from bigger to smaller. but the prob is that balance is method. class ClientsBalance(models.Model): client = models.OneToOneField('Client', on_delete=models.CASCADE,related_name='Client') def inputs(self): total = self.client.invoice_set.aggregate(sum=Sum('total_general')) return round(total[("sum")] or 0, 2) def outputs(self): total = self.client.clientpayment_set.aggregate(sum=Sum('total_paid')) return round(total[("sum")] or 0, 2) def balance(self): return self.outputs() - self.inputs() def Dashboard(request): clientsbalances = clientsbalance_set.all()[:10] context = {'clientsbalances': clientsbalances} return render(request, 'dashboard.html', context) -
Django class based views- handle redirect to the same view, add new context
After POST request I want to redirect user to the same view, adding something to the context. I have no idea how to do it. I tried using get_context_data(**kwargs) but I think I don't really understand the concept. If I do not add anything into context I simply redirect to the same view, which sounds dumb but works. Here's my code: (the class is "home.html" view) class FilteredZamTableView(LoginRequiredMixin, SingleTableMixin, FilterView): table_class = ZamTable template_name = 'home.html' paginate_by = 10 filterset_class = ZamFilter def post(self, request, *args, **kwargs): if request.POST.get('accept_zam'): try: ... return redirect('home') except Exception as e_msg: context = self.get_context_data(**kwargs) context['error'] = e_msg return render(response, "home.html", context) I get this error msg at self.get_context_data(**kwargs) django.urls.exceptions.NoReverseMatch: Reverse for 'home' with keyword arguments '{'e_msg': AttributeError("'FilteredZamTableView' object has no attribute 'object_list'")}' not found. 1 pattern(s) tried: ['$'] -
Marshmallow didn't serialize nested one-to-many Django relation
I need to serialize list of Post objects and return it as JSON in Django. For this purpose I use marshmallow. It works fine, except nested Comment model, that not serializing at all: [ { "id": 6, "created_at": "2021-03-22T13:57:24.576260+00:00", "user": { "id": 1, "username": "admin" }, "group": { "title": "Post title", "id": 2, "members": 6 }, "text": "This is post text" } ] And it should be like this: [ { "id": 6, "created_at": "2021-03-22T13:57:24.576260+00:00", "user": { "id": 1, "username": "admin" }, "group": { "title": "Post title", "id": 2, "members": 6 }, "comments": { { "id": 1, "user": { "id": 1, "username": "admin" }, "text": "This is first comment text" }, { "id": 2, "user": { "id": 1, "username": "admin" }, "text": "This is second comment text" } }, "text": "This is post text" } ] Here is a code. Models: class Post(models.Model): text = models.TextField(max_length=1600) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True,) group = models.ForeignKey(Group, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.CharField(max_length=1200) created_at = models.DateTimeField(auto_now_add=True) Marshmellow schema: class CommentSchema(Schema): id = fields.Int() user = fields.Nested(UserSchema) text = fields.Str() class PostSchema(Schema): id = fields.Int() text = fields.Str() created_at = fields.DateTime() user … -
Nepali Date-picker orientation/placement required to top
I'm using NepaliDatepicker from here: https://leapfrogtechnology.github.io/nepali-date-picker/demo/ i attached datepicker placed at the bottom of the popup page. My problem is that the datepicker appears below the screen. when when i reduce zoom only then i see this else not. -
How is the UserAttributeSimilarityValidator supposed to be used in Django?
I am testing a REST API I wrote in Django, but this validator does not work as intended. I read the docs on this, but I need more than a description; I need a working example. I have it defined in settings.py as is the default. # my_app/settings.py AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, ... ] However, when I run the test, I get an unexpected and undesired success. # api/authentication/tests.py body = { 'username': 'frank', 'email': 'frank@example.com', 'password1': 'frank@example.com', 'password2': 'frank@example.com', } response = self.client.post(url, body, format='json')) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) > ./manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_register (api.authentication.tests.AuthTests) Ensure we can register a user and test for validation errors. ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/matt/Repositories/my_app/back-end/api/authentication/tests.py", line 108, in case_password_has_email self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) AssertionError: 201 != 400 ---------------------------------------------------------------------- Ran 1 test in 0.275s FAILED (failures=1) Destroying test database for alias 'default'... Am I missing the point of this validator? Am I just using it wrong? My intended behavior is for a 400 response to be sent with an error message, like the other validators allow for. How do I accomplish this? -
String value for decimal field doesn't throw ValidationError in view but works fine in shell
I created test project to figure this out. Here is the form: class PaymentForm(forms.Form): amount = forms.DecimalField(max_digits=2, decimal_places=2, required=False) Everything works as expected in shell: >>> from testapp.forms import PaymentForm >>> f = PaymentForm({'amount': 'a'}) >>> f.errors {'amount': ['Enter a number.']} >>> f.is_valid() False But if I enter string value in a template and submit the form, it doesn't give any error messages at all and 'it is valid' is being printed. def add_payment(request): if request.method == 'POST': payment_form = PaymentForm(request.POST) if payment_form.is_valid(): print('it is valid') else: payment_form = PaymentForm() return render(request, 'testapp/add.html', {'payment_form': payment_form}) When i make the field required, the form gives the expected 'Enter a number' and the view - 'Required field' error message. Any ideas how to make it work? Is this how django forms supposed to work? Because i couldn't find anything by googling. -
Filter two models django
I have two similar models: class Boat(models.Model) name = models.CharField(max_length=140, help_text="Enter a Boat name") company = models.CharField(max_length=140) time = models.TimeField(auto_now=False, auto_now_add=True, editable=False, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ['-time'] class Car(models.Model) name = models.CharField(max_length=140, help_text="Enter a Boat name") company = models.CharField(max_length=140) time = models.TimeField(auto_now=False, auto_now_add=True, editable=False, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ['-time'] For example, there are 3 objects of the car model: Name Created Nissan Almera 02/2/2020 Renault Logan 01/9/2020 Mitsubishi L200 03/24/2021 and 1 one object of the boat model: Name Created wooden boat 01/01/2021 Is it possible to make a filter that would display the 3 most recently created objects? i.e wooden boat, mitsubishi L200 and renault Logan -
defining all columns in django values just to get foreign key value
I am working on a Django app and I have a model containing about 60 columns with few ForeignKeys For e.g. class Company(models.Model): name = models.CharField(max_length=100) city = models.CharField(max_length=100) address = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) # and many more rows I need to show all data in DataTable. Company.objects.all().values() To get the username from user column, I need to call it as Company.objects.all().values('user__username') But this doesn't makes sense to me, Just to get the username, I will have to define all columns of Company model Company.objects.all().values('name', 'city', 'address', 'user__username') I was already getting 'name', 'city', 'address' with .values() But to get username, I have to define them explicitly. This is okay with small models, but this approach becomes tidious and error-prone with bigger models. I'm sure there must be a better way to do this that I dont know. Any help would be appreciated. -
Django query sets optimization
I am having a function with some filtering logic, and returns certain levels after passing through different validations, however I would like to optimize this code so that I remove duplicates from the querysets. Its not that direct , but it's possible to see the duplicates, how best can I remove the duplicates below : def get_bo_level(self, main_company): shares = BeneficialOwnerShares.objects.filter( parent_company=self, owner_company=main_company) if shares.exists(): return 1 level_one_business = BeneficialOwnerShares.objects.filter( parent_company=self).values_list('owner_company') shares = BeneficialOwnerShares.objects.filter( parent_company__in=level_one_business, owner_company=main_company) if shares.exists(): return 2 parents = BeneficialOwnerShares.objects.filter( owner_company=self ).values_list('parent_company', flat=True) level_three_business = BeneficialOwnerShares.objects.filter( owner_company__in=parents, parent_company=main_company ).first() if level_three_business: return 3 return None -
CORS allowing jsonplaceholder
I'm learning vue and I'm experimenting with API calls with axios to my local django server. Therefore I encountered CORS errors. I already know how CORS works and why it is blocking my calls, however when I try to send a call to this fake API for testing, it works flawlessly. How is cors allowing it? Here's an example code: axios.get('https://localhost:8000/api/posts') .then( () => console.log('Local server working :)')) axios.get('https://jsonplaceholder.typicode.com/todos') .then( () => console.log('Fake api working :)')) Result: -
How retrieve Discord messages to my website?
I currently have a Python/Django platform and a Discord community. I would like to get the messages of a channel to convert them into notifications on the site. Obviously I consulted the Discord doc but I really have trouble understanding. I don't want to create a bot for this simple action, in principle by using the OAuth app with the "messages.read" scopes it would be possible. I can generate my token now: def discord_get_token(): data = { 'client_id':DISCORD_CLIENT_ID, 'client_secret':DISCORD_PRIVATE_KEY, 'grant_type': 'client_credentials', 'redirect_uri': 'http://127.0.0.1:8000', 'scope': 'identify connections messages.read' } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } r = requests.post('%s/oauth2/token' % DISCORD_BASE_URI, data=data, headers=headers) r.raise_for_status() #Token print(r.json()['access_token']) return r.json()['access_token'] Then the call to the messages with the following route /channels/{channel.id}/messages : def get_channel_messages(id_channel): route = "/channels/"+ str(id_channel) +"/messages" data,error_message = request_discord('GET',route) print(data) def request_discord(method,url_access,body={}): data ='' #Call token error_message = '' access_token = discord_get_token() #Call request headers = {'Content-Type':'application/json','Authorization':'bearer ' + access_token} body = body if method=="GET": result = requests.get(DISCORD_BASE_URI + url_access, headers=headers,data=body) else: result = requests.post(DISCORD_BASE_URI + url_access, headers=headers,data=body) #Check result if result.status_code != 200 and result.status_code != 201: error_message = "Impossible de d'obtenir un resultat erreur: " + str(result.status_code) else: data = result.json() return data,error_message A 401 error is returned. Unlike …