Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use jinja tag inside jinja tag
this is my code {% if {{post.author.profile.image.url}} is None %}.When i run this code i get:Could not parse the remainder: '{{post.author.profile.image.url}}' from '{{post.author.profile.image.url}}' How to solve this?And how to use a jinja tag inside jinja tag -
pandas: How to get first positive number?
I have a pandas dataframe like: name a b c jack -10 -6 -10 bill -6 -3 -5 ray -3 -12 -9 pew 4 -23 -2 shaun 12 3 2 mitch 3 5 2 How can i make a new dataframe which takes the first positive value from each respective columns(a,b,c) and divides all the values in that column with that selected first positive value of that column and store the result of division in place of all the values. The output should look like this name a b c jack -10/4 -6/3 -10/2 bill -6/4 -3/3 -5/2 ray -3/4 -12/3 -9/2 pew 4/4 -23/3 -2/2 shaun 12/4 3/3 2/2 mitch 3/4 5/3 6/2 -
Extract data from ORM and group by Date
I have a function which data like this : my_workouts = Workouts.objects.order_by('my_date').filter( my_date__year=year, my_date__month=month) I want to do the same with another model where I want to group the weight by date: Models.py class Quiz(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quizzes') scheduled_date = models.DateTimeField(max_length=255, default=0) weight = models.IntegerField(default=0) What I tried: data = Quiz.objects.orderby('scheduled_date'). filter(owner_id=request.user.pk,my_date__year=year, my_date__month=month). annotate(c=Sum('weight')).values('c') But this is not working, Please Help! -
How can I save my object in an other table?
I have this code : entryA = myTable1.objects.all().first() entryB = copy.deepcopy(entryA) But the problem is I would want to save entryB but if I do entryB.save() I will have a new entry in myTable1 whereas I want to have a new entry in myTable2 which contains the same fields. Could you help me please ? Thank you -
django join multiple tables via select_related()
I have three tables users, blocks, cars class User(models.Model): user_id = models.BigIntegerField(primary_key=True) is_out = models.CharField(default='N') birthday = models.DateTimeField() class Cars(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, db_column='user_id', related_name='cars') title = models.CharField() sold_out = models.CharField(default='N') class Blocks(models.Model): user_id = models.BigIntegerField() target_user_id = models.ForeignKey(User, on_delete=models.CASCADE, db_column='target_user_id', related_name='blocks') I want to extract cars that is satisfied below condition. Cars that from user who is not is_out='N' Cars that doesn't sold out. (sold_out='N') Cars of users that does not exist in the target_user_id column of the blocks table related user_id=10000 To get cars that matched above condition, I wrote the query like this. blocks = Blocks.objects.filter(user_id=10000).values_list('target_user_id', flat=True) Cars.objects.filter(sold_out='N').select_related('user_id').filter(user_id__is_out='N').exclude(user_id__in=blocks) But as you know that, if blocks grows up, maybe there is performance issue occured. Question Is there any way to join blocks? Above query is best case? Any defect on my schema? Thanks. -
What tech stack to choose to download 9000 images in a webpage?
I have a website that will need to download 9000 photos, about 36,9 MB right after loading. I have a progress bar, so it is user friendly but I want this to be as fast as possible. I'm choosing between Python + Django and Java + Spring. I'm also choosing hosting and my choices are Heroku or Netlify. Which one of these are the best for what I want to achieve? The website will be exclusively used in Europe, Portugal. Thank you! -
How to store image in a variable in python?
How to store image in a variable in python.If i get answer with explanation it would be better.I tried searching in stackoverflow and google but didn't get? -
PythonAnywhere cannot get site to redirect without www
Whenever I try to access my pythonanywhere django site without "www." in front it redirects to the pythonanywhere "COMING SOON! This is going to be another great website hosted by PythonAnywhere." landing page. ALLOWED_HOSTS = [u'webapp-******.pythonanywhere.com', u'******.pythonanywhere.com', u'******.co.uk', u'www.******.co.uk'] Anyone encountered and solved this before? -
how do i install django in ubuntu 18.04
I am installing Django using pip command but its showing error the command used: pip install django showing error: ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/pytz' Consider using the --user option or check the permissions. -
Unable to deploy django project on apache with virtualenv and mod_wsgi
I'm trying to run django project with mod_wsgi and apache.I have installed virtual environment and I included bps.conf file in /etc/apache2/sites-available. I couldnot run the project on browser. bps.conf image -
How to fix str object has no attribute '_meta'
I am migrating my model in Django project but error is being generated.Below is the code. What should be corrections in my code to solve this Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #addtional portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(blank=True,upload_to="profile_pics") def __str__(self): return (self.user.username) Forms.py from django import forms from django.contrib.auth.models import User from basic_app.models import UserProfileInfo class UserForm(forms.ModelForm): password = User.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ['username','email', 'password'] class UserProfileInfo(forms.ModelForm): class Meta(): model = UserProfileInfo fields=['portfolio_site','profile_pic'] Admin.py from django.contrib import admin from basic_app.models import UserProfileInfo # Register your models here. admin.site.register('UserProfileInfo') I am getting Attribute Error: 'str' object has no attribute '_meta' -
the way to build forget_password api and save verification code
i try build api get_password this api send verification code to email and api save verification code in session, another way is save verification code on database not sessions, so what is the best way to do this ? -
How to access functions from ModelAdmin in template?
Lets assume a ConactAdmin for showing a ConactModel: class ContactAdmin(admin.ModelAdmin): change_form_template = "admin/contact_change.html" def my_custom_fnc(): return "Test" Now I want to access my_custom_fnc() in an view html my contact_change template like <p>{{my_custom_fnc()}}</p> Is there a list of properties which I can access in my own template? I couldn't find it in the documentation. -
Django: module not found while running in Docker container
I'm running a Django project in a Docker container, and I want to add a module (specifically, django-prometheus) I ran: pip install django-prometheus and docker run -p 9090:9090 prom/prometheus successfully, and I made the necessary alterations to my settings.py and urls.py files, as specified in the README I then rebuilt the project and restarted it, but it is giving me the error ModuleNotFoundError: No module named 'django_prometheus' (full error report: Traceback (most recent call last): api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker api_1 | worker.init_process() api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process api_1 | self.load_wsgi() api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi api_1 | self.wsgi = self.app.wsgi() api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi api_1 | self.callable = self.load() api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load api_1 | return self.load_wsgiapp() api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp api_1 | return util.import_app(self.app_uri) api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app api_1 | __import__(module) api_1 | File "/usr/src/app/project/wsgi.py", line 16, in <module> api_1 | application = get_wsgi_application() api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application api_1 | django.setup(set_prefix=False) api_1 | File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup api_1 | apps.populate(settings.INSTALLED_APPS) api_1 | File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 89, in … -
Django Admin: Show only some objects in ManyToMany field?
I have relatively simple data model with User, Group and Task. Each group has its own tasks and users. Users can be only assigned to one group. Tasks belong to groups and each task has manyToMany field for users, so multiple users can have the same task assigned. In my admin when assigning users to task it shows all created users, I want it to only show users from the same group as the task. What would be the best approach? I have checked available customization options for admin.ModelAdmin but haven't found anything related to my problem. -
Process to wait for DB(handle Operational error)
Problem: I have a django process which talks to DB and gets the result. Before starting the process, I have code to check if db connection is successful or not using connection.ensure_connection(). If it db connection is established, then the process will start or the process will be waiting for db to get connected. Now Let's say I have the process started. The process has total 5 queries listed below: ModelOne.objects.get(pk=1) ModelOne.objects.get(pk=2) ModelOne.objects.get(pk=3) ModelOne.objects.get(pk=4) ModelOne.objects.get(pk=5) First two queries have successfully run and then the DB goes down. Now while executing ModelOne.objects.get(pk=3) process throws an Operational Error: Connection refused. Is there any way where if suddenly DB goes down while a process is running, then pause the process, ensure db connection is established and resume the process? Python -- 2.7, Django -- 1.11 -
If else code not working in layout.html django
I am trying to implement blog app with django.In home page there will be list of post."post.author.profile.image" is a path to load image from database.If "post.author.profile.image" is None i need to load an alternative image and if it exist it should load the image from database.So i tried the following code: def homepage(request): post= Post.objects.all().order_by('-date') return render(request,'layout.html',{'posts':post}) layout.html {% for post in posts %} <div class="list"> <div class="con"> {% if "post.author.profile.image.url" is None %} <img src="{% static 'images/b.png' %}" class='logo3'/> {% else %} <img src="{{ post.author.profile.image.url }}" class='logo3'/> {% endif %} </div> </div> {% endfor %} After running the server if i click on inspect the path in src of image tag is media/None.The code under if is not even running.Whats problem in my code? -
Apache public ip connection
I would like my Django web application in a raspberry pi, to be accessible outdoors by entering the public ip of the raspberry pi with apache2. I did exactly the same thing as on this site: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04 However, I can enter locally, by putting the local RPI ip address in the project setting.py. But when I try to enter with the public ip to access it outdoors it doesn't work. If someone can help me or explain what I didn't understand.... Thank you for your feedback! -
Is Django uncompatible with Microsoft Edge?
I develop a Django application, it works perfectly on Firefox and Chrome but it's ugly on Edge. I tried to add this line but it doesn't work. I don't know the source of the problem. <meta http-equiv="X-UA-Compatible" content="IE=edge"> -
How to pass the environment variable from .env file to supervisord
I have a .env file at /home/home/ubuntu/orlando.env I have a .conf file at /etc/supervisor/conf.d/orlando_celerybeat.conf I want to pass all the environment variables at .env to the orlando_celerybeat.conf. How can I do it I can easily pass the single variable by using (environment=my_environment=TEST) in .conf file but I want to pass through the file ; the name of your supervisord program [program:orlandocelery] environment=my_environment=TEST ; Set full path to celery program if using virtualenv command=/home/ubuntu/envs/bin/celery worker -A orlando --loglevel=INFO ; The directory to your Django project directory=/home/ubuntu/orlando ; If supervisord is run as the root user, switch users to this UNIX user account ; before doing any processing. user=ubuntu ; Supervisor will start as many instances of this program as named by numprocs numprocs=1 ; Put process stdout output in this file stdout_logfile=/var/log/celery/orlando_worker.log ; Put process stderr output in this file stderr_logfile=/var/log/celery/orlando_worker.log ; If true, this program will start automatically when supervisord is started autostart=true ; May be one of false, unexpected, or true. If false, the process will never ; be autorestarted. If unexpected, the process will be restart when the program ; exits with an exit code that is not one of the exit codes associated with this ; process’ … -
How to get current object/instance in save_form (intermediate save page)
I have the following code where I'd like to modify the confirmation page by making it show some in the admin backend the elements which will be modified/affected after confirming it. The problem is that I don't know how to get the current instance. Could you please help me? (I think it's through the request variable). If you know another way of doing so instead of by modifying the save_form I'd appreciate it to know. Thank you. Class MyClass(modelAdmin): def save_form(self, request, form, change): instance = ????? query = MyModel.objects.filter(...) if 'apply' in request.POST: for object in query: somefunction(object) return render(request, 'path/template.html', context='affected_elements', query) -
How to overwrite a model's save method to fill a field upon model instance saving
In the model below, I have added file_name field to store just the filename. I have overwritten the save method to fill this field upon saving, but the field is still empty after uploading the file through admin panel. Even if I put a print statement in the save method, it will not print the file name. Migrations are applied. What am I doing wrong? class DataFile(models.Model): file = models.FileField(upload_to='data files') file_name = models.TextField(default='', blank=True) uploaded_at = models.TimeField(default=datetime.datetime.now()) def __str__(self): return f'{os.path.basename(self.file.path)}, uploaded at: {str(self.uploaded_at)})' def __save__(self, *args, **kwargs): self.file_name = os.path.basename(self.file.name) super(DataFile, self).save(*args, **kwargs) -
Where should custom statup code live in django projects?
While, switching to gunicorn on my current project, I understood that the way I handled model caching on startup was not a good one. Setting app name: website project name: personal_cms There are several models I equipped with a load method. class SomeModel(models.Model): something = models.CharField(max_length=60) something_else = models.URLField() @classmethod def load(cls): cache.set('{}'.format(cls.__name__), cls.objects.all(), None) Typically, signals call these methods every time something change in the model. To load those while starting the server, I just added the following in wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'personal_cms.settings') from website.models import SomeModel, SomeOtherModel SomeModel.load() SomeOtherModel.load() application = get_wsgi_application() The problem The code above works, but only using while using python manage.py runserver, not gunicorn personal_cms.wsgi:application. The reason, from what I understood, is that running manage.py comes with a specific context. Without it, apps aren't loaded when gunicorn hits wsgi.py: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Now that I think about it, it seems wrong to load the app's models from the project's wsgi.py. So, where should I call the load methods so that models are cached on startup no mater the wsgi server chosen? -
How to make URL to load in background in django rest framework
Guys i am using html2canvas to get screenshot of div , for that my page to be load once to generate a image. -
how to get the user from a manytomanyfield in django using djago singals and creating another object with the recived many to many user field
i want to know is there any way where we can get the updated many to many field in one model using signals and post them to another model class Post(models.Model): name=models.CharField(max_length=24) nc=models.ManyToManyField(settings.AUTH_USER_MODEL) def __str__(self): return self.name # return self.name m2m_changed.connect(receiver=like_post,sender=Post.nc.through) i want to collect the updated record in the nc field of post model and using signals i want to create an object using function here is the signal that connects to Post model def like_post(sender, *args, **kwargs): # if kwargs['action'] in ('post_update'): if kwargs['action'] in ('post_add', 'post_remove','post_update'): print(kwargs['instance']) instance = kwargs['instance'] print(instance) notify = Notify.objects.create( recipient=instance, creator=Post.objects.get(pk=50), state='unread', type=kwargs['action'], ) else: print('no instance') in the recipient and the creator section i want to update those fields with an existing user object the creator is the person who updated the manytomanyfield and the recipient is the person who created that post notify model: class Notify(models.Model): recipient = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notify_recipient',on_delete=models.CASCADE) creator = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notify_sender',on_delete=models.CASCADE) state = ('read', 'unread', 'unseen') type = models.CharField(max_length=30, blank=True) url = models.CharField(max_length=50, blank=True) whenever i run this the instance just prints the post object name and fires this error ValueError at /admin/posts/post/50/change/ Cannot assign "<Post: ok>": "Notify.recipient" must be a "User" instance.