Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect to a remote Database in Django using PostgreSQL
Me and my friend are doing to joint app together and was wondering if there is an easy way to connect to his database so I can migrate as well? Thank you Onur -
Access data when overriding Django admin index_template
I am trying to create a dashboard type table on my Django admin Dashboard page. I have made an override to the template using the following in my urls.py: admin.site.index_template = "admin/my_custom_index.html" admin.autodiscover() So I can add HTML to this my_custom_index.html and it will show on the dashboard, however I need to access model data (ex. Customer.objects.all()) from within this HTML page, is this possible? I have made it work before when I extended a change list view, but because I directly updated the index_template from the urls.py file I cannot figure this out. -
django: how to load the static files with hash/md5 appending correctly?
using Django 3 I followed the Django Doc https://docs.djangoproject.com/en/3.0/ref/contrib/staticfiles/#manifeststaticfilesstorage to export my static files with a hash appending. settings.py production STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' static_root folder (output) static_root/ staticfiles.json static_root/css/ project_styles.87c2920e7bc3.css project_styles.css everything is collected correctly. Afterwards i uploaded everything to my apache static server. And i set off / comment the STATICFILES_STORAGE . That is how i understand the Doc´s? If i leave this setting on in production i get an 500 Error. settings.py production # STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' After restarting my Django app in production, my site is still loading project_styles.css but not the hash Version project_styles.87c2920e7bc3.css in my browser. Even if i delete project_styles.css Django will not serve the hash version. Question Did i miss some settings in the settings.py in production mode? In the Doc´s they mention to set STATICFILES_STORAGE = django.contrib.staticfiles.storage.StaticFilesStorage but it shows no difference. And as it is mentioned it´s only for testing. What i have to do to load the correct static hash version in production? do i have to set something in my templates, so that django will look into the json file for the correct hash version? Or do i have to name the hash file? -
Plotly express line charts plots differently (all over the plane)
Hi all I am currently developing a django web app, I have used plotly (python package not the django-plotly) to do the graphing. On my development environment my charts work fine like below, But when I clone my repositery and run it on different machine graphs look like this, Following are my configurations, I use Mongodb and x axis values are as type string Tested on both windows and a centos machine still get the below wired looking graph I pass the data as a list of dictionaries (not as a dataframe) Added plotly js library in static files (I dont see a effect on this) def lineGraph(response): fig = px.line(response, x="trans_date", y="total_withdrawal", title='Total Withdrawals', template="plotly_dark") fig.data[-1].name = "Withdrawals" return plot(fig, output_type='div') First 5 elements: [{'unit_id': 2, 'trans_date': '2017-01-03', 'branch': 'test', 'total_withdrawal': 4100}, {'unit_id': 2, 'trans_date': '2017-01-09', 'branch': 'test', 'total_withdrawal': 18300}, {'unit_id': 2, 'trans_date': '2017-01-14', 'branch': 'test', 'total_withdrawal': 20000}, {'unit_id': 2, 'trans_date': '2017-01-17', 'branch': 'test', 'total_withdrawal': 800}, {'unit_id': 2, 'trans_date': '2017-01-18', 'branch': 'test', 'total_withdrawal': 158800}] -
hierarchical group django query
I'm trying to get a hierarchical group in categories using only one or maximum two django querysets. I got Django this model: from django.db import models class Category(models.Model): level = models.CharField(max_length=10) name = models.CharField(max_length=45) parent = models.ForeignKey('Category') and this is the queryset i got: categories = Category.objects.all().order_by("parent").order_by("level").values() I'm trying to do this: [ { "id": 1, "name": "Tecnología", "level": "l1", "parent_id": null, "child":[ { "id": 3, "name": "Computación Lorem", "level": "l2", "parent_id": 1, "child":[ { "id": 5, "name": "Portatiles", "level": "l3", "parent_id": 3 } ] } ] } ] I know this json has a new label ("child"). I can't create that, so i need a way to look close as possible to the top one. But this is what i got: [ { "id": 1, "level": "l1", "name": "Tecnología", "parent_id": null, }, { "id": 3, "level": "l2", "name": "Computación Lorem", "parent_id": 1, }, { "id": 5, "level": "l3", "name": "Portatiles", "parent_id": 3, } ] Can you people give me a friendly hand, please? i'll apreciate it so much. -
Displaying "Like" and "Dislike" buttons if user has liked a post with Django
thank you for taking the time to read this. I'm working on a project for CS50W in which I have to display a series of posts which users can like and then dislike. I can successfully display the number of likes but I can't get the "Like" Button to change into "Dislike" once this is done. Here's the relevant code: views.py def index(request): return render(request, "network/index.html", { "posts": Post.objects.all().order_by('time'), "form": NewPost(), "likes": Like.objects.all(), }) ... def like(request, post_id): if request.method == "POST": #make sure user can't like the post more than once. user = User.objects.get(username=request.user.username) #find whatever post is associated with like post = Post.objects.get(id=post_id) #access liked values: if Like.objects.filter(user=user, post=post).exists(): Like.alreadyLiked = True return HttpResponseRedirect(reverse('index')) else: newLike = Like(user=user, post=post) newLike.alreadyLiked = True post.likes += 1 post.save() newLike.save() return HttpResponseRedirect(reverse('index')) Then models.py from django.contrib.auth.models import AbstractUser from django.db import models import datetime class User(AbstractUser): pass class Post(models.Model): text = models.CharField(max_length=127) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author") time = models.TimeField(auto_now=False, auto_now_add=True) likes = models.PositiveIntegerField(default=0) def __str__(self): if self.likes == 1: return f"{self.user} ({self.time}): {self.text} - {self.likes} Like" elif self.likes == 0: return f"{self.user} ({self.time}): {self.text} - No Likes" else: return f"{self.user} ({self.time}): {self.text} - {self.likes} Likes" class Like(models.Model): user = models.ForeignKey(User, … -
How to manage IAM User Secret Keys in Django
I have a Django project (deployed on EBS) that uses several AWS services (SES, S3, etc.) through an IAM user. I am wondering what the best way to store this IAM user's credentials in the Django project is. I have thought of a few approaches and have a few questions for each: Make a .env file with the credentials. Can this be hacked though? Is this the most secure way? Use Amazon Secrets Manager to create a secret with the credentials. I tried this, but then realized that you need to supply credentials to use it (😅). Is there a better method? What would you recommend? -
How to insert value to {% url tag %} from js script inside django template
I'm using leaflet JS in Django template. I want to show markers on map where latitude and longitude is taken from a queryset. I figured out that I can send queryset by views and then using Django template language use it inside to set lat i lon to particular marker. I would like to have an image in popup of marker and here my problem comes. I know that I can't use JS because it's client side vs Django template is server side but how to solve case where you want to dynamically create markers and popup with image which is in database. Should I use AJAX to do that? my views: class MapView(ListView): template_name = 'map.html' model = Post queryset = serialize('json', Post.objects.all(), fields = ['lat','lon', 'image']) and template where below for loop is marker1 where popup is hard-coded and works ok: var map = L.map('map').setView([49.175573,20.072700], 11); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); var post_base = {{object_list|safe}} for (let index = 0; index < post_base.length; index++) { console.log(post_base[index]['fields']['lat']); var image_path = post_base[index]['fields']['images'] marker = new L.marker([post_base[index]["fields"]["lat"],post_base[index]["fields"]["lon"]]).addTo(map) .bindPopup("<img style=10%; src={% static 'images/????????????????????????'%}/>"); } marker1 = new L.marker([49.295236, 20.413089],{opacity:0.5}).addTo(map) .bindPopup("<img src={% static 'images/lomnica_image.jpeg' %}/>"); </script> Could anybody explain what … -
Django - Call a specific method in a specific time
I am trying to call method in my Django application and I came across something new called 'celery'. But I am not sure how to use it. In my views.py, I have a method which I want to execute once in every week, but for test purposes, I am just calling it for one minute once. from celery.schedules import crontab from celery.task import periodic_task @periodic_task(run_every=crontab(hour="*", minute="*", day_of_week="*")) def every_day(): print("Method Called") After this when I call python3.7 manage.py runserver, the method is not called. Has anyone implemented this technique? Kindly help me out if someone knows more about this. -
Local & Prod Settings.py in Django
I've implemented the normal way to do local and prod with two settings.py files and an __init__.py: from .base import * from .production import * try: from .local import * except: pass The problem is that in some of my views.py files, there is also specific functionality depending on local or prod, for example integrating django axes in prod. How can I check if I use the local or prod settings file in my views.py files? Thanks!! -
Django DateInput widget format doesn't change
I hate a Datetime field and a widget to select a date. Currently it's in mm/dd/yyyy format. I need it to be in dd/mm/yyyy, nothing suggested in other answers seems to have a result: My settings.py DATE_FORMAT = '%d/%m/%Y' DATE_INPUT_FORMATS = ['%d/%m/%Y'] USE_I18N = True USE_L10N = True In my forms.py: class MyForm(forms.ModelForm): date_start = DateField(widget=forms.widgets.DateInput(format='%d/%m/%Y', attrs={'type': 'date'}), input_formats= settings.DATE_INPUT_FORMATS) What could be the problem? -
How docker can come into play in my web application?
I have created a web app that needs some isolation/containerization to make it secure .The description about app is : I have created a django based web platform that takes python file as an input containing a function, then with the help of eval function i am passing arguments and executing that file .The function is returning a value that i am using in my views of django for some calculation and then rendering the computed result to web page. Here the problem is,after deployment what if someone has uploaded a malicious code so to reduce the damage to some extent i was advised to use docker , but i don't know how and where can docker be implemented in my web app. My web app is totally based upon django and uses no external frontend framework like(react,angular etc.) If someone can help me sorting my issue then it would be of much help. Also Since i don't know about any kind of containerization ,hope my question makes sense and do correct me if it lacks something. Any resources or reference will be helpful. Thanks in advance. -
Elasticsearch_DSL displays only the top ten search results
I am trying to use Elasticsearch-dsl-py to index certain data. When executing a query, I found that only the first ten results were displayed. When I did a search, I found that Elasticsearch is by default showing a result of a size not exceeding 10. How can I display more results? # Create the mapping of mymodel def bulk_indexing(): NormalizedEventtable.init() es = Elasticsearch() bulk(client=es, actions=(b.indexing() for b in models.NormalizedEvent.objects.all().iterator())) # Search function def search(client_ip_address): s = Search().filter('match', client_ip_address=client_ip_address) result = s.execute() for item in result: print(i) print(item.username) i=i+1 bulk_indexing() search('10.7.11.2') -
Django redirect by calling function view?
I need to redirect while keeping the original request. Is this approach inline with Django 3 logic or am I creating some furute catastrofe? def final_view(request): # use some_new_variable to do stuff and then display it in the template return render(request, another_template_name, {}) def original_view(request): # do stuff request.some_new_variable = "x" return final_view(request) -
Djnago Class based views related
How to get a list of n no.of model entries from a model having m no.of entries Indetail.....I have a model of 50 entries i want a query set of 6 ramdom entries from that 50 entries using built-in class based ListViews. -
Cannot resolve keyword 'month' into field. Choices are: calendar, color, completed, date, date_created, id, title, user, user_id
First of all thanks to you for stoping for a while to help me out form the problem even your small help matters a lot. I am trying to edit filter my form using the month selected by the user is there any way to resolve the error. when i select a month form filter form and submit it gives the error mentioned above. I am a begginer of django even ur small helps matters a lot My Models lass Event(models.Model): COLOR_CHOICES = ( ("ORANGE","Orange"), ("GREEN","Green"), ("YELLOW","Yellow"), ("BLUE","Blue"), ) CALENDAR_CHOICES = ( ("WORK","Work"), ("PROJECT","Project"), ) user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=200) date = models.DateTimeField(default=datetime.now,validators=[validate_date]) completed = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now=True,auto_now_add=False) color = models.CharField(max_length=9,default="ORANGE",choices=COLOR_CHOICES) calendar = models.CharField(max_length=9,default="WORK",choices=CALENDAR_CHOICES) # end_time = models.DateTimeField() def __str__(self): return self.title MONTH_CHOICES = ( ("1","Jan"), ("2","Feb"), ("3","Mar"), ("4","Apr"), ("5","May"), ("6","June"), ("7","July"), ("8","Aug"), ("9","Sep"), ("10","Oct"), ("11","Nov"), ("12","Dec"), ) class Approval(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User,on_delete=models.CASCADE) approved = models.BooleanField(default=False) comment = models.CharField(default="Approved",max_length=250) month = models.CharField(max_length=120, choices=MONTH_CHOICES, default="Jan") # month = models.CharField(choices=Month_Choices,default=) def __str__(self): return str(self.approved) Views.py def user_event_view(request, pk): today = datetime.now() user = User.objects.get(id=pk) events = user.event_set.all().order_by('date').filter(date__year=today.year, date__month=today.month) event_filter = EventFilter(request.GET, queryset =events) if request.method == 'POST': form = ApprovalForm(request.POST) if form.is_valid: approval = form.save(commit=False) approval.user = … -
Is there a way to update continiously server side data when there is no connection with client?
I am creating a Real-time browser multiplayer game in which you move squads around the globe and you can fight other squads nearby. I am using django framework and I will use django-channels which uses webSockets for the real time notifications. In the database each squad has it postion in latitude and longitude health, moral. The problem is that, when you move a squad, and the user closes the browser, How can I keep updating that squad position to begin the interaction with possible nearby squads. For example I want to move my squad from A to C, it will take 6 hours so I disconnect (close browser) after 30 min. BUT after 4 hours, my squad encounters a enemy squad in B and a fight should begin updating my as well enemy squad attributes (health, moral, squad stopped). How can I keep updating my squad postion while there is no user who pushes data (POST, GET, WebSocket) and trigger a change in the database. I came with Long-polling: Making request every x time (no need to be very frequent since movement is slow). But for this, Will I need to use a separate "polling server" or process? -
Template does not exist from the main app
I have a project that looks like this main --templates ----main ------contact.html --settings.py app1 app2 app3 app4 Each of my other apps templates work correctly. But now I am trying to reference a template in my main app but I get the error Template does not exist Since this is my main app (base app?) it doesn't have a apps.py and it isn't added to the INSTALLED_APPS. I altered my settings.py file to look like this.. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(MEDIA_ROOT), 'main/templates'], 'APP_DIRS': True, This works on my Windows dev station but when I push it to my live Ubuntu server is when I get the error. -
How can I delete a <dict> object in a Django QuerySet
I have this queryset in Django (lets call it qs) which 3 different object instances. Two of them are identical except for the image file: <QuerySet [ {'investment__name': 'Stefano', 'investment__net_returns': Decimal('11.00'), 'investment__my_images__image': '**investments/None/IMG01.JPG**'} {'investment__name': 'Stefano','investment__net_returns': Decimal('11.00'), 'investment__my_images__image': '**investments/None/IMG02.JPG**'}, {'investment__name': 'Alberto','investment__net_returns': Decimal('22.00'), 'investment__my_images__image': '**investments/None/IMG03.JPG**'} ]> I want to render in a template only the first object and the third of the queryset. I'm trying to delete the second but i don't now how to delete a queryset Object. The way I tried is something like this: inv="" for i,investment_instance in enumerate(qs): if investment_instance['investment__name']==inv: investment_instance.delete() else: inv=investment_instance['investment__name'] im=investment_instance['investment__my_images__image'] But of course investment_instance.delete() doesn't work. Any ideas? -
How to install Django to IntelliJ in community version?
Hi everyone is there any way to enable or add Django to IntelliJ ? sadly i can not add Django to module. with screenshots it will be more easy to understand. remember one thing that i already installed Django using terminal but still can not see in module -
Wagtail filter child pages by a ForeignKey
I'm using Wagtail, and I want to filter a selection of child pages by a Foreign Key. I've tried the following and I get the error django.core.exceptions.FieldError: Cannot resolve keyword 'use_case' into field when I try children = self.get_children().specific().filter(use_case__slug=slug): class AiLabResourceMixin(models.Model): parent_page_types = ['AiLabResourceIndexPage'] use_case = models.ForeignKey(AiLabUseCase, on_delete=models.PROTECT) content_panels = ArticlePage.content_panels + [ FieldPanel('use_case', widget=forms.Select()) ] class Meta: abstract = True class AiLabCaseStudy(AiLabResourceMixin, ArticlePage): pass class AiLabBlogPost(AiLabResourceMixin, ArticlePage): pass class AiLabExternalLink(AiLabResourceMixin, ArticlePage): pass class AiLabResourceIndexPage(RoutablePageMixin, BasePage): parent_page_types = ['AiLabHomePage'] subpage_types = ['AiLabCaseStudy', 'AiLabBlogPost', 'AiLabExternalLink'] max_count = 1 @route(r'^$') def all_resources(self, request): children = self.get_children().specific() return render(request, 'ai_lab/ai_lab_resource_index_page.html', { 'page': self, 'children': children, }) @route(r'^([a-z0-9]+(?:-[a-z0-9]+)*)/$') def filter_by_use_case(self, request, slug): children = self.get_children().specific().filter(use_case__slug=slug) return render(request, 'ai_lab/ai_lab_resource_index_page.html', { 'page': self, 'children': children, }) I've seen this answer, but this assumes I only have one type of page I want to filter. Using something like AiLabCaseStudy.objects.filter(use_case__slug=slug) works, but this only returns AiLabCaseStudys, not AiLabBlogPosts or AiLabExternalLinks. Any ideas? -
AWS Error Deploying Django App on Elastic Beanstalk- wsgi
I'm trying to deploy a Django App on AWS Elastic Beanstalk. I've followed the tutorial [here]https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html, except with my own app instead of their sample app. The app works perfectly when i run it locally. Whenever I try to deploy it on Elastic Beanstalk, I run into an error: Your WSGIPath refers to a file that does not exist. I've looked at many other similar posts, but none of their fixes worked for me. Attached below is my project directory and my config file that is supposed to point to the application object (named application) inside the wsgi file. I'm using the eb command line interface. option_settings: aws:elasticbeanstalk:container:python: WSGIPath: mysite.wsgi:application -
Getting field into Django serializer via two joins
I have the following Django query in a DRF GET call: word_saves = Word.objects.prefetch_related( "character__dictionary").filter(user_id=user_id) I am trying to output it with this serializer: class WordSerializer(serializers.Serializer): user_id = serializers.IntegerField() character_id = serializers.IntegerField() correct = serializers.IntegerField() mistakes = serializers.IntegerField() score = serializers.FloatField() trials = serializers.IntegerField() simplified = serializers.CharField( source="character__dictionary.simplified") def create(self, validated_data): return Word.objects.update_or_create( user_id=validated_data.pop('user_id'), character_id=validated_data.pop('character_id'), defaults=validated_data ) However this doesn't seem to be the way to grab the value. So how would I add a field connected by two joins to my serializer? Here are my models: class Word(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE) character = models.ForeignKey( Char, on_delete=models.CASCADE) correct = models.PositiveIntegerField(default=0) mistakes = models.PositiveIntegerField(default=0) score = models.FloatField(default=0) trials = models.PositiveIntegerField(default=0) class Char(models.Model): dictionary = models.ForeignKey( Dictionary, on_delete=models.CASCADE) user = models.ForeignKey( User, on_delete=models.CASCADE) active = models.BooleanField() class Dictionary(models.Model): traditional = models.CharField(max_length=50) simplified = models.CharField(max_length=50) pinyin_numbers = models.CharField(max_length=50) pinyin_marks = models.CharField(max_length=50) translation = models.TextField() level = models.IntegerField() class Meta: db_table = 'dictionary' indexes = [ models.Index(fields=['simplified', ]), models.Index(fields=['traditional', ]), ] My goal is to, from the Word model, select the simplified field off of the Dictionary model and put it in the serializer. -
Reuse JSON schema for single or a list of object(s)
I want to validate a single and list object(s) using JSON schema, but I am not sure how to reuse single object schema for list object schema. How is my current solution: { "foo_object_schema":{ "title":"Foo Object schema", "type":"object", "properties":{ "id":{ "type":"integer" }, "label":{ "type":"string" } } }, "foo_list_schema":{ "title":"FooList", "type":"array", "items":{ "foo_object":{ "title":"Foo Object schema", "type":"object", "properties":{ "id":{ "type":"integer" }, "label":{ "type":"string" } } } } } } I tried to use "#ref" but I failed to reuse it without putting foo_object schema in value of one field. I understand why it failed as the reference can only trace to the keys within one JSON schema. Here is my failed schema definition: { "foo_list_schema": { "title": "FooList", "id": "foo-list", "type": "array", "items": [ { "$ref": "#foo_object_schema" } ], "default": [] } } Any ideas to reuse the foo_object_schema to validate a list of foo objects without defining duplicate foo object schema? -
How to run tests in django project in PyCharm?
I created a test and I am trying to run in with PyCharm. Unfortunately, it fails with the following error: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. django.contrib.contenttypes is presented in INSTALLED_APPS and is on the top of the list. Can anybody help me to fix this issue and run my test through PyCharm?