Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Should I use clean() to fetch Product of provided Product id in Django Form?
Is it semantically correct in Django to fetch a Product object of provided Product id in the clean() function? forms.py def clean_product(self): product_id = self.cleaned_data['product'] try: product = Product.objects.get(id=int(product_id)) except ValueError: print('error') raise ValidationError('Invalid value') return product views.py def submit_new(request): status = 'fail' if request.method == 'POST': form = NewBForm(request.POST) if form.is_valid(): ... b = form.save(commit=False) b.product = form.cleaned_data['product'] boost.save() status = 'success' return JsonResponse({'status': status}) -
If value is not given in form its not storing null value defaultly?
I created a form in django.I need to set imagefield as optional so i gave required=False.And in my model i gave default = None.My problem is if the user doesn't set profile picture the default value None is not storing in database? forms.py class Register(forms.Form): Email = forms.EmailField(widget=forms.TextInput(attrs= {"class":"inputvalues"})) Username = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"})) Password = forms.CharField(widget=forms.PasswordInput(attrs= ({"class":"inputvalues"}))) Firstname = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"}),max_length=30) Lastname = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"}),max_length=40) Confirm_Password = forms.CharField(widget=forms.PasswordInput(attrs= ({"class":"inputvalues"}))) picture = forms.ImageField(required = False) models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(upload_to='media',default=None) views.py def register(request): if request.method == "POST": form = Register(request.POST,request.FILES) pro=Profile() if form.is_valid(): email = form.cleaned_data['Email'] User_name=form.cleaned_data['Username'] Password=form.cleaned_data['Password'] firstname=form.cleaned_data['Firstname'] lastname=form.cleaned_data['Lastname'] user=User.objects.create_user(username=User_name, password=Password,email=email, first_name=firstname,last_name=lastname) if form.cleaned_data['picture']: pro.image = request.FILES['picture'] pro.user = user pro.save() redirect('/') -
Google multiple accounts: Oauth2: 'NoneType' object has no attribute 'provider'
I've already read this and this, but my problem is different: I have 2 accounts on gmail, and it works when I try with the second one, which is not admin and which has no account information. For the first one, even if I remove the authorization access and google asks me again which account and if I agree with giving my email, I still get the 'NoneType' object has no attribute 'provider'. As a note, I've managed to make it work with facebook and twitter, that's why I'm stuck here, you can try it here, your gmail, facebook or twitter will work, I don't know what could the problem come from: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'bla' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'bla' SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ] SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) -
Switch object create from static data to dynamic data django rest framework viewsets
I have a django rest framework viewset. Within the viewset, I want to create a view that creates a new object based on the data entered in the django rest framework backend page. I currently have it right now that I hard coded just to test and see if i can add. I not want to switch it to dynamic data that is passed into the view. I cant seem to figure it out. I tried just getting rid of the data and **data in the request but that broke it and i couldnt get it to work. viewset create view: @permission_classes((IsAuthenticated)) def create_user(self, request): data = { 'version':1, 'path':'testingpath5', 'namespace':'testingnamespace1', 'value':'testin value 3', 'user_id':1, 'person':request.user } queryset = Preference.objects.create(**data) serializer = PreferenceSerializer(queryset) return Response(serializer.data) I want to be able to create a new object based on the data that is passed in from the django rest framework backend page. -
Nginx, SPA & Sphinx Doco Authentication
I have an SPA app which uses Azure AD for authentication. It's working well and now I've added some user doco using Sphinx. I've configured Nginx so the doco is available via /app/doco. This works well, however now I would like to also secure it so only Azure AD authenticated users can access the doco. To do this I have made use of the auth_request (http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) module. This works if I am using standard Django authentication but when I use Azure AD authentication it isn't working as the request does not have the users token included etc. The way I understand the auth_request module to work is: User attempts to access /app/doco (which includes the users token) Nginx is configured to check if the user is authenticated by going to /app/auth_check (custom Django view) which returns either 200 or 404 If 200, user is given access to /app/doco It feels like that above approach is flawed, trying to hit a square peg through a round hole? Will something like the above work or is there another tool/approach that better fits? -
Django puts spaces in first Line of TextField
I'm creating a webapp where I can present a documentation. In my documentations I often have some code snippets so I used prism (https://prismjs.com/) to format the text I enter in a textfield on the admin page. The Problem is that whenever I enter code in the textfield it makes spaces on the first line like that: import { Pipe, PipeTransform } from '@angular/core'; import { UserService } from '../user.service'; My code looks likt this: Template: <pre><code class="language-{{ subdoc.language }}"> {{ subdoc.code }} </code></pre> -
How to combine more than one querysets in django
Here i am trying to combine query-sets from different models and i tried like this.But this code is giving me error: How can i solve this ?? Exception Type:TypeError Exception Value: unhashable type: 'list' def search_all(request): q = request.GET.get('q') if q: courses = Course.objects.filter(title__icontains=q) students = Student.objects.filter(name__icontains=q) teachers = Teacher.objects.filter(name__icontains=q) users = User.objects.filter(username__icontains=q) all_results = list(chain(courses,students,teachers,users)) # all_results = courses | students | teachers | users return render(request,'all_search_results.html',{all_results:all_results,'q':q}) else: return redirect('home') -
How to get QuerySet values separately?
How I can to get values from QuerySet separately? The result of my QuerySet now is „, ]>“ How I can get 5, 90 to separate variable ? -
SwingTime in Djnago
I have a table in my ORM from which I want to calculate the total weight and display it on a calendar and for the same I want to use SwingTime but I was not able to use it. Models.py class Quiz(models.Model): total_trucks = models.IntegerField(default=0) offered_price = models.IntegerField(default=0) weight = models.IntegerField(default=0) posted_on = models.DateTimeField(auto_now_add=True) Now I can get the total weight like this: total_weight = Quiz.objects.aggregate(Sum('weight')) But how Do I use it with SwingTime? I find another useful Link but was not able to understand it completely to use but it also solves the problem. Any help is appreciated. -
How to store a dataframe object between API calls?
My Django app will allow the users to upload an Excel file and will then analyze and visualize data in this file. To handle the Excel files, I have introduced a model with FileField: class DataFile(models.Model) file = models.FileField(upload_to='data_files') Next, I want to create some API views for this app that would take the file uploaded by user, manipulate it with Pandas dataframe object and return the manipulated data. For example: def some_api_view(request): data_file = DataFile.objects.last() dataframe = pandas.read_excel(data_file.file.path) maniupulated_dataframe = # ... dataframe manipulation goes on here ... # return JsonResponse({'manipulated_dataframe': manipulated_dataframe'}) My concern is that each API view like this will need to read the Excel file on its own. Is it possible to design the API in a way that would allow reading the file into a dataframe only once (since it will always be the same file), and then the API views would only be responsible for retrieving this dataframe, manipulating it and returning manipulated data? I am using an SQL database, so I cannot store the dataframe object itself in the database. Also, I would rather avoid pickling it. -
How to authenticate user from standalone react frontend with django backend (same domain, different ports), using a third-party CAS authentication?
I'm setting up a django backend with Django REST framework for providing APIs, with authentication implemented through a third-party CAS server. Currently my backend authentication has been successfully implemented (using django-cas-ng package), which means I can implement different permissions for different groups of user. The django backend serves through localhost:8000 by default. Adding a standalone react frontend (localhost:3000 by default) seems complicating the authentication system. Requests (implemented by axios) sending from 3000 port to 8000 port are unable to authenticate. I've tried npm run build to build the static files and integrate them with django. Within the same 8000 port all the authentication and permissions work fine. Could anyone suggest how to implement authentication through different ports? -
How to display the values from a many to many filed after using .vlaues() in queryset?
I wrote a views function for my django applications which is: def index(request): influencers = Influencer.objects.all().order_by('followers').values() print(influencers) paginator = Paginator(influencers,16) page = request.GET.get('page') paged_listings = paginator.get_page(page) user_list = UserList.objects.all().filter(user_id = request.user.id).values() queryset = list(chain(paged_listings,user_list)) content = {'total_page_count': paginator.num_pages, 'influencer_count':paginator.count, 'data': queryset} return JsonResponse(content) It returns a JSON object. The problem is when I use .values() on the first line of the function it doesn't display the values from Many to Many field in the Respose. I tried writing an alternative function, which displays the values from the many to many field but shows error when the pagination influrnation is passed i.e. total_page_count and influencer_count. The alternative function is given below: def index(request): influencers = Influencer.objects.all().order_by('followers') paginator = Paginator(influencers,16) page = request.GET.get('page') paged_listings = paginator.get_page(page) user_list = UserList.objects.all().filter(user_id = request.user.id) paginate = {"total_pages":paginator.num_pages} queryset = list(chain(paged_listings,user_list)) ser_query = serializers.serialize('json', queryset,indent=3,use_natural_foreign_keys=True) return HttpResponse(ser_query,content_type='application/json') When I include paginate in queryset it gives the error 'str' object has no attribute '_meta' The model class for the views function is: class Influencer(models.Model): full_name = models.CharField('Full Name',max_length=255) username = models.CharField('Username',max_length=255,unique=True) photo = models.URLField(blank=True,max_length = 500) categories = models.ManyToManyField(Category,blank=True,max_length=400) hashtags = models.TextField('Hashtags',blank=True) I want both the pagination and ManyToMany Field information in my JSON response. How should … -
save username and password in django login form
I am using the django User model to create a login form for my custom admin page. I want the username and password to be saved when I logout. I know saving username and password in login form is not a good idea but I am doing it as a test project so I don't want to keep entering the username and password everytime I log in. forms.py class LoginForm(forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput) remember_me = forms.BooleanField(required=False) views.py def login(request): if request.method == 'POST': form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] remember_me = request.POST.get('remember_me') user = authenticate(request, username=username, password=password) if user : login(request, user) if not remember_me: request.session.set_expiry(0) redirect_url = request.GET.get('next', 'dashboard') messages.success(request, 'logged in.') return redirect(redirect_url) else: messages.error(request, 'Invalid username or password') else: form = LoginForm() return render(request, 'login.html', {'form': form}) template <form action="" method="post"> {% csrf_token %} <input type="text" name='username'> <input type="password" name='password' required> <button type="submit">Log in</button> <input type="checkbox" name="remember_me" id="basic_checkbox_1" > <label for="basic_checkbox_1">Remember me</label> </div> </form> -
DRF - SerializerMethodField
I've an API view as below:- class ProfileAPI(generics.RetrieveAPIView): serializer_class = ProfileSerializer def get_object(self): try: return Profile.objects.get(user=self.request.user) except: return None # I don't raise NotFound here for a reason. # I don't want a 404 response here, but a custom HTML response, explained below. class ShopAndProfileDetailsSerializer(ProfileSerializer): html = serializers.SerializerMethodField() def get_html(self, obj): # some custom HTML response based on whether the user obj is `None` or not. if not obj: return NOT_LOGGED_IN_HTML return CUSTOM_HTML class Meta(object): model = Profile fields = ('html',) Now when the user is logged-in, I get the html key in the response. However, when the user is None (logged-out), I get an empty response. Why? and how can I rectify it?