Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
How can I make a field readonly after sending a Post Request in Django?
How can I make the start_date readonly after the Question is created? I have tried modifying the admin.py file but the date field is still editable, I got no idea how to can solve that This is the Question model class Question(models.Model): poll_question = models.CharField(max_length=255, blank=False) title = models.CharField(max_length=255, blank=True) start_date = models.DateTimeField('date published', blank=False,) def __str__(self): return self.poll_question def choices(self): if not hasattr(self, '_choices'): self._choices = self.choice_set.all() return self._choices This is the code I added in the admin.py file in order to make the start_date readonly after creation but there is still no change. class DateAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if obj: return self.readonly_fields + ('start_date') else: return [] -
how to make a profile page in django with the information availiable in django allauth module?
I want to make a url as account/profile and add some form to make change for the user information. I have tiried avatar module but it didnot work. -
django.db.utils.OperationalError: no such table: quiz_gradingmodel
This occurred after running python manage.py makemigrations after a new model known as "gradingmodel" was added into models.py ---What I did before running makemigrations--- db.sqlite3 was deleted. migrations file was deleted. relevant pycache file was deleted. PS: after commenting out the newly added model, makemigrations seems to work, I'm not sure why this is happening. Any suggestions/ideas would be greatly appreciated :) -
Correct way to display images in ReactJS from Django static files
I am building an app using ReactJS, Django, Heroku and as my storage I am using Amazon S3. When I run python manage.py collectstatic everything works as it should. All my static files are uploaded to my bucket. However, until now, in my ReactJS code I had been referring to my static images this way: <img className={"some-class"} src={"staticfiles/images/image.png"}/> And, of course, on my local host this would work. However, this line will always try to load the asset from my local storage. What would be the correct way to refer to my S3 bucket files on production and keep refering to local storage when in development? These are my settings for production: # ... all the keys and etc. are there. AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 public media settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'myApp.storage_backends.PublicMediaStorage' And this is for my local development: STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') .. and of course at the end: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] My .css files are correctly being loaded from the S3 bucket. However, I … -
ORA-00001: unique constraint DJANGO ORACLE
By Sql Developer, I made an insert into and in my page django shows it correctly, but when I enter another value through the page, I get the error that the id already exists, because the record was entered from the developer not from django, how can I fix this? to do a bulk upload from developer? -
(DJANGO-ALLAUTH) Select a valid choice. google is not one of the available choices
I want to add a social app provider though Django admin/socialaccount/socialapp/add/. I keep getting the error below: Even though I have already specified the app provide in the settings.py as followed: SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'offline', } } } Having followed all the required steps in the docs, obtained client id and secret key https://django-allauth.readthedocs.io/en/latest/providers.html#google and I also have refreshed, cleared cache, run makemigrations and migrate many times but the field won't show 'google' as the option. Could you show me the way to solve this? Thank you! -
ValueError at /success Invalid address in django EmailMultiAlternatives
I want sent to multiple email but i got this raise ValueError('Invalid address "%s"' % addr) ValueError: Invalid address "['ex1@gmail.com', 'ex2@gmail.com', 'ex404@gmail.com']" email_id = ["ex1@gmail.com","ex2@gmail.com","ex404@gmail.com"] username = name email = email_id ######################### mail system #################################### htmly = get_template('email/Email.html') d = { 's_id' : s_id, 'username': username, 'tran_id' : tran_id, 'amount' : amount } subject, from_email, to = 'welcome', 'your_email@gmail.com', email html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() -
Django query orderby
I'm trying to create a queryset in Django. My queries continue in the following order. But it doesn't implement the order_by operation. What is the problem? The first two queries are working all_products = Product.objects.filter(category=category.id) all_products = all_products.filter(price__gte=100) all_products = all_products.order_by('price') -
Can you select all exists in django?
I have been building an access manager to police API interactions in my application. I have a model which represents a User having Access to a given model instance, it looks like: class Permission(models.Model): user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') The access manager is aware of model hierarchies and can figure out that if you're trying to view or modify a given object type with a given ID, that it can check if you have permissions on it, or on a parent entity in the tree. It builds up Q objects, and hits the database asking if a relevant permission exists for the user. I have come to a new use case, where a particular entity has 2 parents in the tree, and I need the access manager to check that the user has permissions somewhere one both sides of the tree. Here is a (sanitised) Q object that I thought is what I needed: <Q: (AND: (OR: (AND: ('content_type', <ContentType: myapp | foo>), ('object_id', 676)), (AND: ('content_type', <ContentType: myapp | bar>), ('object_id', 634)), (AND: ('content_type', <ContentType: myapp | wibble>), ('object_id', 1)) ), (OR: (AND: ('content_type', <ContentType: myapp | foo>), ('object_id', 2)), … -
Adding a `unique_on` constraint to an annotation filter in Django
In Django, how do you use the filter attribute of the Sum() annotation to only calculate SUM on attributes which belong to a unique model? In the codeblock below, how can roi_avg be filtered in a way that I can describe only in this pseudocode: roi_avg = Sum(avg_field, filter= tweets_we_need + Q(tweets__twitter_calls__coin__id==Unique) avg_field = F('tweets__twitter_calls__roi_plus_year') tweets_we_need = (Q(tweets__created_at__date__lt=one_year_back) & ~Q(tweets__twitter_calls__roi_plus_year=None)) users = ( User.objects .annotate( roi_avg = Sum(avg_field, filter= tweets_we_need), calls_count = Count('tweets', filter = tweets_we_need), unique_coins = Count('tweets__twitter_calls__coin', filter = tweets_we_need, distinct=True) ) .exclude(roi_avg=None) .order_by("-roi_avg", "-unique_coins") ) -
Django - Combining Urls from different apps
I am fairly new to Django and I had a question regarding how to manage multiple django apps. I have an app that deals with user accounts which shows the profile page and dashboard of the user. However, I have another app called blogs where I want to show the blogs written by that user. What I basically want is to have a separate tab in the navbar that says "blogs" and when you click on the blogs it should go to the url "localhost:8000/user/blogs" not just localhost:8000/blogs. How can I go about combining the two apps in such a way? -
Django deployed on Heroku in admin gives error 500
I'm very new to python. I've deployed my beginners Django app to Heroku. Its my tutorial project. I this project I have Students, Group, Teachers app. Models are connected somehow. So there is only CRUD class-based view. When Im entering admin page its only Group is working and showing list of objects. Teachers and Group gives 500error. Through application home page everything works properly. -
How can I setup html template to render my views and OneToOne models in Django?
I am new to Django and I am building a practice project for my portfolio. I have 2 models in Django which will be accessed by users/supervisors and also overall views by admins/superusers. class Vacation(models.Model): vacation_id = models.AutoField(primary_key=True) request_date = models.DateField(auto_now_add=True) requestor = models.ForeignKey("Employee",on_delete=models.SET_NULL,null=True) start_date = models.DateField(null=True) end_date = models.DateField(null=True) objects = models.Manager() def __str__(self): return (f"{self.vacation_id}") pass class VacationApproval(models.Model): is_approved = models.BooleanField(default=False) approved_by = models.ForeignKey(Supervisor,on_delete=models.SET_NULL,blank=True,null=True) approved_date = models.DateField(null=True, blank=True) team = models.CharField(choices=TEAM_CHOICES, max_length=255) vacation_id = models.OneToOneField("Vacation",on_delete=models.CASCADE,null=True) objects=models.Manager() I am trying to render the approval onto an HTML template. <thead> <tr> <th>Vacation ID</th> <th>Request Date</th> <th>Requestor</th> <th>Start Date</th> <th>End Date</th> <th>Status</th> <th>Approved Date</th> </tr> </thead> <tbody> {% for vacation in vacations %} <tr> <td>{{ vacation.vacation_id}}</td> <td>{{ vacation.request_date }}</td> <td>{{ vacation.requestor }}</td> <td>{{ vacation.start_date }}</td> <td>{{ vacation.end_date }}</td> <td><span class="tag tag-success">{{ vacation.vacation_id.vacation_approvals.is_approved }}</span></td> <td>{{ approval.approved_date }}</td> </tr> {% endfor %} My view below will assign the models for rendering within my html template class VacationListView(ListView): template_name = "vacation_list.html" context_object_name='vacations' def get_queryset(self): user = self.request.user if user.is_superuser: queryset = Vacation.objects.all() print("Superuser") print(queryset) else: queryset = Vacation.objects.filter( requestor=user ) return queryset def get_context_data(self, **kwargs): user = self.request.user context = super(VacationListView,self).get_context_data(**kwargs) if user.is_organizer: queryset = VacationApproval.objects.filter( organization=user.userprofile, ) context['vacation_approvals'] = VacationApproval.objects.all() print(context) return context