Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I assign two foreign keys to two fields in one model in Django?
So I have Article model and Category model. And below are my models. class Category(models.Model): objects = models.Manager() category_kor = models.CharField(max_length=10, default="책") category_eng = models.CharField(max_length=10, default="book") def __str__(self): return self.category class Article(models.Model): objects = models.Manager() category_eng = models.ForeignKey(Category, on_delete=models.CASCADE, related_name = '', null=True, default=None) category_kor = models.ForeignKey(Category, on_delete=models.CASCADE, related_name = '', null=True, default=None) title = models.CharField(max_length = 100) subtitle = models.CharField(max_length = 100) url = models.URLField(max_length=10000) def __str__(self): return self.title So I've done some research and noticed that I have to do something with the related_name but I cannot fully understand and apply it to my model. Please help. Thank you very much. -
module 'search.views' has no attribute 'search'
I'm using the wagtail cms to do a search. I'm using the default search in the /search folder. When I preform a search I get the following exception thrown at me. AttributeError at /search/ module 'search.views' has no attribute 'search' This is my views.py from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.shortcuts import render from wagtail.core.models import Page from wagtail.search.models import Query def search(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: search_results = Page.objects.live().search(search_query) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = Page.objects.none() # Pagination paginator = Paginator(search_results, 10) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return render(request, 'search/search.html', { 'search_query': search_query, 'search_results': search_results, }) This is my template/search/search.html {% extends "base.html" %} {% load static wagtailcore_tags %} {% block body_class %}template-searchresults{% endblock %} {% block title %}Search{% endblock %} {% block content %} <h1>Search</h1> <form action="{% url 'search' %}" method="get"> <input type="text" name="query"{% if search_query %} value="{{ search_query }}"{% endif %}> <input type="submit" value="Search" class="button"> </form> {% if search_results %} <ul> {% for result in search_results %} <li> <h4><a href="{% pageurl result %}">{{ result }}</a></h4> {% if result.search_description %} {{ result.search_description }} {% endif %} … -
What is the best practice migrating from Django1.6 (Python2) to Django3 (Python3)
I would like to move my Django1.6 project that was written on Python2 to the newest version of both Django3 and Python3. The project is relatively big and it has to be running and maintainable through the whole process of upgrading. Here are two approaches that I tried: Move models and other necessary script to an independent file that both versions of the project can inherit from. I would only leave python2 dependent methods and rewrite them in Python3 folder. This resulted in a lot of issues with imports and inherits. Wrap the new version (django3 python3) over the old version (django1.6 Python2). Basically, old version was a folder in the new version. This way I could easily import any file from the old project, but managing a joint project like this was a big pain. -
vpython on django page
I would like to include a vpython image/animation in a webapp which I am creating via django. The idea is that a user can upload a file and that that file is then rendered using vpython and displayed as part of a webpage of the webapp. For now all I try to do is render the box() from vpython on that webpage. I have vpython7 installed and when I use the command line I do get a box in my browser however I have not been able to display as part of the django app webpage. I am rather new to django, webapps in general and vpython so I might be doing several thing wrong here but anyway I hope someone could help. Currently (but I have tried several things) I am doing this: views.py from django.shortcuts import render import vpython as vp def index(request): box1 = vp.box() return render(request, 'read_and_run_inp/index.html', {'box':box1}) and my index.html <html> <head> <title>Going to show the file</title> </head> <body> file goes here {{ box }} </body> </html> I keep getting the error: RuntimeError: There is no current event loop in thread 'Thread-1'. I have been trying to google this but I understand to little about … -
Getting Permission denied when Running collectstatic in Django in ElasticBeanstalk
When running the following command I am getting this error: Permission denied: '/opt/python/bundle/4/app/staticfiles' source /opt/python/current/env && python /opt/python/current/app/manage.py collectstatic --noinput Here are my settings: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' -
Cascading filters from the same Model Django
I am stuck in a situation and looking for some advise. I have a table/Model with a uniqueID, Category, Sub-Category & Distributor as columns. This data automatically gets updated from a workflow. I have joined this model to another as many to many. Can some one please advise how to create a form in such a way that the columns used from the above mentioned table are cascading and also unique? Thank you -
"Attempted relative import with no known parent package"
When i want to save this django file: from django.urls import path from . import views urlpatterns = [ path('index/', views.index, name='main-view') ] I get an error : "ImportError: attempted relative import with no known parent package" What should I do with it? -
isnull=Truel vs =None in django queryset
There are two ways to fetch objects which has None in particular column Book.objects.filter(publication__isnull=True).values('id') and Book.objects.filter(publication=None).values('id') Both results in same query which is SELECT id from book WHERE publication IS NULL; So, here I want to check, is there any difference between them from any perspective like "performance", "best practice", "pythonic way" and etc. So that I can decide which one to use. I have found a related question but answer is not satisfactory -
Django distinct() keep complaining "SELECT DISTINCT ON expressions must match initial ORDER BY expressions" , but I already given the expressions
I am trying to remove the duplicated organisation value in the stock management model. The field type of "organisation" is a foreign key type. I had checked the type of query set is <class 'django.db.models.query.QuerySet'>, below coding should be work, but the django keep complain about "SELECT DISTINCT ON expressions must match initial ORDER BY expressions". I had checked the doc of distinct https://docs.djangoproject.com/en/3.0/ref/models/querysets/ and follow exactly the same. The only difference is the docs getting the query set with {Model}.objects.all() and super().get_queryset(request, but both return exactly SAME TYPE of query set to me. Can someone explain what is the different between {Model}.objects.all() and super().get_queryset(request) class StockManagementAdmin(admin.ModelAdmin): list_display = ['organisation'] def get_queryset(self, request): qs = super().get_queryset(request).order_by('organisation').distinct('organisation') return qs -
Why Django/Python request doesn't work from production server
I work on a Django application. From python code I make a post to Zoom server: ... 1) conn = http.client.HTTPSConnection("api.zoom.us") ... 2) conn.request("POST", "https://api.zoom.us/v2/users/me/meetings", headers=headers, body=body) Headers and body are previously defined. This request is working from localhost but not from hosting server. I get the following error when running the second code-line with no other details: ConnectionRefusedError On hosting server I tried also to send the POST requests from terminal with curl command and it worked just fine. Any suggestion on what might be wrong ? -
Get complete parameter in URL including special characters
http://localhost:8000/pary/?url=https://jobs.chegg.com/#categoryName#-jobs&uid=OIKAHY&env_id=4 In my Django views for pary function, for the above url, when I am doing data = request.GET.get('url') I am getting data as https://jobs.chegg.com/ instead of https://jobs.chegg.com/#categoryName#-jobs Its ignoring all the content after # keyword. Please suggest how to get the complete url parameter value in python. -
Django signals to log entry
I'm trying to create a log entry for the model changes. I have created a modified_by field in the Order form. I want to save the username of the user in the modified_by field that would update the current model form or create a new order. Everytime I try to update the form I'm getting this error " 'NoneType' object has no attribute 'user'" signals.py from crequest.middleware import CrequestMiddleware from django.dispatch import receiver from django.db.models.signals import post_save from django.contrib.auth.models import User from .models import Order @receiver(post_save, sender=Order) def log_audit(sender, instance, created, **kwargs): request = CrequestMiddleware.get_request() modified_by = request.user class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) address = models.CharField(max_length=100) phone = models.IntegerField(max_length=11) method = (('Pay Upfront', 'Pay Upfront'),('Upon Delivery', 'Upon Delivery'),) shipping_method = models.CharField(max_length = 100, choices = method) language = models.CharField(max_length=30) box = models.CharField(max_length = 30) print_name = models.CharField(max_length=30) Diagnosis_note = models.CharField(max_length=30, blank=True) memo = models.CharField(max_length=100, blank=True) date_created = models.DateTimeField('date_created', default=timezone.now(), blank=False) manu_date = models.DateField('Manufacturing') status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") modified_by = models.CharField(max_length=100, blank=True) views.py def update_profile(request): try: profile = request.user.profile except Profile.DoesNotExist: profile = … -
What is use case for stealth_options in Django?
according to documentation: For custom management commands that use options not created using parser.add_argument(), add a stealth_options attribute on the command: class MyCommand(BaseCommand): stealth_options = ('option_name', ...) but why not just add these options to parser.add_argument()? Is there any profit to use stealth_options? -
How to annotate cumulative count to django queryset?
I have the following query, where I get a count of due tasks by week. I want to add also the cumulative count of due tasks. tasks = (Task.objects .annotate(year=ExtractYear('due_on')) .annotate(month=ExtractMonth('due_on')) .annotate(week=ExtractWeek('due_on')) .values('week', 'month', 'year') .annotate( due=Count('due_on') ).order_by('due_on') ) I've tried this by annotating a raw query like this, but this doesn't work. tasks = (Task.objects.filter( content_type__model='incometaxreturn' ) .annotate(year=ExtractYear('due_on')) .annotate(month=ExtractMonth('due_on')) .annotate(week=ExtractWeek('due_on')) .values('week', 'month', 'year') .annotate( due=Count('due_on'), cum_due=RawSQL("select Count(due_on) from tasks_task where extract('week', due_on) > %s", (today().isocalendar()[1],)) ).order_by('due_on') ) Any advise on best way to achieve this? -
How to speed up search including special character alternatives and nested loops (Python/Django webapp)?
I have three loops nested in a python/django webapp backend. all_recommended_services has all the service info I need to go through. alternatives has the search criteria entered in the search bar, including all special character alternatives (for example: u is substituted with ú, ö with ő and so on...). Finally, the loop for value in alternative: goes through all search words individually split by empty space. There are search keyword combinations which yield millions of alternatives, which totally kills the webapp. Is there an efficient way to speed this up? I tried to look into itertools.product to use cartesian, but it didn't really help me avoid more loops or speed up the process. Any help is much appreciated! for service in all_recommended_services: county_str = get_county_by_id(all_counties, service['county_id']) for alternative in alternatives: something_found = False for value in alternative: something_found = search_in_service(service, value, county_str) if not something_found: break if something_found: if not service in recommended_services: recommended_services.append(service) -
Can't deploy my django website to my cPanel/CentOS
I am relatively new to centOS, cPanel and everything within this world. I have a simple django website I followed the guide below step by step : https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-centos-7 and I still can't see my website when I visit my domain name. (zakwanji.com) My django project's path is as follows => ~/public_html/django/website/myproject -
Python, how to merge three dictionary in one filtering for key?
I have the following dictionaries: personale_dip={'a': [550.0], 'b': [157.65]} personale_dip_costo={'a': [1.0], 'b': [150.0]} personale_result={'a': 550.0, 'b': 23648.64} Personale_result has been obtained with the following code: personale_result={k : v[0] * personale_dip_costo[k][0] for k, v in personale_dip.items() if k in personale_dip_costo} I want to create a new variable, called final_value that, that for each key (matching them across dictionary) summarize all three dictionary giving me the following result: final_value={'a': [550.0, 1.0, 550.0], 'b': [157.65, 150.0, 23648.64]} How should I do it? Any help would be much appreciated. Thanks in advance! EDIT I have tried the following code: from collections import defaultdict personale_dip = {'a': [550.0], 'b': [157.65]} personale_dip_costo = {'a': [1.0], 'b': [150.0]} personale_result = {'a': 550.0, 'b': 23648.64} data = defaultdict(list) for d in [personale_dip, personale_dip_costo, personale_result]: for k, v in d.items(): if isinstance(v, list): data[k].extend(v) else: data[k].append(v) but the result is defaultdict(<class 'list'>, {'a': [550.0, 1.0, 550.0], 'b': [157.65, 150.0, 23648.64]}) If I want to obtain only {'a': [550.0, 1.0, 550.0], 'b': [157.65, 150.0, 23648.64]} How could I get it? -
Modify result list API django-rest-framework
I'm using django-rest-framework to create an API rest for my model, on my model I'm saving a range of dates (start and end) but on list for API I need one entry by date. #serializers.py class ShceduleSerializer(FlexFieldsModelSerializer): class Meta: model = Shcedule fields = ['id', 'start', 'end', 'user'] #viewsets.py class ShceduleViewSet(FlexFieldsModelViewSet): queryset = Shcedule.objects.all() serializer_class = ShceduleSerializer Now, I have something like this: "results": [ { "id": 1, "start": "2020-05-25", "end": "2020-05-29", "user": 50 }, But I need a one entry by date "results": [ { "id": 1, "date": "2020-05-25", "user": 50 }, { "id": 1, "date": "2020-05-26", "user": 50 }, { "id": 1, "date": "2020-05-27", "user": 50 }, { "id": 1, "date": "2020-05-28", "user": 50 }, { "id": 1, "date": "2020-05-29", "user": 50 }, -
TypeError: when calling User.objects.create()
I am able to get a TypeError when calling User.objects.create(). TypeError: User() got an unexpected keyword argument 'new_password' It would be great if anybody could figure me out where i'm doing thing wrong. thank you so much in advance. serializers.py : class PasswordChangeSerializer(serializers.ModelSerializer): old_password = serializers.CharField(write_only=True, required=True, max_length=30) new_password = serializers.CharField(write_only=True, required=True, max_length=30) confirm_password = serializers.CharField(write_only=True, required=True, max_length=30) class Meta: model = User fields = ['old_password', 'new_password', 'confirm_password'] def validate(self, data): old_password = data['old_password'] new_password = data['new_password'] confirm_password = data['confirm_password'] user_queryset = User.objects.all() if user_queryset.exists() and user_queryset.count() == 1: user_set = user_queryset.first() if not user_set.check_password(old_password): raise serializers.ValidationError({'old_password': 'Wrong password!'}) if confirm_password != new_password: raise serializers.ValidationError({'password': 'Password must be confirmed correctly!'}) return data def update(self, instance, validated_data): instance.set_password(validated_data['new_password']) instance.save() return instance views.py : class PasswordChangeAPIView(APIView): permission_classes = [IsAdminUser] serializer_class = PasswordChangeSerializer def post(self, request, format=None): data = request.data password_ser = PasswordChangeSerializer(data=data) if password_ser.is_valid(): password_ser.save() new_data = password_ser.data return Response(new_data, status=HTTP_201_CREATED) else: return Response({"msg":"invalid user!"}, status=HTTP_400_BAD_REQUEST) -
Make MEDIA_ROOT point to a website url instead of a local directory
So i have two Django projects, a main and a child-site, both are running on separate servers with separate domain-names. The media files are stored on and can only be posted to the main site, but the child-site has to access those media files somehow. How can i configure the MEDIA_ROOT setting (or something else, for that matter, in my project) so that the media files are automatically fetched from my main site. Or what changes can i make so that a fixed URL (of my main site) is added as a prefix when addressing any sort of media file. P.S. i am using pythonanywhere (two beginner/free accts., one for each site). -
django rest framework serializer allows extra fields
I'm creating a serializer for a view. It's not a ModelSerializer. This serializer contains the possible fields to send in the request. I have noticed that in the request I can send fields that don't appear in the serializer and it passes the serializer validation. For example, this the serializer: class MySerializer(serializers.Serializer): days = serializers.IntegerField(required=False) users_list = serializers.ListField(child=serializers.CharField(), required=False) class Meta: fields = [ 'days', 'users_list' ] In the View I do this: class UserValuesViewSet(viewsets.ModelViewSet): serializer_class = MySerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) return Response(status=status.HTTP_201_CREATED) I can see that the serializer is called, and when sending wrong values types I do get an exception, but when sending fields that don't appear in the serializer 'fields' it also passes the validation. For example: data = { 'days': '7', 'users_list': ['1234', '123456'], 'some_key': 'some_value' } How can I enforce the possible fields to send from the serializer? -
How to clone a model instance without cloning database relationship?
I'm building a cart model with the following code. from django.db import models class Item(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=8, decimal_places=2) def __str__(self): return self.name class Order(models.Model): date = models.DateTimeField(auto_now_add=True) transcation_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.date) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, blank=True, null=True) quantity = models.IntegerField(default=0, blank=True, null=True) The many-to-one relationship between Item and Order allow one Order to contain many Item and that look fine. A model instance can be simply cloned as already answer in this question. My problem is, if the price of an Item is changed. The price of contained items in Order is change to. But I don't want it to be changed. In the situation that customer already make a purchase, the price cannot be change. Is there anyway to clone the Order instance that completely not related to the other model? -
django python - how to list the progressive numeric value of a list
I would like to render a list obj with the progressive number as follow: List item 1 #(with id=10) List item 2 #(with id=2) List item 3 #(with id=3) and so on... I don't want to use the id/pk, since I am ordering the objects alphabetically. I'm using class based views: class EquipmentType_ListView(ListView): model = EquipmentType template_name = 'equipment/equipment_type.html' context_object_name = 'obj_list' #default = object_list ordering = ['type'] with a very simple model: class EquipmentType(models.Model): type = models.CharField(max_length=100, unique=True) date_posted = models.DateTimeField(auto_now_add=True) and the corresponding html: {% extends 'equipment/base.html'%} {% block content%} {% for instance in obj_list %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ instance.type }}</a> <small class="text-muted">{{ instance.date_posted}}</small> </div> </div> </article> {% endfor %} My question is, should I add the code to the views.py or directly to the html file(for cycle)? I'm not an experienced programmer, but I feel like it should be straight forward. Also it could be very useful to apply generically on all king of list elements rendered out. I was thinking there should be some "method" on the "for instance in obj_list" where you could print out directly on the html the instance's relative number, or perhaps adding an inner … -
Call celery task as per the value of datetimefield?
So i have this field in my models.py end_date = models.DateTimeField(blank=True, default=None, null=True) I want to run a celery task when the date is same as end_date. I know how to use periodic tasks.But I dont know to call it as per the value of end_date -
how to change id per form in select2 django formset
i need to increment id field forms per form default id which django provides is id_formsetname_set-0-fieldName and 0 increment one by one in my case named id_items_set-0-model and for second form will be id_items_set-1-model it display in inspect element source code from browser , i used this for loo script for (var i = 0; i < 10; i++){ $("#id_items_set-"+i+"-model").select2(); } but only worked for the first form , i dont want to use django-select2 my template looks like this this is my snippet <tbody class="tbody tb1 " id="form_set"> {% for item in items.forms %} <tr class="p-0 col-12"> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.price | add_class:'col-12 '}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.quantity | add_class:'col-12 '}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.model | add_class:'col-12 0model model' | attr:'id:id_items_set-0-model'}} </div> </td> </tr> {% endfor %} </tbody> <script type="text/javascript"> $(function(){ $('.tb1 tr:last').formset({ prefix:'{{items.prefix}}', addText:'add', deleteText:'remove', addCssClass:'btn btn-success', }); }) </script> <script type="text/javascript"> $(document).ready(function(){ for (var i = 0; i < 10; i++){ $("#id_items_set-"+i+"-model").select2(); } }) </script> only work for my first form then doesnt have any effect on other forms ? is there something i did wrongly in the script part please?