Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin: two ListFilter Spanning multi-valued relationships
I have a Blog model and a Entry model. Entry has a Foreignkey to Blog: One Blog has several Entries. I have two ListFilters for Blog: One for "Entry title", one for "Entry published year". If you filter for entry_title=Lennon and entry_published_year=2008, then I see all Blogs which have entries an entry with title "Lennon" and an (maybe an other) entry with pub-year=2008. That's not what I want. Related docs: https://docs.djangoproject.com/en/3.2/topics/db/queries/#spanning-multi-valued-relationships This is because django does this: qs = qs.filter(title_filter) qs = qs.filter(published_filter) To get the desired result one need to combine both filter() calls into one. How to get both ListFilter into one filter() call? -
how to use titan.email in django to send email to the users
I got titan.email account when i bough AWS hosting How to use this email account to send email to the users in djago EMAIL_HOST='smtp.titan.email' EMAIL_HOST_USER='admin@test.com' EMAIL_HOST_PASSWORD='password' EMAIL_PORT= 465 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_SSL=True I am getting this error while sending email smtplib.SMTPSenderRefused: (504, b'5.5.2 <webmaster@localhost>: Sender address rejected: need fully-qualified address', 'webmaster@localhost') -
My docker container is not working p option
I tried many times for port forwarding. But, return message is connection refused. using official image is working. but using my image is not working. I did many searching and tried. But all failed. T^T What is my problem.? My docker image is exists in hub.docker.com docker pull redukyo/ubuntu:qf_user Please help me! -
how to receive objects in index.html from admin panel?
all bojects have been successfully save in admin dashboard but do not receive dynamic data in index.html page from admin dasboard. please any one can be help me. **views.py** from django.shortcuts import render from .models import home # Create your views here. def home(request): homeobject = home.objects.all() return render(request, 'index.html', {'homes': homeobject}) **models.py** class home(models.Model): HOME_CATEGORY = [ ('SR', 'Service'), ('VL', 'Vlog'), ('CR', 'course'), ] title = models.CharField(max_length=120) description = models.TextField() image = models.ImageField(upload_to='images') home_category = models.CharField(max_length=2, choices=HOME_CATEGORY) **index.html** {% for home in homes %} {{home}} {% endfor %} -
How to resolve this error - "Attribute Error"? [closed]
When am passing the string into another variable, it is giving me error. Please check below error a = 'Market' prompt1=float(input('Please enter your price: ')) ## Place an order print( alice.place_order(transaction_type = TransactionType.Buy, instrument = enter_strike, quantity = enter_quantity, order_type = OrderType.a, product_type = ProductType.Intraday, price = prompt1, trigger_price = None, stop_loss = None, square_off = None, trailing_sl = None, is_amo = False) ) Error Message: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-27-bf8957bdded0> in <module> 14 instrument = enter_strike, 15 quantity = enter_quantity, ---> 16 order_type = OrderType.a, 17 product_type = ProductType.Intraday, 18 price = prompt1, c:\users\ravi\appdata\local\programs\python\python38\lib\enum.py in __getattr__(cls, name) 339 return cls._member_map_[name] 340 except KeyError: --> 341 raise AttributeError(name) from None 342 343 def __getitem__(cls, name): AttributeError: a When am passing the string into another variable, it is giving me error. Please check below error -
Django model fieldsets with lable name from model?
I have a model named "Documents" and now i have two fields on the table namely - type & path Now type will be updated from admin end and path will be updated by users, so too handle this i was using model set form ( as there are more than one fields to be updated at once ) from django.forms import modelformset_factory documentFormset = modelformset_factory(Documents, fields=('document_path',), extra=0) formset = documentFormset(queryset=Documents.objects.filter(type="Request")) So the above gives the required, but now the problem is i need to display the "type" as field name to the respective path field ! For instance: If a row has id | type | path | 1 | Request | | 2 | Certificate | | And when using model formset on the above it gives two forms with "path" as input and its default lable as "Path" So the problem is i need to show "type" value as label name, Certificate : Input(filepath) // need this instead of Type: Input(filepath) So how to change fields label name to name something from the same model -
AttributeError: 'TestModelCreateView' object has no attribute 'object'
I'm overriding get_success_url in my object creation view. Everything else works fine but the tests fail with the error; AttributeError: 'TestModelCreateView' object has no attribute 'object' # View.py from django.views.generic import CreateView class TestModelCreateView( CreateView, BaseFormMixin ): form_class = TestModelForm model = TestModel def get_success_url(self) -> str: return reverse_lazy( "ops:test_model_update", kwargs={"pk": self.object.pk} ) # Test.py def test_model_url(): test_obj:TestModel = baker.make(TestModel, comment=fake.text()) v = TestModelCreateView() call_back_url = v.get_success_url() assert f"/ops/test_model_update/{test_obj.pk}" in call_back_url -
Create project django in pycharm
Creating a project with django in pycharm. Create using the directory on the left (but they are not displayed during creation) I dont have directory like in left photo -
Why does my filtering of queryset on valid pk returns full queryset?
As far as I understand, querysets can always be filtered on. However, if I create this queryset filtering breaks: set_synonyms = Compound.objects.filter(synonyms__name__icontains=query_string) It is a proper queryset: <QuerySet [<Compound: 2-[4-(2-methylpropyl)phenyl]propanoic acid>, <Compound: 2-[4-(2-methylpropyl)phenyl]propanoic acid>, <Compound: 2-[4-(2-methylpropyl)phenyl]propanoic acid>, <Compound: 2-[4-(2-methylpropyl)phenyl]propanoic acid>, '...(remaining elements truncated)...']> and I can get the pk of any element of the queryset, e.g.: pk=set_synonyms.first().pk (pk has the value 76) But when I filter on it, the whole queryset is returned: set_synonyms.filter(pk=pk) just returns the whole queryset set_synonyms. And using set_synonyms.get(pk=pk) raises MultipleObjectsReturned exception (because it returns the whole queryset set_synonyms). Possible relevant information: the relation between Compound and Synonym models is a 1-to-many (1 compound having many synonyms). class Synonym(MixinPubChemCompound, models.Model): """Model definition for synonym naming of compound""" name = models.CharField(max_length=999, db_index=True, null=True) compound = models.ForeignKey( Compound, on_delete=models.CASCADE, related_name='synonyms') retrieved_from = models.ForeignKey( generic_models.Reference, related_name='synonyms', on_delete=models.PROTECT) class Compound(MixinPubChemCompound, models.Model): cid = models.IntegerField(unique=True, db_index=True) iupac_name = models.ForeignKey( IupacName, on_delete=models.PROTECT, unique=False) -
Search bar for django
I have a page where the staff is able to see the staff they have enter, but if the lists get too long, it is hard to find the stuff they wanted, hence, I want to create a search bar and a button so that they can search for the stuff easily and display it in a card form as shown below, how do I do that? This is how my website looks like (in the url it will show q=76464 but it just wont display q=76464) views.py def outgoinggallery(request): user = request.user query = request.GET.get('q') category = request.GET.get('category') if category == None: alloutgoinglru = OutgoingLRU.objects.filter(category__user=user) else: alloutgoinglru = OutgoingLRU.objects.filter( category__name=category, category__user=user) if query: return OutgoingLRU.objects.filter(title__icontains=query) else: return OutgoingLRU.objects.all() categories = Category.objects.filter(user=user) context = {'categories': categories, 'alloutgoinglru': alloutgoinglru} return render(request, 'Outgoing/outgoinggallery.html', context) outgoinggallery.html {% extends "logisticbase.html" %} {% block content %} <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <style> td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; border-radius: 15px; } .image-thumbail { height: 200px; object-fit: cover; } .list-group-item a { text-decoration: none; color: black; } </style> <br> <div style="padding-left:16px"> <div class="row"> <div class="col-md-9"> <div class="row"> <h5>View Outgoing LRU</h5> <div class="col-md-7"> <form method="GET" action="" id="searchform"> <input … -
Django compress string data
I have a django model having: raw_data = models.TextField(_("raw_data"), default='') It just storing some raw data which can be 1K - 200K. I have 50 millions rows. I need to decrease size of data in database. How can I tell what consume most data over all database ? Should I use a string compression before storing the data ? 2.1 I saw here: Text compression in PostgreSQL that it get compressed anyway, is that true ? 2.2 I did some python code compression, I am not sure if changing bytes to string type can cause in lossing data: def shrink_raw_data(username): follower_data = get_string_from_database() text = json.dumps(follower_data).encode('utf-8') # outputs as a bytes # Checking size of text text_size = sys.getsizeof(text) print("\nsize of original text", text_size) # Compressing text compressed = str(zlib.compress(text, 9)) # store String in database # Checking size of text after compression csize = sys.getsizeof(compressed) print("\nsize of compressed text", csize) # Decompressing text decompressed = zlib.decompress(compressed) # Checking size of text after decompression dsize = sys.getsizeof(decompressed) print("\nsize of decompressed text", dsize) print("\nDifference of size= ", text_size - csize) follower_data_reload = json.loads(decompressed) print(follower_data_reload == follower_data) I am not sure about "str(zlib.compress(text, 9))" since my data is stored as string in … -
Why does my ModelForm with CheckboxSelectMultiple widget not validate?
I have a SelectCategoryForm which renders a queryset of Model Category that stores the different categories. The Model UserCategoryFilter stores the filter selected and saved by a user. # Form class SelectCategoryForm(forms.Form): choices = forms.ModelMultipleChoiceField(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple) # Models class Category(models.Model): poller_category = models.CharField(max_length=30) category_color = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.poller_category) class UserCategoryFilter(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.ForeignKey(Category, on_delete=models.CASCADE) # View @require_POST def save_category_filter(request): # User logged in? if request.user.is_authenticated: # Get the form instance filter_form = SelectCategoryForm(request.POST) # Form validation if filter_form.is_valid(): Now when I select some categories in the template and submit, the view validates the form as invalid. -
type object 'ArticleSitemap' has no attribute 'filter' Sitemap
I am working with the Django sitemap framework. Trying to improve SEO stuff for my blog, I have expanded my Article model in models.py and introduced sitemaps.py in one of the Django apps named MArticles. But I have faced an Attribute Error: type object 'ArticleSitemap' has no attribute 'filter'. Below are my python files. In sitemaps.py from django.contrib.sitemaps import Sitemap from .models import Article class ArticleSitemap(Sitemap): changefreq = "weekly" priority = 0.8 def items(self): return Article.modelmanager.all() def lastmodified(self, obj): return obj.last_updated In models.py from django.db import models import datetime from EHub.models import * from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse from mptt.models import MPTTModel, TreeForeignKey from taggit.managers import TaggableManager from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class IpModel(models.Model): ip=models.CharField(max_length=100,null=True) def __str__(self): return str(self.ip) class Article(models.Model): options=( ('draft','Draft'), ('published','Published'), ) def get_absolute_url(self): return reverse('MArticles:article_detail',kwargs={'pk':self.id,'slug':self.slug}) class CustomManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status ='published') title=models.CharField(max_length=250,null=True) thumbnail = models.ImageField(upload_to="thumnails/%y",null=True,blank=True) description = RichTextUploadingField(null=True,blank=True, config_name='sourcecode',) author=models.ForeignKey(User,on_delete=models.CASCADE,related_name='blog_posts') slug=models.SlugField(null=True,unique=True) tags=TaggableManager() category = models.ManyToManyField(Category,blank=True) publish_date = models.DateField(default = datetime.date.today) last_updated=models.DateTimeField(default=timezone.now) views=models.ManyToManyField(IpModel,related_name="post_views",blank=True) featured = models.BooleanField(default=False) status=models.CharField(max_length=10,choices=options,default='draft') previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True) objects = models.Manager() modelmanager = … -
Something wrong with django json serializer
i try looking for answers but so far to no avail, basically i try to return django model as json however, it seem that the serializer convert it to string instead my code is as follow: view.py from django.shortcuts import render from screener.models import maintable from .models import Messages from django.http import JsonResponse from django.core import serializers from datetime import datetime import json def infiniteScroll(request, room_name): dateFilter=request.GET.get('date') dateFilter=dateFilter[5:len(dateFilter)-4] dateFilter=datetime.strptime(dateFilter, '%d %b %Y %H:%M:%S') data=serializers.serialize('json', reversed(Messages.objects.filter(room=room_name).filter(date_added__lt=dateFilter).order_by('-date_added')[:2])) return JsonResponse(data, safe=False) urls.py from django.contrib import admin from django.urls import path from . import views app_name='chat' urlpatterns = [ path('<str:room_name>/', views.room, name='room'), path('<str:room_name>/hist/', views.infiniteScroll, name='infiniteScroll'), ] when i go to the site http://127.0.0.1:8000/chat/AAPL/hist/?date=Thu,%2023%20Sep%202021%2014:03:42%20GMT the result is a page with string instead: "[{\"model\": \"chat.messages\", \"pk\": 118, \"fields\": {\"username\": \"adiputra12\", \"room\": \"AAPL\", \"content\": \"hello\", \"date_added\": \"2021-09-23T13:54:30.043Z\"}}]" how can I return json instead like shown below: [{'model': 'chat.messages', 'pk': 118, 'fields': {'username': 'adiputra12', 'room': 'AAPL', 'content': 'hello', 'date_added': '2021-09-23T13:54:30.043Z'}] -
Django Pass urls args directly to template like TemplateView, but with DetailView
I have a detail view. I require to be able to have url args in the template like what TemplateView does, e.g. if I have the following url: views.FooView.as_view(), {'page_title':'Foos of the world'}, name='foo',), Then in the template, it expects 'page_title' from the context, not view.kwargs.page_title (due to the whole sites framework). I think I tracked down the mixin for attaching urls args directly in the context to ContextMixin, However when I try add the mixin to the DetailView, e.g. class FooView(ContextMixin, DetailView): I get an error: TypeError: Cannot create a consistent method resolution order (MRO) for bases ContextMixin, DetailView I think DetailView inherits from ContextMixin, in which case why does it not provide the functionality? -
Django Question matching query does not exist
I have two models for Question and Answer, every question has several answers from the authenticated users, now i want a user can delete a specific answer that is related to him, my question has slug, and also for answers i have id field, i want to delete that answer according to the id, i have created a simple code and i think that is not correct, when i click on delete answer button i am receiving this error. ( raise self.model.DoesNotExist( questions.models.Question.DoesNotExist: Question matching query does not exist.) models.py from django.db import models from django.conf import settings class Question(models.Model): created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length = 250) body = models.TextField() slug = models.SlugField(max_length = 250, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="questions") def __str__(self): return self.title class Answer(models.Model): created_at = models.DateTimeField(auto_now_add=True) description = models.TextField() question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="answers") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.author.username This code is for listing all the answers that is related to the question, and in here at the bottom i have a button for deleting the specific answer. <div class="container"> {% for answers in answer_list%} <div class="card mt-4 py-3 shadow"> <div class="card-body"> <p class="card-text">{{answers.description}}</p> <div class="row"> <div class="col col-md-auto"> Answered By: {{answers.author.username}} … -
Send Form back and from two views in Django
I am making a project that involves users being able to write inside a Form and then save it as a markdown file. I need to find a way to show the user how does the markdown he is currently writing would look already once parsed; this would be shown on a separate static page with a return button to go back to writing. This last part is giving me problems since I manage to show the user how his file would look like yet I haven't been able to find a way to render it back to the original entry form where it came from Preview HTML {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>Preview</h1> <h3>{{title}}</h3> <hr> {{preview|safe}} <form action="{% url 'new_entry' %}" method="POST"> {% csrf_token %} <input type="submit" name="return" value="Return"> </form> {% endblock %} New Entry HTML {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>New Entry</h1> <div class="form-group"> <form action="{% url 'new_entry' %} " method="POST"> {{form.as_table}} {% csrf_token %} <input type="submit" value="Save" name="submit"> <input type="submit" value="Preview" name="preview"> </form> </div> {% endblock %} Views for Preview and New HTML def preview(request): #Retrieve data from the … -
how to copy my my production app data into my local host app
I deployed an app on Heroku and I have same app in my local machine now i want to copy all my deployed app data on my local app to so is there any way to do it anyway that will be very helpful because I don't know how to copy all my production data and paste it into my local machine I am using default sqlite3 Django default database -
Django redirect to detail page after authentication
here is my code class UserProfileView(DetailView): template_name = 'main/userprofile.html' context_object_name = 'userprofile' model = ProfilePersonal # def dispatch(self, request, *args, **kwargs): # if request.user.is_authenticated: # pass # else: # return redirect('/accounts/login/?next=userprofile/6') # return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) comments_connected = Review.objects.filter(profile=self.get_object()).order_by('-date_created') context["comments"] = comments_connected context['comment_form'] = ReviewForm return context def post(self, request, *args, **kwargs): if request.user.is_authenticated: new_comment = Review(content=request.POST.get('content'), rating=request.POST.get('rate'), profile=self.get_object(), user = self.request.user) else: return redirect(f'/accounts/login next=userprofile/{self.get_object()}') new_comment.save() return self.get(self, request, *args, **kwargs) Everything works fine except for the fact that if a user try to drop a comment and the user is not login in he will be be redirected to the login page but after authentication i want to redirect the user the user detail page where he was redirected from. for example if i was redirected from 127.0.0.1:8000/userprofile/6 after logging in i should be redirected to 127.0.0.1:8000/userprofile/6 in order to continue with what i was doing -
Django & Cassandra: How to give choice field to a model with Django Cassandra engine?
Hey guys I am new to Cassandra and was trying to integrate it with Django with Django Cassandra engine package. I have a choice field with some types like, TYPE = [('1', '1'), ('2', '2'), ('3', '3'),] with postgres, I can use a CharField with choices, but how can I achieve the same with Cassandra? Can anyone provide some hints? Thanks in advance. -
How to retrieve foreign field name in Django Rest Framework
I have 2 models one for a user and another for associated files for the user Models.py class IndividualUser(models.Model): membership_id = models.CharField(primary_key=True, max_length=100, default=1) profile_image = models.ImageField(blank=True, upload_to ="individual_member_profile/", null=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) class MemberCatalogue(models.Model): membership_id = models.ForeignKey(IndividualUser, default=None,on_delete=models.CASCADE, related_name="member_catalogue") files = models.FileField(upload_to="individualmembercatalogue/") Currently Iam getting absolute path for files. I need a filename uploaded by user for which Iam trying to get "files" field and and then split it with "/". But Iam struggling to get the files field from MemberCatalogue. My serializers look like this at the moment: class MemberCatalogueSerializer(serializers.ModelSerializer): files = serializers.FileField() class Meta: model = MemberCatalogue fields = ['id','membership_id', 'files'] class IndividualMembersSerializer(serializers.ModelSerializer): member_catalogue = MemberCatalogueSerializer(many=True) filename = serializers.SerializerMethodField('get_filename') def get_filename(self, obj): return obj.individualmember.files class Meta: model = IndividualMembers fields = "__all__" But I cant get the desired output. Expected output is like { "membership_id": "142369ca1b1484d8d9d6d87fdc8543db", "member_catalogue": [ { "id": 156, "membership_id": "142369ca1b1484d8d9d6d87fdc8543db", "files": "http://127.0.0.1:8000/individualmembercatalogue/some_file.pdf" "filename" : "some_file.pdf" } ], "profile_image": null, "firstname": "John", "lastname": "Doe", } -
File download in Django template
I am trying to download a file, but getting the download in html format, how I can get the file in its on format class Certificate(models.Model): name = models.CharField(max_length=80, blank=True, null=True) cert = models.FileField(upload_to='cert/', blank=True, null=True) def download_link(self): self.cert.url <a href="{{ obj.download_link }}" download> Download File</a> Tried the following way also but still in html format def download_link(self): path = self.cert.path filename = 'download.extension' fl = open(path, 'r') mime_type, _ = mimetypes.guess_type(path) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response -
how to test a unit test using pytest django if there is a function defined but not the class?
@api_view(['GET']) def get_search(request): search_text = get_searchText() return Reponse({"search-txt":search_text}) here, search_txt is an api for searching the text,and search_text is a variable I tried below but was unable to test the above code, from django.test import TestCase, Client class TestViews(TestCase): def setUp(self): self.client = Client() self.searchtxt_url = reverse('search-txt') def test_search_project(self): response.self.client.get(self.searchtxt_url) self.assertEquals(response.status_code, 200) what can be a possible way to test a function with api -
Django large queryset return as response efficiently
I have a model in django called "Sample" I want to query and return a large number of rows ~ 100k based on filters. However, it's taking up to 4-5 seconds to return the response and I was wondering whether I could make it faster. My current code looks like this: @api_view(['POST']) def retrieve_signal_asset_weight_ts_by_signal(request): #code to get item.id here based on request qs = Sample.objects.filter( data_date__range=[start_date, end_date], item__id = item.id).values(*columns_required) df = pd.DataFrame(list(qs), columns=columns_required) response = df .to_json(orient='records') return Response(response, status=status.HTTP_200_OK) Based on multiple test cases -- I've noticed that the slow part isn't actually getting the data from DB, it's converting it to a DataFrame and then returning as JSON. It's actually taking about 2 seconds just for this part df = pd.DataFrame(list(qs), columns=columns_required). Im looking for a faster way to convert queryset to a json which I can send as part of my "response" object! Based on this link I've tried other methods including django-pandas and using .values_list() but they seem to be slower than this, and I noticed many of the answers are quite old so I was wondering whether Django 3 has anything to make it faster. Thanks Django version : 3.2.6 -
I want user can change website language using drop-down without login but if they log in website should translate in their saved language preference
I am using a Django website in which a user can change their language using a drop-down menu. I use Django i18n for the translation of the website. Now problem is that I want a user can visit some pages of the website without login and they can change the language using a drop-down. But when a user logs in, the language of the website should change to the default language of that user's we store in their porifle section. How can I achieve this? language_form.html {% load i18n %} <form action="/i18n/setlang/?next={% url 'homepage' %}" method="post"> {% csrf_token %} <select name="language" style="padding: 4px 3px;"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_current_language_bidi as LANGUAGE_BIDI %} {% for language in LANGUAGES %} <option value="{{ language.0 }}"{% if language.0 == LANGUAGE_CODE %} selected {% endif %} "> {{ language.1 }} </option> {% endfor %} </select> {% for lang in aLANGUAGES %} {{lang.list}} {% endfor %} <input type="submit" value="Change language" style="padding: 3px 3px; margin-right: 10px;"> </form> The above code is my drop-down form for the select languages but I want user can select their preferred language in the profile section and that will be enabled automatically when they logged …