Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how we can show users in admin panel in django in m2m field without list comprehension
class Page(models.Model): user = models.ManyToManyField(User) post = models.TextField() post_date = models.DateField() def get_user(self): return ", ".join([str(p) for p in self.user.all()]) how we can do without list comprehension https://i.stack.imgur.com/PPnYj.png -
Django custom field has no attribute 'set_attributes_from_name'
I have a custom field to convert the input date to a timedelta in years, rounded up: class CustomField(models.Model): start_date = models.DateField() def days_to_years(self, date: timedelta): return math.ceil(date.days / 365) def save(self, *args, **kwargs): delta = datetime.today() - self.start_date self.start_date = math.ceil(delta.days / 365) super(CustomField, self).save(*args, **kwargs) Which I use in models like: from django.contrib.postgres.fields import ArrayField class Component(ComponentBase): years = ArrayField( CustomField() ) When I try to make migrations, the error AttributeError: 'CustomField' object has no attribute 'set_attributes_from_name is raised, which I can't seem to debug because I'm still quite fresh to Django. Any suggestions would be very welcoming :). -
django forms is_valid() method always returning true if all the form field's required is false
models.py created a model registerForm.my database is mysql. from django.db import models class registerForm(models.Model): name = models.CharField(max_length=50 ) username = models.CharField( max_length=50) email = models.EmailField(max_length=50) password = models.CharField(max_length=50) class Meta: db_table = 'userForm' def __str__(self): return self.name forms.py from django import forms from django.forms import widgets from login_and_logout.models import registerForm class regForm(forms.ModelForm): def __init__(self, *args, **kwargs): # first call parent's constructor super(regForm, self).__init__(*args, **kwargs) # there's a `fields` property now self.fields['name'].required = False self.fields['username'].required = False self.fields['email'].required = False self.fields['password'].required = False class Meta: model = registerForm fields = "__all__" views.py check form is valid using is_valid() method . i printed def signup(request): if request.method == 'POST': form = regForm(request.POST) print(form.is_valid()) if form.is_valid(): return HttpResponse('success') else: return HttpResponse('fail') form = regForm() return render(request, 'signup.html', {'form': form}) i trying to implement form validation using javascript in client side and serverside validation in dajngo . in order to acheive form validation without required attribute i give required false in dajngo forms.py. but after the is_valid() method always returning true. but if i remove the init funtion i used to remove requied field in forms.py the is_valid() works. i want to remove the required field and also i want to work the is_valid() … -
Filter queryset only where the user is added to ManyToManyFIeld
I want to return all leads that contain a current user. How to do it? Models.py class CustomUser(AbstractUser): def __str__(self): return self.email class Lead(models.Model): budget = models.IntegerField() buyer = models.ManyToManyField(CustomUser) What queryset is expected Lead.objects.filter(buyer__have=request.user) -
What is latest(>9.6) postgres version compatible with Django 1.11.20?
Postgres 9.6 is deprecated, we need to upgrade to a version which is compatible with Django 1.11.20. I have already checked django docs but it mentions any postgres version>9.3 but how do i verify it? Thanks for the support in advance:) -
Django/React/Firebase - CORS error when uploading big files
I have a website with React hosted on Firebase, with Django for backend running on a server with nginx. On this website I have a form where the user can upload up to 3 images. On my local PC it works fine, but on the production environment I get this error when I try to upload big files (more than 5mb): A server/network error occurred. Looks like CORS might be the problem. Sorry about this - we will get it fixed shortly. Now the thing is that the images get uploaded normally, I can see them when I check the submitted form on the website admin area, but on the frontend, after submitting the form, instead of the success message I get that error. I have incresed nginx client_max_body_size 15M, but I still get the error. But given that the images do get uploaded, I think the max body size is not the problem. -
How can we use consumer sent function in django model manager function?
i'm trying to send a message whenever a new task created.. The problem here is.. there is not error coming in terminal and anywhere but the message that suppose to send is not sending.. the model manager function is unable to reach consumer sent function... class TaskManager(models.Manager): async def send_now(self,data): ........ room_name = await create_roomname_threadID(mydata["project_key"],username) print("room_name :",room_name) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( room_name, { 'type': 'sent', 'object': object }) asgi from notifications.sockets import routing "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns, ) ), routes websocket_urlpatterns = [ path('ws/project/<str:project_key>/<str:username>/', consumers.ProjectConsumer.as_asgi()), ] consumer ..... # Receive message from room group async def sent(self, event): sender = event['object']["sender"] receiver = event['object']["receiver"] message = event['object']["message"] print("hey hey hey ") # Send message to WebSocket await self.send(text_data=json.dumps({ 'sender':sender, 'receiver':receiver, 'message':message, })) -
Desing path to create a C++ web framework
I would like to pose a metatopic about a nice (the best it's too much, I guess) way to develop a C ++ web framework, like Java's Spring or Python's Django. We need some sockets programming, some nice template programming to offer a nice and usable API, web request and response handlers, database handlers, possible some kind of ORM ... but ... what more? And in which order? How do you imagine a nice abstract approach (the big steps) that you should make to create a monster project like this? Bonus points to who answer this one thinking about the best user experience (since C++ it's not exactly the most syntax friendly programming language) using the internal API's that should be the core of the project, (in big words, not concrete). -
problem showing errors in field in django form
I have a problem displaying an error in a field of my form In the view I get this but without the error description: But in the html the tag if the description exists, it just isn't showing it to me: Here is the implementation of the error, it is nothing to write home about: def clean(self): form_data = self.cleaned_data result = utils.verificarFechaPeriodo(self.AIGN_PER_ID, form_data['act_fechaini'], 6,'YYYY-MM-DD') if result[0][0] is not None: self._errors["act_fechaini"] = [str(result[0][0])] del form_data['act_fechaini'] return form_data -
why this occurs AttributeError: 'User' object has no attribute 'cusromer'
why this error occurs I cant understand .I am creating a e-commerce website where a customer can add products to cart and and purchase it # .I look allot but not getting the right answer which can remove that please help me to solve this it is showing'User' object has no attribute 'Customer' and Customer = request.user.Customer thus there is a problem in customer word or some other thing . models.py from django.db import models from django.contrib.auth.models import User from django.db.models.fields.related import OneToOneField class Customer(models.Model): user = OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=400, null=True) email = models.EmailField(max_length=254) def __str__(self): return self.name class products(models.Model): name = models.CharField(max_length=500, null=True) price = models.FloatField() degital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null=True,blank=True) def __str__(self): return self.name @property def imageURL(self): try: url =self.image.url except: url ='' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=500, null=True) def __str__(self): return str(self.id) class Orderitem(models.Model): product = models.ForeignKey(products, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) class shippingaddress(models.Model): customer = models.ForeignKey( Customer, on_delete=models.SET_NULL, null=True, blank=True ) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) address = models.CharField(max_length=500, null=True) city = … -
Not able to redirect the forms in my website and show Success message in django
I am new to Django, The form takes input from a user and saves it in /admin and also sends mail to my email.I am trying to get success message after clicking on Send message but I am not able to get the Success message.Also I want page to redirect in same contact form and cleared input fields. Thankyou #My Views.py from django.shortcuts import render from django.shortcuts import render from collections import namedtuple from django.contrib import messages from django.shortcuts import redirect, render from django.views.generic import ListView, CreateView, DeleteView, DetailView from . import models from . import forms from django.core.mail import send_mail from django.conf import settings from django.http import HttpResponseRedirect def home(request): return render(request, 'index.html') def contact(request): contact = models.Contact.objects.all() form = forms.ContactForm() if request.method == 'POST': firstname = request.POST['firstname'] lastname = request.POST['lastname'] email = request.POST['email'] phone = request.POST['phone'] message = request.POST['message'] data = { 'firstname': firstname, 'lastname': lastname, 'email': email, 'phone': phone, 'message': message } message = ''' The message is sent by: {} {} Email_id: {} Phone No: {} Message: {} '''.format(data['firstname'], data['lastname'], data['email'], data['phone'], data['message']) send_mail(data['email'], message, '', ['bbchanna@gmail.com']) form = forms.ContactForm(request.POST) if form.is_valid(): form.save() form = forms.ContactForm() return render(request, 'contact.html', {'form': form, "success": True}) else: raise NotImplementedError … -
NoReverseMatch at /polls/1/ in Django 4.0
I am learning Django from the official documentation, and getting this error: NoReverseMatch at /polls/1/ Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/\\Z'] Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/ Django Version: 4.0 Exception Type: NoReverseMatch Exception Value: Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/\\Z'] These are my urlpatterns: urlpatterns = [ path('', views.index, name='polls'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/result/', views.result, name='result'), path('<int:question_id>/vote/', views.vote, name='vote'), ] View.py File: def index(request): latest_questions = Question.objects.order_by('-pub_date') return render(request, 'polls/index.html', {'latest_questions': latest_questions}) def detail(request, question_id): detail = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'detail': detail}) def result(request, question_id): return HttpResponse("This is the result for question no. %s" % question_id) def vote(request, question_id): return HttpResponse("You are voting for question %s" % question_id) And this is where the problem lies on detail.html: <form action="{% url 'vote' question.id %}" method="post"> -
Django AppConfig ready()
I have Django 2.1.7 I read Django documentation as well as, this How to use django AppConfig.ready() and this Overriding AppConfig.ready(). Now, the folder/file structure is like this, my_app __init__.py urls.py sub_app1 migrations __init__.py admin.py apps.py models.py ... sub_app2 ... sub_app3 ... and all sub_apps are registered into INSTALLED_APPS of Django settings.py file as my_app.sub_app1 for example. I noticed that when I try to override ready()for sub_app1 w/in sub_app1.apps.py, overriding has no effect. When I flatten my structure above as my_app __init__.py urls.py apps.py overriding of ready works fine. In other words, it seems that overriding of readyof a sub app w/in sub app's apps.py doesn't work. Also, whether using default_app_config w/in sub app's __init__.py or my_app.sub_app1.apps.SubApp1Config w/in settings.py INSTALLED_APPS it gives error django.core.exceptions.ImproperlyConfigured: Cannot import 'sub_app1'. Check that 'my_app.sub_app1.apps.SubApp1Config.name' is correct. Why is this happening? -
Compose template variable with another template in Django
I'm trying to dynamically get a template variable in an html file. Depending on the particular file loaded i'm having some things passed in the context: prefix, a string which for sake of the example may be "foo" or "bar" foo_conf bar_conf Both foo_conf and bar_conf have the attribute timestamp. The non-working code I've written is the following: <div class="col-12">Configuration: {{ prefix|add:'_conf.timestamp'|time }}</div> What I want to do is so take the value of the variable foo_conf.timestamp or bar_conf.timestamp and pass it to the "time" filter, displaying the result. But with the code I've written, the string "bar_conf.timestamp" (or foo_conf.timestamp") is passed to the "time" filter, which of course throws an exception being designed to work with time objects, not strings. How can I achieve the desired behaviour? Thanks in advance. -
ImportError: No module named south.v2 but I have installed v2
I am running django 1.2 on a windows 10. I created a virtual environment and cloned my repository from github. I try to migrate ./manage.py migrate and I get the error: ImportError: No module named v2 I have checked similar problems but they don't work on my project. ! Migration assist:0332_alias_crawl_from probably doesn't exist. Traceback: Traceback (most recent call last): File "manage.py", line 6, in execute_manager(conf) File "D:\workspace\Fix python\web\venv2\lib\site-packages\django\core\management_init_.py", line 438, in execute_manager utility.execute() File "D:\workspace\Fix python\web\venv2\lib\site-packages\django\core\management_init_.py", line 379, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\workspace\Fix python\web\venv2\lib\site-packages\django\core\management\base.py", line 191, in run_from_argv self.execute(*args, **options.dict) File "D:\workspace\Fix python\web\venv2\lib\site-packages\django\core\management\base.py", line 218, in execute output = self.handle(*args, **options) File "D:\workspace\Fix python\web\venv2\lib\site-packages\south\management\commands\migrate.py", line 79, in handle tree = migration.dependency_tree() File "D:\workspace\Fix python\web\venv2\lib\site-packages\south\migration.py", line 117, in dependency_tree tree = all_migrations() File "D:\workspace\Fix python\web\venv2\lib\site-packages\south\migration.py", line 112, in all_migrations for app in get_migrated_apps() File "D:\workspace\Fix python\web\venv2\lib\site-packages\south\migration.py", line 94, in get_migration module = import(app.name + "." + name, '', '', ['Migration']) File "D:\workspace\Fix python\web\assist\migrations\0332_alias_crawl_from.py", line 4, in from south.v2 import SchemaMigration ImportError: No module named v2 Here are my pip freeze list ''' amqp 1.0.13 amqplib 0.6.1 anyjson 0.3.3 beatbox 16.1 BeautifulSoup 3.2.0 billiard 2.7.3.34 carrot 0.10.7 celery 3.0.22 contextlib2 0.6.0.post1 Django 1.2 django-basic-apps 0.7 django-celery 2.5.0 django-filebrowser 3.2 django-mobileadmin 0.5.2 … -
How to clear or resize a textarea if website is duplicated?
If the user duplicates the website, everything else is reset except for the textarea. How can I clear the textarea if the website is duplicated OR resize the textarea on given Input Original Website Duplicated Website I already tried adding textarea.value = ""; in the JavaScript file but it is not properly working. Is there an easier way than checking the cookies to find out if the website is being duplicated? I only want to remove or resize the textarea, the information if the website is being duplicated does not matter. The backend is made with django. -
Elasticsearch Python Django: How to limit the output text content and highlight the input keyword
This is my search function in views.py def search(request, pk, slug): es = Elasticsearch() es_client = Elasticsearch(['http://127.0.0.1:9200']) print('called search') search_text = request.GET.get('qq') print('Search text: {}'.format(search_text)) print('cluster id/ ealstic search index: {}'.format(pk)) s = None count = 0 try: if search_text: s = Search(index=str(pk)).using(es_client).query("match", content=search_text) response = s.execute() count = 0 for hit in s: count += 1 print(str(count) + ' - ' + str(hit.currnet_url)) #print(hit.content) else: print('nothing more found') else: print('No text to search') except Exception as e: count = 0 print('Exception caught') msg = 'Cluster is not ready to be searched' return render(request, 'base_app/cluster_search.html', {'warning':msg, 'count':count}) return render(request, 'base_app/cluster_search.html', {'cluster':slug, 'hits':s, 'count':count}) This is how I am indexing data to Elasticsearch. def elastic_indexer(text, depth, url, clusrer_id): es_client = Elasticsearch(['http://127.0.0.1:9200']) doc = { "date": time.strftime("%Y-%m-%d"), "currnet_url": url, "depth": depth, "content": text } res = es_client.index(index= str(clusrer_id), doc_type="_doc", body=doc) print(res["result"]) This is the frontend template where the users input a text to search. {% extends "account/base.html" %} {% load i18n %} {% load crispy_forms_tags %} {% block head_title %}{% trans "Search" %}{% endblock %} {% block content %} <a href="{% url 'clusters' %}">Go Back</a> <P style="font-size:17px;">You are searching in {{cluster.title}}</P> <form method="GET" action=""> {% csrf_token %} <button class="btn btn-primary" action="">Search</button> <input … -
Django: change TextField before save
This is my model : class Card(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) imp_id = models.TextField(null = True) And here is my view : def Add(request): if request.method == 'POST': form = Add_card(request.POST) if form.is_valid(): save = form.save(commit = False) save.user = request.user save.imp_id = "asd" # I tried to change it here but I failed save.save() else: form = Add_card() cards = Card.objects.all() return render(request, 'addcard.html', {'form': form, 'cards' : cards}) How can I change that textfield before save? -
How do I pass data to another view function for processing
I have the following code that i need to pass on to another function, process_payment for further processing. I've tried the code below but it doesn't seem to work as expected. def SubscribePage(request): if request.method == 'POST': form = PaymentForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] amount = '20' return redirect(process_payment(name, email, phone, amount)) else: form = PaymentForm() context = { 'form': form } return render(request, 'subscribe.html', context) Please advise on where i could be going wrong. Regards. -
django : ValueError - Cannot serialize
i have error in my django project . when i run 'python manage.py makemigrations' command than come error. ValueError: Cannot serialize: <django.db.models.query_utils.DeferredAttribute object at 0x000001B5A3078940> models.py class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) quntity = models.IntegerField(default=1) price = models.IntegerField(default=Product.price) address = models.CharField(max_length=200) phone = models.CharField(max_length=13) date = models.DateTimeField(auto_now=True) print(Product.price) def __str__(self) -> str: return self.product.name admin.py from django.contrib import admin from .models import Order # Register your models here. class OrderAdmin(admin.ModelAdmin): models = Order list_display =['product','customer','quntity','price','address','phone','date'] admin.site.register(Order,OrderAdmin) and this is my error page:- -
How to filter custom urls in ModelViewSet with django-filters
class ExportTabView(ModelViewSet): permission_classes = [UserHasDatasetChangeAccess] queryset = JobTable.objects.all() filterset_fields = [ "job_type", "action", "source_table__name", "source_table__type", ] ordering_fields = ["created_on", "modified_on"] ordering = ["-modified_on"] I am able to use django filters with above api as : /api/export-tab-view?source_table__name='temp' But after adding custom urls in this model view set, I am not able to use django filters . class ExportTabView(ModelViewSet): serializer_class = ExportTabSerializer permission_classes = [UserHasDatasetChangeAccess] queryset = JobTable.objects.all() filterset_fields = [ "job_type", "action", "source_table__name", "source_table__type", ] ordering_fields = ["created_on", "modified_on"] ordering = ["-modified_on"] @action(detail=False) def export_dataset(self, request, id=None): """ Returns a list of all the relationship names that the given dataset has """ jobs = JobTable.objects.filter( dataset=get_object_or_404(DataSet, id=self.request.META.get(DATASET_ID, "")) ) return Response(ExportTabSerializer(jobs, many=True).data) Now filters are not working when i call api /api/export-tab-view/export_dataset?source_table__name='temp' -
How to create Conda virtual environment within project subdirectory
I want to create conda env in my project subdirectory like virtual env. Kindly explain the process to create, activate and deactivate conda env. Take my project directory as :- myProject/ -
Django .annotate TruncMonth : How to Get full range of Months
I want total earning from each month and display it in graph so im making below query Here's my query: query = UserOrderService.objects.all() query = query.annotate(month=TruncMonth('order_booking_date')).values( 'month').annotate(no_of_services=Count('pk')).annotate( total=Sum(F('service_price') * F('quantity'))).order_by('month') Above query only gives data from months where booking happend Output: "data": [ { "no_of_services": 1, "total": 26725.0, "month": "November" }, { "no_of_services": 1, "total": 26725.0, "month": "December" } ] Where as i want all data from all months Even if there's no data in that particular month Expected Output: "data": [ { "no_of_services": 0, "total": 0, "month": "January" }, { "no_of_services": 0, "total": 0, "month": "February" }, { "no_of_services": 0, "total": 0, "month": "March" }, ... { "no_of_services": 1, "total": 26725.0, "month": "November" }, { "no_of_services": 1, "total": 26725.0, "month": "December" } ] -
How can I filter time by using Django_Filters
start_time = django_filters.TimeFilter(lookup_expr='gte', field_name='created_at__hour', input_formats="%H") end_time = django_filters.TimeFilter(lookup_expr='lte', field_name='created_at__hour', input_formats="%H") Input: start_time = 10 Result: { "start_time": [ "Enter a valid time." ] } -
Get results of the search from MSSQL data base in Django web page
I have to create simple Web page which will search data in a SQL Server data base. I managed to connect to my database and run server with my simple HTML which has Label, textbox, button and listbox. Expect this, project has default settings. Could you please help me, how can i set request to DB like "Select * FROM Mac_Storage where MAC = "Here should be the text from textbox"" to button and return the results to my Web page?