Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is plotly failing to load in django project?
I am using Plotly.react() function to render a graph on my template HTML file. In the function, I am passing in the id for the HTML element where I want the graph to render, data for both x&y axis, plot type, and layout information. Excerpt from my code: var metricsOneGraphDiv = document.getElementById('metricsOne'); var metricsOneTraces = [{ x: {{rmabRisks.dates|safe}}, y: {{rmabRisks.counts}}, type: 'scatter', }] var metricsOneLayout = {{rmabRisksLayout | safe}} Plotly.react(metricsOneGraphDiv, metricsOneTraces, metricsOneLayout); I get the following error from the Firefox console when I try loading this view Loading failed for the <script> with source https://cdn.plot.ly/plotly-latest.min.js. I have tried to reinstall plotly, however, I get stuck waiting for the pip install to complete. Can someone please suggest a possible solution? Thanks in advance -
The page does not display information about created links in the admin panel. Django
The page should display a feedback form and links created in the admin panel. Created models: from django.db import models class ContactModel(models.Model): # feedback form name = models.CharField(max_length=50) email = models.EmailField() website = models.URLField() message = models.TextField(max_length=5000) create_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.name} - {self.email}' class ContactLink(models.Model): # links icon = models.FileField(upload_to='icons/') name = models.CharField(max_length=200) def __str__(self): return self.name I connected the models to the admin panel: from django.contrib import admin from .models import ContactModel, ContactLink @admin.register(ContactModel) class ContactModelAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'email', 'create_at'] list_display_links = ('name',) admin.site.register(ContactLink) Everything works correctly, you can create links in the admin panel. Below views.py: from django.shortcuts import render from django.views import View from .models import ContactLink class ContactView(View): def get(self, request): contacts = ContactLink.objects.all() form = ContactForm() return render(request, 'contact/contact.html', {'contact': contacts, 'form': form}) urls.py: from django.urls import path from . import views urlpatterns = [ path('contact/', views.ContactView.as_view(), name='contact'), path('feedback/', views.CreateContact.as_view(), name='feedback'), ] I go through the for loop through the code to return links from the admin panel: #links <div class="contact__widget"> <ul> {% for contact in contacts %} <li> <img src="{{ contact.icon.url }}"> <span>{{ contact.name }}</span> </li> {% endfor %} </ul> </div> #feedback form <form action="{% url 'feedback' %}" method="post"> … -
MultiValueDictKeyError at /homepage/detail when trying to query database with django
I understand from other posts that MultiValueDictKeyError is related to whatever is in the .html file isn't reaching the database. I haven't found a specific solution that seems to work for me though. Here is the views.py: def detail(request): try: if request.method == 'POST': name = request.POST['name'] state = request.POST['state'] tm = TM.objects.filter(Name__icontains=name, State__icontains = state) return render(request, 'homepage/detail.html', {'name': name, 'state' : state, 'tm': tm}) else: return render(request, 'homepage/detail.html', {}) except TM.DoesNotExist: raise Http404("Info Does Not Exist") Here is the detail.html: <html> <head> <title>Territorial</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> {% load static %} <link rel="stylesheet" href="{% static 'html5up-read-only/assets/css/main.css' %}" /> {% load static %} <link rel="stylesheet" href="{% static 'html5up-read-only/assets/css/detail.css' %}" /> </head> <body class="is-preload"> <h2>Territory Managers</h2> {% if name %} {{ name }} {{ state }} {% else %} <h3> No results </h3> {% endif %} and here is the models.py: class TM(models.Model): #Change this to territory manager and delete database and recreate Name = models.CharField(max_length = 200,null=True) Cell = models.CharField(max_length= 200, null=True) EmailAddress = models.EmailField(null=True) Notes = models.CharField(max_length=500, null=True) Distributor = models.CharField(max_length=200,null=True) State = models.CharField(max_length=200,null=True) Brand = models.CharField(max_length=200,null=True) def __str__(self): try: if self.Distributor is not NullBooleanField: return self.Name + ' - ' + self.Distributor … -
I have created model form using django. The form isnt saving on submit though. The page keeps displaying the invalid form page
index.html <div class="container add_dog_form"> <form method="POST"> {% csrf_token %} <div class="row" id="namefield"> {{ form.as_table }} </div> <div class="row"> <button type="Submit" id="form_submit">Submit</button> </div> </form> </div> forms.py class DogForm(forms.ModelForm): class Meta: model = Dog fields = ['name', 'dog_pic'] views.py class IndexView(generic.ListView): template_name = "takyi1/index.html" context_object_name = "dogs_context" dog_form = DogForm def get_context_data(self, **kwargs): self.dogs_context = super().get_context_data(**kwargs) self.dogs_context['dogs'] = self.dog self.dogs_context['form'] = self.dog_form return self.dogs_context def post(self, request, *args, **kwargs): form = self.dog_form(request.POST) if form.is_valid(): form.save() return HttpResponse('Valid Form') else: return HttpResponse('inValid Form') -
Django template tags in HTML
I am trying to point an image source to a filepath tag I have specified in my views.py, but for some reason it won't load in the project index file, but will in the specific projects pages. And all my other tags on the same page work, so Am unsure what I am doing wrong? <img src="{{ filepath }}" class="card-img-top" alt="Project Image"> Appears in the page as <img src="" class="card-img-top" alt="Project Image"> which shows the alt text. Views.py filepath = "/static/img/" + project.title + ".png" -
cannot retrieve values from database django
I have a table I am trying to retrieve values from. It has two foreign keys and that is it. I use get_or_create on the table and create an object. I verify with the admin panel that the object is there. Then, I try to retrieve it but I do not get the values even though I can see them in the admin panel. Here is the table: class req(models.Model): to = models.ForeignKey(User,on_delete=models.CASCADE) from = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return "request sent" In the piece of code below, what I retrieve I try to display it as it is in the p tag and also I tried doing req.to and req.from.first_name but in vain, I did not see any values. def get(self, request): u = get_user(request) try: my_requests = req.objects.get(from=u) except req.DoesNotExist: fr = None if fr == None: return redirect(reverse('dogpark:index')) if my_requests != False: context_dict['req'] = my_requests return render(request, 'myapp/req.html', context=context_dict) Can anybody see the problem that I cannot and comment ? -
pytest parametrize is deleting my fixturedata after first parametrize value
I have two fixtures: @pytest.fixture def all_users(): all_existing_group_names = Group.objects.all().values_list( "name", flat=True ) tmp_list = [] for group_name in all_existing_group_names: user = User.objects.create(username=f"user-{group_name}", password=group_name) group = Group.objects.get(name=group_name) user.groups.add(group) tmp_list.append(user) return tmp_list and @pytest.fixture def admin_user(all_users): User.objects.all() # is empty the second time return all_users And this is how my test looks like Class TestSomething: @pytest.mark.parametrize('first_val, second_val', [('test', 'test'), ('test2', 'test2'),..]) @pytest.mark.django_db(transaction=True) def test_something(self, all_users, first_val, second_val): ... In my test i am deleting some model instances through a post request(which in the view is wrapped with a transaction.atomic request). This is why i need transaction=True, because the deleted objects need to be there again when the second run of parametrize runs. Now, my problem is that if i use transaction=True, on the second run it will revisit my fixtures but now suddenly my database is empty, the Groups.objects.all() method doesn't return anything at all. If i switch back to transaction=False, it works but this way i have a problem because my post request deleted stuff that i need for the next parametrize run. What am i doing wrong? I don't get it :( ughhh -
Django Rest Framework - Write an explicit `.update()` method for serializer
I'm trying to make a put request using DRF but this error appears: AssertionError: The `.update()` method does not support writable dotted-source fields by default. Write an explicit `.update()` method for serializer `model.serializers.ModelSerializer`, or set `read_only=True` on dotted-source serializer fields. This is the view: class Model(GenericAPIView): def put(self, request, pk): model = MyModel.objects.filter(id=pk).first() serializer = ModelSerializer(model, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is the serializer: class ModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' def update(self, instance, validated_data): status = validated_data.pop('status', None) model = super().update(instance, validated_data) if status: model.set_status(status) model.save() return model What is wrong with the update() method? Also, how can I only update one field of the object? -
Django: is there something like an id of a queryset?
I am looking for something that I can use to have the value of a queryset. This would be the replacement of the use of filters like this: # Normal myquerysetA = Model.objects.filter(name="John",age=20) # Value i wanna query_id = myquerysetA.query_id() # Equivalent myquerysetB = Model.objects.filter(query_id=77777) myquerysetB == myquerysetA True -
Кнопка "Вернуться назад" со всеми заполненными параметрами формы Django
При ошибке на стороне сервера после отправки формы должна выходить страница с ошибкой и кнопкой вернуться назад. Если нажать на кнопку, то произойдёт редирект на страницу формы, и поля формы должны быть заполнены также, как до первой отправки. Не совсем понимаю, как это реализовать. Сохранение полей формы можно реализовать через request.session, но как их вывести? -
I have two images in the same static folder. Why is Django only rendering one of them?
I am trying to create a carousel on my homepage in my Django Project. Carousel code in base.html: {% load static %} <!doctype html> <html lang="en"> (irrelevant header and navbar code here) <div id="carouselHomepage" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselHomepage" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselHomepage" data-bs-slide-to="1" aria-label="Slide 2"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{% static '/shirts.png' %}" class="d-block w-100" alt=""> </div> <div class="carousel-item"> <img src="{% static '/banner.png' %}" class="d-block w-100" alt=""> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselHomepage" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previouss</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselHomepage" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Nexts</span> </button> </div> (irrelevant body and jquery scripts here) </html> Note I have loaded static at the top of the file. The images banner.png and shirts.png are both in my app/static folder. The banner.png image is loading fine, but the shirts.png doesn't load and I see an error in my project terminal in VS Code: "GET /static/shirts.png HTTP/1.1" 404 1789 I can't figure out what this 1789 error means. There are a few other images in my static folder, and I get this error when trying to include any picture other than banner.png, which is giving no issues and loading … -
I'm trying to connect Django with Mysql but 'm getting an error 'list' object has no attribute '_default_manager'
Views.py file from django.shortcuts import render from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView from .models import News_Post,Category from .forms import addArticleForm,updateArticleForm from django.template import loader from django.urls import reverse_lazy import mysql.connector # Create your views here. mydb = mysql.connector.connect( host="localhost", user="root", password="goodboy123", database = "nexus360" ) cursor = mydb.cursor() # -- Display all the news on the homePage according to the latest date -- # class HomeView(ListView): cursor.execute("select * from news_post") model = cursor.fetchall() template_name='home.html' ordering=['-date'] def get_context_data(self,*args,**kwargs): cursor.execute("select * from category") category_menu= cursor.fetchall() context=super(HomeView,self).get_context_data(*args,**kwargs) context["category_menu"]=category_menu print(context) return context Models.py Here is the models.py file but I don't think this file is required. I'm new to Django and don't have much idea from django.db import models from django.contrib.auth.models import User from django.urls import reverse import datetime from ckeditor.fields import RichTextField #---------Creating the tables-------# #---------Category Table---------# class Category(models.Model): name=models.CharField(max_length=30) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') # -----UserAccount Table-----# class UserAccount (models.Model): user_id=models.CharField(max_length=100, null=False , primary_key=True) email=models.EmailField(null=True) contact_no=models.CharField(max_length=13) password=models.CharField(max_length=100) # -----Table column of news articles class News_Post(models.Model): title=models.CharField(max_length=100) # News_content=models.TextField() News_content=RichTextField(blank=True,null=True) date=models.DateField(default='DEFAULT VALUE') #post_date=models.DateField(auto_now_add=True) author=models.ForeignKey(User,on_delete=models.CASCADE) category=models.CharField(max_length=30,default='Politics') def __str__(self): return self.title + ' | '+ str(self.author) def get_absolute_url(self): return reverse('home') **urls.py ** Here is the Urls.py file from django.urls import path from .views import … -
django admin error when adding element to a table (Please correct the errors below)
I've spend the whole day on an error tell by django admin = Please correct the error bellow) when saving data The thing is i don't get any other indication about the error and i have no idea how to solve the problem models.py class meeting(models.Model): time = models.DateTimeField() capacity = models.CharField(max_length=25, default=0) USERNAME_FIELD = 'time' REQUIRED_FIELDS = ['time'] admin.py class MeetingAdmin(BaseUserAdmin): list_display = ('time', 'capacity') list_filter = ('time', 'capacity') fieldsets = ( (None, {'fields': ('time', 'capacity')}), ) add_fieldsets = ( (None, { 'classes': ('time', 'capacity'), 'fields': ('time', 'capacity'), }), ) search_fields = ('time',) ordering = ('time',) filter_horizontal = () admin.site.register(User, UserAdmin) admin.site.register(meeting, MeetingAdmin) -
Angular Django app cache not being cleared?
we have a really weird problem going on. We are developing an app that uses Angular on the frontend and Django on the backend, and we did extensive testing, with our team and an external QA team pick the app apart. So we are sure this should work. This week our clients started their client testing, and the client is reporting that the app is not working as expected. Basically, it wouldn't load the dynamic edit-user/:id/ route, and the app would be 'stuck'. (Additionally, some API calls that would retrieve dates return null). We thought it might be a caching problem (because the app wasn't working with dynamic data before we've added the HashLocationStrategy to represent the URL) so we connected to the clients PC and tried to clear the cache. Didn't work. The client also reported the same issue on Safari, Chrome and Firefox (Client uses a Mac machine), and also their iPad. Could it be a network caching issue? Then I built a new version with the package versioning inside the app to make sure we have the same version but it still behaves like that. (gets stuck on dynamic routes) This is quite a complicated issue because … -
Swedish BankID Python Animated QR code generation with hmac
I'm developing a Django project that will use BankID for authorization and digitally sign. I am using pybankid, and I have nothing but nice things to say about that project. My problem lies with trying to use the code provided by bankIDs documentation. QRCode Docs import hashlib import hmac import time qr_start_token = rp_response["qrStartToken"] # "67df3917-fa0d-44e5-b327-edcc928297f8" qr_start_secret = rp_response["qrStartSecret"] # "d28db9a7-4cde-429e-a983-359be676944c" order_time = time.time() # (The time in seconds when the response from the BankID service was delivered) qr_time = str(int(time.time() - order_time)) # ("0" or another string with a higher number depending on order_time and current time) qr_auth_code = hmac.new(qr_start_secret, qr_time, hashlib.sha256).hexdigest() # "dc69358e712458a66a7525beef148ae8526b1c71610eff2c16cdffb4cdac9bf8" (qr_time="0") # "949d559bf23403952a94d103e67743126381eda00f0b3cbddbf7c96b1adcbce2" (qr_time="1") # "a9e5ec59cb4eee4ef4117150abc58fad7a85439a6a96ccbecc3668b41795b3f3" (qr_time="2") # (64 chars hex) qr_data = str.join(".", "bankid", qr_start_token, qr_time, qr_auth_code) # "bankid.67df3917-fa0d-44e5-b327-edcc928297f8.0.dc69358e712458a66a7525beef148ae8526b1c71610eff2c16cdffb4cdac9bf8" (qr_time="0") # "bankid.67df3917-fa0d-44e5-b327-edcc928297f8.1.949d559bf23403952a94d103e67743126381eda00f0b3cbddbf7c96b1adcbce2" (qr_time="1") # "bankid.67df3917-fa0d-44e5-b327-edcc928297f8.2.a9e5ec59cb4eee4ef4117150abc58fad7a85439a6a96ccbecc3668b41795b3f3" (qr_time="2") I get TypeError: key: expected bytes or bytearray, but got 'str', when I try to convert qr_start_secret to bytes I get Unicode-objects must be encoded before hashing. I'm at a loss. Does anyone have any ideas? -
How to retrieve individual Item using DRF
I want to display product detail page using drf but I keep running into one error after another. urls.py path('product/id>', views.product_detail_view.as_view(), name='product-detail'), models.py class Product(models.Model): categories = models.ManyToManyField(Category) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="product_owner") item = models.CharField(max_length=150) slug = models.SlugField(max_length=255, blank=True, null=True) brand = models.CharField(max_length=255, default="brand") image = models.ImageField(upload_to="images/products/") label = models.CharField(max_length=254, default='', blank=True, null=True) serializers.py class product_detail_serializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() class Meta: model = Product fields = ("id", "categories", "item", "slug", "image") lookup_field = "id" views.py class product_detail_view(generics.RetrieveAPIView): serializer_class = product_detail_serializer lookup_field = "id" I want to know what I did not do properly here -
Test Multiple HTML Templates To Make Sure They Return 200
I have 100s of HTML Templates that I have to test and don't know how to test each individual one to make sure that they load properly. I assume i would use a for loop through my project urls.py but when I do this i get the following error: AttributeError: 'URLResolver' object has no attribute 'name' from django.test import SimpleTestCase, TestCase, Client from django.test.utils import setup_test_environment from django.urls import reverse, URLPattern from django.conf import settings import importlib from foo.urls import urlpatterns # Create your tests here. class LoginTest(SimpleTestCase): def login_view_test(self): client = Client() for url in urlpatterns: response = client.get(reverse(url.name)) self.assertEqual(response.status_code, 200) print(str(reverse(url.name)) + " Status Code:" + str(response.status_code)) For some reason the code says that the URLResolver has no name attribute, I feel this error is it telling me I need to look in a different location for the name to reverse I just don't know where to look. -
Django: Add a unique index on expressions in postgres
Consider the django model - class Students(models.Model) id = models.BigAutoField(primary_key=True) scoreA = models.CharField(null=True, max_length=15) scoreB = models.CharField(null=True, max_length=15) I'm looking to add this unique index. create unique index unq_idx on students ((case when scoreA is not NULL then scoreA else '' end), (case when scoreB is not NULL then scoreB else '' end)); How do I add it through the django ORM ? I'm using Django 3.1 with postgres 12.1 The use-case is to have a unique constraint over the two fields which doesn't allow multiple NULL values (Link) -
Django returning case sensitive results despite correct database collation and use of icontains
I have the following DRF view: class DictionaryFuzzyView(generics.ListAPIView): queryset = Dictionary.objects.filter(disabled=False,).order_by(Length('simplified').asc()) serializer_class = FuzzySerializer filter_backends = (filters.DjangoFilterBackend, OrderingFilter) pagination_class = LimitOffsetPagination ordering_fields = ['id'] filter_class = FuzzyFilter FuzzyFilter looks like this: class FuzzyFilter(filters.FilterSet): simplified = filters.CharFilter(field_name='simplified', lookup_expr='contains') traditional = filters.CharFilter(field_name='traditional', lookup_expr='contains') pinyin_marks = filters.CharFilter(field_name='pinyin_marks', lookup_expr='contains') translation = filters.CharFilter(field_name='translation', lookup_expr='icontains') frequency = filters.CharFilter(field_name='frequency', lookup_expr='exact') hsk = NumberInFilter(field_name='level', lookup_expr='in') And I do a call like this: http://127.0.0.1:8000/api/v1/fuzzy/?translation=One I'll only get results that contain "One", never results that contain "one", and vice versa. I am using MySQL as my database engine, but as far as I can tell, my collations are correct for case insensitive searching: I am on Django 3.x. What could possibly be causing it/what's the best method to resolve/troubleshoot this? -
django-mptt traversetree children is empty
I am using Django 3.2 and django-mppt 0.13.4 This is my (simplified) model: /path/to/myapp/models.py class Comment(MPTTModel, MyTimestampedModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') content = models.TextField(default='') markdown_content = models.TextField(default='') attachment = models.ImageField() class MPTTMeta: order_insertion_by = ['created_at'] class Meta: permissions = [('can_moderate_comments', 'Can moderate comments'), ('can_attach_file', 'Can attach file'),] class Commentable(models.Model, Foo): accept_comments = models.BooleanField(default=True, blank=True) comments = GenericRelation(Comment) # ... other fields class Article(Commentable, FooBar): pass /path/to/myapp/views.py class ArticleDetailView(DetailView): model = Article def get_context_data(self, **kwargs): context = super(ArticleDetailView, self).get_context_data(**kwargs) article = self.get_object() # .... context['comments'] = article.comments.all() From the mptt documentation <ul class="root"> {% recursetree nodes %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> /path/to/myapp/templates/myapp/article_detail.html {% recursetree comments %} <li> {{ node.markdown_content }} {% if not node.is_leaf_node %} {{node.get_descendant_count}} Replies <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} I add three comments to the database (via the shell command), with the following heirarchical relation: Comment 1 (id=1) Reply To Comment 1 (id=3) Reply To Reply to Comment 1 (id=4) Comment 2 (id=2) When I type the following at the command prompt: Comment.objects.filter(id=1).get_children() => 1 Comment.objects.filter(id=1).get_descendent_count() => 2 … -
How to upload files to db instead root directory?
I have a project in django, i am trying to upload files by an API and save those files in my db but the files are saved in my db and on my ROOT DIRECTORY and i don't want that. POSTMAN API, i select a file, in this case i select "ejemplobionario.txt" Then i go to Visual Studio Code and the file "ejemplobinario.txt" is there I don't want it to be in my root directory, i just want it to be inside database. Please help me! serializers.py class FileSerializer(serializers.ModelSerializer): class Meta(): model = File fields = ('file', 'remark', 'timestamp') models.py class File(models.Model): file = models.FileField(blank=False, null=False) remark = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) views.py class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django Admin error : Please correct the errors below
I've setup a sqlite database using django for meeting managment (there is two fields : time and capacity) When i try to add a meeting in django admin, i get the error Please correct the errors below. ( There is nothing bellow ) Here is my model.py class Custom_meeting(BaseUserManager): def create_meeting(self, times, capacity): if not times: raise ValueError(_('The times must be set')) meeting = self.create_meeting( time=times, capacity=capacity ) meeting.save() return meeting class meeting(models.Model): time = models.DateTimeField(primary_key=True, blank=False) capacity = models.CharField(max_length=25, default=0) USERNAME_FIELD = 'time' REQUIRED_FIELDS = ['time'] objects = Custom_meeting() and this is my admin.py class MeetingAdmin(BaseUserAdmin): list_display = ('time', 'capacity') list_filter = ('time', 'capacity') fieldsets = ( (None, {'fields': ('time', 'capacity')}), ) add_fieldsets = ( (None, { 'classes': ('time', 'capacity'), 'fields': ('time', 'capacity'), }), ) search_fields = ('time',) ordering = ('time',) filter_horizontal = () admin.site.register(User, UserAdmin) admin.site.register(meeting, MeetingAdmin) -
Django-filter how to show only some objects on dropdown?
My site simply works like this: every Manager can have some SubManagers, those SubManagers can have some Agents (so the Agents are indirectly related to the Manager, see models.py to understand better the relations between them). I want to show in the Manager's profile page (see views.py) all the MembershipCard created by his/her related Agents. I'm trying to implement a filter to search, for example, cards created by a specific Agent, i'm able to do this but i would like to show in the dropdown only the Agents related to the Manager, the dropdown list now shows all Agents in the database models.py class StandardProfile(models.Model): name = models.CharField(max_length=200, null=True) surname = models.CharField(max_length=200, null=True) phone_number = models.CharField(max_length=200, null=True) class Meta: abstract = True class Manager(StandardProfile): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) class SubManager(StandardProfile): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) manager = models.ForeignKey(Capo, null=True, on_delete = models.SET_NULL) class Agent(StandardProfile): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) manager = models.ForeignKey(Manager, null=True, on_delete = models.SET_NULL) subManager = models.ForeignKey(SubManager, null=True, blank=True, on_delete = models.SET_NULL) class MembershipCard(models.Model): agent = models.ForeignKey(Agent, null=True,blank=True, on_delete = models.SET_NULL) client = models.ForeignKey(Client, null=True,blank=True, on_delete = models.SET_NULL) creation_date = models.DateTimeField(auto_now_add=True, null=True) activation_date = models.DateTimeField(null=True,blank=True) expiration_date = models.DateTimeField(null=True,blank=True) views.py @login_required(login_url='login') def profilePage(request, pk): #www.mysite.com/profilePage/<pk> user = User.objects.get(id=pk) … -
Best Python framework for event driven microservices
I want to build a simple system consisting of a few microservices to present patterns of this architecture in my thesis. Each service will have only one instance and I'll use docker-compose to run it locally. I'm going to show some auth mechanisms, CQRS and communication via events. Which Python framework would you consider best for this kind of thing, from your experience? I've read that asynchronous frameworks are well suited for microservices, so I'm particularly interested in FastAPI/Celery combo. Aside of that, I'm good at DRF. -
Why is my Selenium selector pulling a dict? (Django/Python 3.8)
I've just updated selenium in my django app on PythonAnywhere. This is my code: from selenium import webdriver def Synonym(): chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") browser = webdriver.Chrome(options=chrome_options) browser.get("https://www.synonym.com/synonyms/test") test = browser.find_element_by_class_name("logo").text browser.quit() return test But it gives me an error: AttributeError: 'dict' object has no attribute 'text' When I grab it without the .text this is what it gives me: {'ELEMENT': '0.3567871003333163-1'} I'm using a paid account and should be able to access any site. Sidenote: is there a way to stop selenium from making /tmp/ files and folders? Thanks!