Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image after uploading in template does not show , Django , AWS3
I have some problems with the image field, I store them on AWS through DigitalOcean. Fun Fact: When I upload an image on to the admin panel, it works fine, and when I’m trying to do the same in a template , image updates but does not get stored on AWS also Image not shown on page . here is my files : settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_ROOT=os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/photos/' urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py user = request.user.id image = request.FILES['image'] fs = FileSystemStorage() image_fs = fs.save(image.name, image) file_url = fs.url(image_fs) image_new = UserMembership.objects.filter(user=user).update(image=image_fs) return render(request, 'main/settings.html', { 'file_url': file_url }) also when I click to image in admin panel i get this This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>NoSuchKey</Code> <BucketName>financal-space</BucketName> <RequestId>tx000000000000004683770-005ec5341d-ab90b1-ams3b</RequestId> <HostId>ab90b1-ams3b-ams3-zg02</HostId> </Error> Help me pls !! It is very important . I can't fix it for 3 days -
How can I build a tree based on the answers that the user will insert in the form? DJANGO/PYTHON
I've created a forms in Django, and I would like to build something like a tree with the TAG and Level fields forms. I have in the level Field four options (Plant, System, Equipment, Part). The user will insert a tag and choose a level, if he selects System for example, I want to insert the forms inside of the level Plant. for example: CMI will be insert in the TAG Field, and would be LEVEL= PLant, after the user would insert another tag. ex: SSP and chosse LEVEL = SYSTEM. CMI ╚══ CMI/SPP How can I do this? my models: class Tree(models.Model): TAG = models.CharField(blank=True, max_length=250) name = models.CharField(max_length=250,blank=True) level = models.CharField( default='Plant', blank=True, max_length=50, choices=( ('Plant', 'Plant'), ('System', 'System'), ('Equipment', 'Equipment'), ('Part', 'Part'), ) ) def __str__(self): return self.nome class FormTree(forms.ModelForm): class Meta: model = Tree exclude = () my views: def register_tree(request): if request.method != 'POST': form = FormTree() return render(request, 'tree/register_tree.html', {'form': form}) form = FormTree(request.POST, request.FILES) if not form.is_valid(): form = FormTree(request.POST) return render(request, 'tree/register_tree.html', {'form': form}) form.save() return redirect('register_tree') def tree(request): arvore = Tree.objects.all() search_id = request.GET.get('search_id') search_name = request.GET.get('search_name') search_tag = request.GET.get('search_tag') search_level = request.GET.get('search_level') if search_id: tree = Tree.objects.filter(id=search_id) if search_name: tree … -
BaseModelFormSet __init__ method not fired if clean method is fired?
I'm using a BaseModelFormSet where I'm displaying several form values on the template. The BaseModelFormSet looks like this: class BaseFormSetValidation(BaseModelFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) days = ['day_1', 'day_2', 'day_3', 'day_4', 'day_5', 'day_6', 'day_7'] for form in self.forms: if form['status'].value() != 'open': for day in days: form.fields[day].widget.attrs['readonly'] = True def clean(self): super().clean() days = ['day_1', 'day_2', 'day_3', 'day_4', 'day_5', 'day_6', 'day_7'] for form in self.forms: for day in days: current_day = form.cleaned_data.get(day) if current_day is not None and current_day > 24: raise ValidationError([{day: ["Submitted hours per day cannot exceed 24 hours"]}]) Basically, if the form instance is not "open", it should be read only (form should not be editable) - works fine so far. However, if I purposely add a number higher than 24 to another, editable form (which is what the clean method catches), the ValidationError is correctly fired, but the __init__ method makes all the other form(s) editable - not sure why. -
how to create a trigger event whenever the my models are populated in admin?
I want to create a trigger that will send the model's data to my script whenever they are populated via admin. Is this possible? -
how to get the actual instance in django ManyToMany through?
i have a project i want to get the actual instance for updating in signals , i want to filter by two pk instances class Product(models.Model): name = models.CharField(unique=True, max_length=50) class Order(models.Model): cutomer = models.CharField(max_length=50) products = models.ManyToManyField(Product ,through='ProductOrder') class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) item = models.ForeignKey(Order, on_delete=models.CASCADE) quantity_order = models.PositiveIntegerField(default=1) class ReturnOrder(models.Model): cutomer = models.ForeignKey(Order,on_delete=models.CASCADE) products = models.ManyToManyField(Product ,through='UpdateOrder') class UpdateOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) ordering = models.ForeignKey(ReturnOrder, on_delete=models.CASCADE) return_quantity = models.PositiveIntegerField(default=1) i want filter instances by Order pk and ProductOrder when a new UpdateOrder instance created then it will update ProductOrder in the actual Order instance this is my signals def return_pre_save(sender , instance,created , *args,**kwargs): if created: Order.objects.filter(pk=instance.ordering_id,how to get the ProductOrder id of an object ).update(update some stuff) pre_save.connect(return_pre_save, sender=UpdateOrder) i want to get the instance id of ProductOrder , i mean filter by two pk -
Django ManyToMany with to choices
I am trying to setup a multiselect to choices. type = models.CharField(max_length=20, choices=TYPE_CHOICES) The above is what I am currently doing, but it only gives me the choice to pick one of the items in "TYPE_CHOICES". I want to be able to select multiple items in "TYPE_CHOCIES". I could do this by using a ManyToMany relationship and making Choices a model, but I prefer to just keep it simple. I have tried searching and I am not finding anything or if this is even possible? -
How to add (css) class to Django-Filter without modifying field-type?
I wish to add CSS classes to my django_filters filter form, nonetheless, I do not manage to get it working and I do somehow try something I either get an error (see below) or it messes with the HTML tag, e.g. a dropdown (select tag) gets converted to a text field. I currently only managed to get the labels changed: #filters.py class OrderFilter(django_filters.FilterSet): class Meta: model = Order fields = ['order', 'customer', 'status'] exclude = ['delivery_date'] def __init__(self, *args, **kwargs): super(OrderFilter, self).__init__(*args, **kwargs) self.filters['order'].label = "Order N°" self.filters['customer'].label = "Customer" self.filters['status'].label = "Status" #not working --> self.filters['order'].widget.attrs['class'] = 'text-red-900' self.filters['status'].widget.attrs['class'] = 'text-red-900' I get the error: "'ChoiceFilter' or "NumberFilter" object has no attribute 'widget'". Is there somehow a possibility to easily add CSS classes to the filter fields? -
Hard coding if statements in templates
I have been working on an e-commerce website for a while. There three types of products there: Clothes, Accessories and Shoes. There is item table and category table. In the category table are the category objects(clothes,accessories, shoes) which maybe in the near future won't be changed. In my case i don't want accessories to have sizes. So when i am rendering the templates i do if statement which checks if the item's category is accessory. If it is I don't render the size field's value(which is null). Everything works good but i think that there is a better way to achieve this functionality without hard coding the if statement. Can you give me an advice for improving the code? models.py class ItemCategory(models.Model): category = models.CharField(max_length=20) class Item(models.Model): seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) category = models.ForeignKey(ItemCategory, on_delete=models.SET_NULL, null=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) price = models.IntegerField(null=True, blank=True) price_negotiable = models.BooleanField(default=False) discount_price = models.IntegerField(null=True, blank=True) size = models.ForeignKey(Size, on_delete=models.SET_NULL, null=True, blank=True) condition = models.CharField(choices=CONDITION_CHOICES, max_length=9) description = models.CharField(max_length=500) {% if item.category.category != 'accessories' %} Size: {{ item.size.size }} {% endif %} -
Multiple fields assignment in Django models
I have several fields in my models that share the same caracteristics and I would like to declare them in one line with something like this: class Shop(models.Model): id, name, brand = models.CharField(max_length=12) Or: class Shop(models.Model): id = name = brand = models.CharField(max_length=12) instead of doing this: class Shop(models.Model): id = models.CharField(max_length=12) name = models.CharField(max_length=12) brand = models.CharField(max_length=12) But Django complains with a TypeError in the first case saying that 'CharField' object is not iterable, and with admin.E108 error in the second case. So my question is how can I declare multiple fields that share the same caracteristics in a single line of code with Django? it looks to me that the second cases is not related to Python. -
my articles shows up oldest first but i want it to show new one first like date wise new one should appear on top
hi i want to show my articles latest article should appear first i used class Meta in models but its not working it does not show any error but it it shows old articles on top. if anyone can please help that would be very helpfull models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(default=timezone.now) thumb = models.ImageField(default='default.png', blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) class Meta: ordering = ['-date'] def __str__(self): return self.title def snippet(self): return self.body[:100]+'...' views.py from django.http import HttpResponse from django.shortcuts import render, redirect from .models import Article from django.contrib.auth.decorators import login_required from . import forms def article_list(request): articles = Article.objects.all().order_by('date') return render(request, 'articles/article_list.html', {'articles': articles}) def article_detail(request, slug): # return HttpResponse(slug) article = Article.objects.get(slug=slug) return render(request, 'articles/article_detail.html', {'article': article}) @login_required(login_url="/accounts/login/") def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): # save article to db instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('articles:list') else: form = forms.CreateArticle() return render(request, 'articles/article_create.html', {'form': form}) -
Is there a way to output just the first element in this if statement, Django template?
In my table and in the some record I have lot of link_img, but I want only the first link_img, what can I do ? I have something like this in my temp {% for link in sousimg %} {% if article.article_img.id == link.img_link.id %} {{ link.link_img }} {% endif %} {% endfor %} -
Unable to create formset from model
I have the following models: class Answer(models.Model): review = models.ForeignKey(Review,related_name='answer_review_assoc',blank=False,on_delete=models.PROTECT) question=models.OneToOneField(Question,related_name='answer_question_assoc',blank=False,on_delete=models.PROTECT) answer=models.CharField(max_length=250,blank=True,null=True) creation_date=models.DateTimeField(blank=False) last_update_date=models.DateTimeField(auto_now=True) created_by=models.ForeignKey(settings.AUTH_USER_MODEL, related_name='answers_created_by',on_delete=models.PROTECT) last_update_by=models.ForeignKey(settings.AUTH_USER_MODEL, related_name='answers_last_update_by',on_delete=models.PROTECT) class Meta: verbose_name_plural = "Answers" class Question(models.Model): question_text=models.CharField(max_length=200,blank=False) question_choice_type=models.CharField(max_length=3, blank=False,choices=QUESTION_CHOICE_TYPE) mandatory=models.BooleanField(blank=True) creation_date=models.DateTimeField(blank=False) last_update_date=models.DateTimeField(auto_now=True) series_type=models.CharField(max_length=3,blank=True,null=True,choices = Series.get_choices_models()['series_type']) created_by=models.ForeignKey(settings.AUTH_USER_MODEL, related_name='questions_created_by',on_delete=models.PROTECT) last_update_by=models.ForeignKey(settings.AUTH_USER_MODEL, related_name='question_last_update_by',on_delete=models.PROTECT) choices=models.ManyToManyField(Choice,blank=True,related_name='question_choices_assoc') question_type=models.CharField(max_length=10, blank=False,choices=QUESTION_TYPE) Form: class AnswerForm(ModelForm): answer = forms.CharField(label='Answer Text',required=True,widget=forms.TextInput(attrs={'placeholder': 'Answer Text','class':'form-control'})) class Meta: model=Answer fields=['answer'] def __init__(self, *args, **kwargs): super(AnswerForm, self).__init__(*args, **kwargs) # question_text=self.instance.question.question_text # print(question_text) I want to create formset of Answer and initialize with some questions This is what I do: q=Question.objects.filter(question_type='PL').first() ansfs=formset_factory(AnswerForm) fs=ansfs(initial=[].append(q)) Now what i want is to set the label of the answer field in AnswerForm to question_text coming from initial values. But i am unable to access self.instance.question.question_text in __init__ method of AnswerForm. models.Answer.Answer.question.RelatedObjectDoesNotExist: Answer has no question. Please help. -
Sum fields in forms.py
My models.py class Expert(models.Model): first = model.IntegerField() second = model.IntegerField() third = model.IntegerField() ...and other 169’s fields like this... All variables get from forms.py (people fill form, choose 1 or 0). How to sum ‘first’,’second’ and ‘third’? Result need in float type and how show it in admin? -
Does not display reply
I have a problem, so I turn to you. I need to display the answer to the comment, through the admin it is possible to do it, but if you write the text in the form, it will not display this text. This is my code, thanks in advance HTML: {% for reply in comment.replies.all %} <div class="comment-avator set-bg" data-setbg="/profile_images/{{ reply.user.profilemodel.img }}"></div> <h5>{{ reply.user.username }} <span>{{ reply.comments_date }}</span> </h5> <p>{{ reply.text }} <a class="comment_likes" href='{% url "comment_likes" comment.id %}'>{{ comment.likes.count }} Like</a> </p> {% endfor %} <form method="post" class="comment-form"> {% csrf_token %} <input type="hidden" name="comment_id" value="{{ comment.id }}"> <h4 class="comment-title">Leave comment</h4> <div class="row"> <div class="col-md-6"> <textarea type="text" placeholder="Your comment" name="reply" id="reply" maxlength="250"></textarea> </div> <div class="col-lg-12"> <input class="site-btn btn-sm" type="submit" value="leave"> </div> </div> </form> Model: class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments') text = models.CharField(max_length=250) comments_date = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, blank=True, related_name='liked_comments') reply = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='replies') def __str__(self): return f'{self.user}/{self.article}' Form: class ReplyForm(forms.Form): reply = forms.CharField(label='reply', max_length=250) Views: def article_detail(request, slug): article = get_object_or_404(Article, slug=slug) success_url = "/" ctx = { 'article': article, 'comments': article.comments.all(), } ctx.update(sidebar_ctx()) user = request.user if request.method == 'POST': form = CommentsForm(request.POST) if form.is_valid(): reply_id = request.POST.get('comment_id') comment_qs … -
Django and angular setup with output hashing enabled
I have setup my django and angular 9 application by following this post: https://medium.com/swlh/django-angular-4-a-powerful-web-application-60b6fb39ef34 I want to use output hashing to avoid problems with resource caching by browser. Is there a way. Perhaps by using wildcards to match a particular type of file eg. style.*.css!! Or set header on all such files to not to cache? -
Read the Docs local install: Celery ValueError: signal only works in main thread
I have a local readthedocs install and get a ValueError exception when trying to import a project. I'm on release 5.1.0, running python 3.6 on Debian buster with celery 4.1.1 (from the requirements files). From the debug.log: [19/May/2020 23:31:11] celery.app.trace:124[24]: INFO Task readthedocs.projects.tasks.send_notifications[39551573-cfe1-46c1-b7e2-28bde20fd962] succeeded in 0.005342413205653429s: None [19/May/2020 23:31:11] celery.app.trace:124[24]: INFO Task readthedocs.oauth.tasks.attach_webhook[119bed10-cacc-450c-bd51-822e96faffd7] succeeded in 0.016763793770223856s: False [19/May/2020 23:31:11] celery.app.trace:249[24]: ERROR Task readthedocs.projects.tasks.update_docs_task[b6c22791-f1c6-4ddb-b64a-68d141580c30] raised unexpected: ValueError('signal only works in main thread',) Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/celery/app/trace.py", line 375, in trace_task R = retval = fun(*args, **kwargs) File "/readthedocs.org/readthedocs/projects/tasks.py", line 448, in update_docs_task signal.signal(signal.SIGTERM, sigterm_received) File "/usr/local/lib/python3.6/signal.py", line 47, in signal handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler)) ValueError: signal only works in main thread I'm using manage.py runserver to run readthedocs, so I tried the --noreload option which has no effect, and the --nothreading option, which causes pages to hang forever. -
Which technologies are more prefered in this situation
I'd like to develop a web application and cant decide what technology to use. I have in mind NodeJS with mongodb database, on the other hand i think about Django with one of the sql databases. I need to focus more on backend stuff of my application. The application is something similar to an eshop, and i'd like to add several shops and every shop is going to have different products and product categories. Im not sure what information is required to answer this question... [EDITED | Also which database actually fits better for this purpose? Is using nosql's with django a nice practice? ] What is better to use and why? Thank you for your asnwers! -
django Join After Group By
I need to have an subquery as the FROM clause in django ORM, like so select * from ( select stuff from table where ... group by ... ) left outer join table2 left outer join table3 How can I do this ? Inspired by This post -
Downloading and Parsing xml file with Django
Hey am working on a django project and i need to download and parse data stored in an xml file to db, how can i do that?. And where can i store my xml file inside my django project -
Django count() function
(noob question I know) Hi everybody, I keep having a problem with the count() function. In my website I added some items to the database, then I'd like to show on the hompage the number of items, but the count doesn't show up. I really can't figure out what I'm doing wrong. this is the code: View.py: class homeView(TemplateView): template_name = 'search/home.html' def conto(self): album = Info.objects.all().count() return album Html file: <h3 style="text-align:center;"> ALBUM TOTALI: {{album}} </h3> -
Filtering rows by datetime plus number of days in django queryset
I have a model with a field datetime as reference date and a field integer that holds the number of days to count from reference date, I need to filter out the rows whos reference_date + number_days is lesser than current_date in django orm. I have tried with RawSQL, delegating the filter to mysql, but i need to access a column of the row, and i don't know how to include an F expresion inside a RawSql expresion, i tried joining strings but it doesn't work. Included my model description. class ActionData(models.Model): properties = models.ManyToManyField(Property, through='ActionProperties') action = models.ForeignKey(Action, on_delete=models.CASCADE) description = models.TextField(null=True) days = models.IntegerField(default=0) promocioned = models.BooleanField(default=False) reference_date = models.DateTimeField(null=True) modified_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def __str__(self): return str(self.pk) + self.action.name -
Trying to figure out how to use decorator_from_middleware functionality
As the title states I want to use the 'decorator_from_middleware' function from here: https://docs.djangoproject.com/en/2.1/_modules/django/utils/decorators/ However I'm just confued on how to properly use it. I have my custom middleware class and all the normal middleware stuff set up. How would I incorperate this function to be able to use my middleware as a per view basis with the help of a decorator? Example: Let's say I have some middleware class class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response How would I use decorator_from_middleware(middleware_class): and apply it to a particular view? -
Django-Haystack and Solr 8.5.1
Does Django haystack work with the latest Solr update (8.5.1)? Plus how do I setup with my Django blog project -
Django website upload images to the wrong s3 bucket
I'm fairly new to AWS and I created two buckets to try and test them. Each has different names and regions, i.e., us-east-2 and ap-southeast-1. I specified the region in my bash profile however the images uploaded via django admin are sent to the bucket with region us-east-2 rather than the bucket with region ap-southeast-1. What could I have missed or is there a setting that I should do? Thanks in advance! Here is my CORS Configuration: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CORSConfiguration> Here is my settings.py: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') # ap-southeast-1 AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Filter objects based on expiry date using Q and "gt" Django
I have a model that it has an expiry field. This field can also be null. How can I return only object that either do not have expiry date or their expiry date is less than the current date? this is my model: class Buzz(models.Model): nickname = models.CharField(max_length=30, blank=True, null = True) content = models.TextField(validators=[MaxLengthValidator(550)]) author = models.ForeignKey(Profile, on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now_add=True) expiry = models.DateTimeField(blank=True, null=True) I want something like: now = timezone.now() Buzz.objects.filter(Q(self.expiry__gt = now) | Q(self.expiry = null )) But it's not returning the correct objects, how can I achieve this? I checked if the expiry field exists for some objects and it does.