Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add ManyToMany field on save
I have a model with a ManyToMany field, and everytime I create an object I need to search the database for more objects with the same phone or email created previously. Right now, I am using a post_save signal to do this, but I wanted to know if there is a better way to do this, maybe on the creation serializer. class Leads(models.Model): name = models.CharField(max_lenght=40) phone = models.CharField(max_lenght=14) email = models.EmailField() other_leads = models.ManyToManyField('Leads') created = models.DateTimeField(auto_now_add) @receiver(post_save, sender=Leads) def add_related(sender, instance, created, **kwargs) if created: [instance.other_leads.add(lead) for lead in Leads.objects.filter(email=instance.email, created__lt=instance.created)] -
how to access session variable inside form class
Hi i have a session variable city, how to access it inside form class. Something like this class LonginForm(forms.Form): current_city=request.city -
How to set automatically 'many' flag of django serializer depending on input being a list or a single item
I have the following machine model. class Machine(models.Model): operators = models.ManyToManyField(User, related_name='machines', blank=True) elasticsearch_id = models.PositiveIntegerField(default=None, null=True, blank=True) company = models.ForeignKey(Company, default=None, null=True, blank=True,on_delete=models.SET_DEFAULT) machine_brand = models.CharField(max_length=200, null=False) machine_model = models.CharField(max_length=200, default='') machine_picture = models.URLField(max_length=200, null=True) tools = models.ManyToManyField('Tool', default=None, blank=True) clustered_tags = JSONField(null=True) elasticsearch_tags = JSONField(null=True, blank=True, default=DEFAULT_TAG_MAP) machine_slug = models.SlugField() With the following serializer. class MachineSerializer(serializers.ModelSerializer): class Meta: model = Machine fields = '__all__' In my views, I am filtering the data on the company the logged in users belongs to. Now, I want to serialize the object and return it to the client. However, I don't know beforehand whether the queryset is a list of objects or a single object so that I can set the many flag of the serializer to true or false. @api_view(['GET','POST']) def manage_operators(request): user_machines = Machine.objects.filter(company=request.user.company) user_machines_ser = MachineSerializer(user_machines, many=True) return Response({'machines': user_machines_ser.data}) Is there any elegant way to solve this? I could solve it this way but there must be a better way of doing it. if len(user_machines) > 0 : user_machine_ser = MachineSerializer(user_machines, many=True) else: user_machine_ser = MachineSerializer(user_machines, many=False) Any input much appreciated! -
Getting an 'x' in the url derived from django regex
I am trying to generate an URL using regex and have got it to an extent. But, the problem is there is an 'x' in the URL which I don't want there, without it the ur. is perfect. I have tried few changes on the regex but removing or adding anything throws an error. view.py def clothes_details(request,slug): item = data.objects.get(slug=slug) print(item) return render(request,clothes_details.html,{'item':item}) url.py url(r'^(?P<designerlink>)[\w-]+/(?P<slug>[\w-]+)/$',views.clothes_details,name='clothes_details'), item.html <div class='items'> {% for item in all_clothes %} <div class='item'> <a href="{% url 'clothes_details' designerlink=item.designerlink slug=item.slug %}"> <img src="{{item.itemimage.url}}" style="width:350px;height:450px;"> </a> <p>{{item.itemcode}}</p> <p>{{item.itemprice}}</p> <p>{{item.itemname}}</p> </div> The result is getting 'http://127.0.0.1:8000/designernamex/dressname/' but I need to get 'http://127.0.0.1:8000/designername/dressname/' -
How to defind a url name for each create and list in viewset rest django
I'm coding a logging middleware, in code i want to know where the function request will be dispatched. But i use router and viewset then list and create function will return the same value of request.resolver_match.view_name . How to know that request call list or create function in middleware -
How can i remove the default “delete selected” admin action in Django
How can i remove the default “delete selected” admin action in Django admin panel? And for example, here is a student math score, how can i use custom action to add his math score? Where should i input the score? I need you help -
Finding the source of Django login page message
I am new to Django. Let me come straight to the topic. I have created a working Django application. I am using django-allauth for implementing social-account authentication. Now, suppose I am logged-in inside my application using an e-mail id whose user does not have a staff access and, if I open admin login page directly, the admin login page is displayed as follows: admin login page My question is how can I stop Django from displaying the message "Successfully signed in as ... ". Where is the source of this message present? -
Django File upload with ajax
Here, I work on project django (V2.1 + python 3.6) upload text files. I have a template for the files I want to upload except that when the form is sent the file is missing; I do not know what's wrong. That's my models: from django.db import models class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) That's my template: <form enctype="multipart/form-data" method="post" action="{% url 'add_document' %}" class="js-add-document-form"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Add document</h4> </div> <div class="modal-body"> {% include 'books/includes/partial_doc_form.html' %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">ADD</button> </div> </form> That's my view: def save_doc_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True docs = Document.objects.all() data['html_doc_list'] = render_to_string('docs/includes/partial_docs_list.html', { 'docs': docs }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def doc_create(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) else: form = DocumentForm() return save_book_form(request, form, 'docss/includes/partial_docs_create.html') That's my js file: $(function () { /* Functions */ var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function … -
Optimalizing Django's QuerySetSequences
In one of my views I have problem, that going into this url makes CPU usage 100% for like 5-10 mins. It means that for the next 5-10 mins my webpage is useless. My bet is that's because of how many database queries I am trying to send. Views.py that gives me trouble: def guild_details(request, guild_name): fixed_guild_name = urllib.parse.unquote(guild_name) players = Player.objects.filter(guild=fixed_guild_name) last_month = datetime.today() - timedelta(days=30) deaths = reduce(QuerySetSequence, [Deaths.objects.filter(killed=player, date__gte=last_month) for player in players]) kills = reduce(QuerySetSequence, [Deaths.objects.filter(killer=player, date__gte=last_month) for player in players]) return render(request, 'guild.html', {'players': players, 'deaths': deaths.order_by('-date'), 'kills': kills.order_by('-date'), 'guild_name': guild_name}) It seems not that bad, but consider that: Database includes over 6000+ "Players". (and rising) Database includes over 26000+ "Deaths". (and rising) At first, I was thinking about doing cache for this webpage, but it's deaths / kills might change every 30 mins or so, so I don't think that will help much - considering that I have trouble accessing this page for the first time if players count is high (10+). If player count is small, I have no trouble accessing this page. Also, I'm running redis / celery with scrapping on same server. Is there something I could optimalize to make it … -
Firebase HttpAccessTokenRefreshError - invalid_user: Robot is disabled [Django web server]
I've built simply app, which uses other web to calculate some values. In my request, i push some data (mainly strings) and then i received executed .json file. I want to send received data to database in firebase (at the beginning it can be in strings format). When you try to send that data, you get info about error: Exception Type: HttpAccessTokenRefreshError Exception Value: invalid_user: Robot is disabled. Before using method, I've initialize firebase authentication via password/mail and I've added content of .json file with key (to config) firebase = pyrebase.initialize_app(config) auth_firebase = firebase.auth() database_firebase = firebase.database() And then I put right data: email = "email@example.com" password = "password" user = auth_firebase.sign_in_with_email_and_password(email, password) user = auth_firebase.refresh(user['refreshToken']) After that, I've tried initialize database and put some data there. 'Data' var contains all values which i want to push. database_firebase.child("devices").child("Samsung") database_firebase.child("devices").push(data) Any suggestion? What could be the reason that error??? -
Django "ValueError: source code string cannot contain null bytes"
I am facing this "ValueError: source code string cannot contain null bytes" error when ever i create a splite3 database and use it. Below are the steps i follow. Create the database using db browser. Run python "manage.py inspectdb > customer.py" I run the server with "python manage.py runserver" I get this error when I run the server. Could someone please help me in this. Thanks, gregory -
Is it necessary to create REST API in a Django application to update db without reloading the page?
I have a HTML page with input fields in a form. After tabbing out of the last input field, javascript is used to populate a table on the same page. I want to use the data stored in the input fields to be saved in the database connected to my Django app. Later, when an edit is made in the table cell, the change should also be reflected in the database without having to reload the page. From what I have read, I need to use Ajax and REST APIs. tldr; is there a way to update a database connected to Django app (offline only) without reloading the page other than using REST APIs? -
'CreateForm' object has no attribute 'user' on form validation
I'm trying to create a view in order to add data to my database through a FormView. However I'm getting this no attribute 'user' error. I found how to get rid of it with a function-based view here : MyModelForm' object has no attribute 'user using django , however I still don't get how to do the same with my class-based view. Here are my files : views.py : class CreateView(FormView): template_name = 'restaurant/create.html' form_class = CreateForm success_url = '' @method_decorator(login_required) def form_valid(self, form): obj = form.save(commit=False) obj.owner = self.request.user obj.save() return super().form_valid(form) forms.py : class CreateForm(forms.Form): name = forms.CharField() category = forms.CharField() capacity = forms.IntegerField() description = forms.CharField(widget=forms.Textarea) models.py : from django.contrib.auth.models import User class Restaurant(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) category = models.CharField(max_length=200) description = models.TextField() capacity = models.IntegerField(default=0) Thanks in advance ! -
NotImplementedError: Django doesn't provide a DB representation for AnonymousUser
I get the following error: Traceback: File "C:\Users\HP\GST\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\HP\GST\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\HP\GST\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\HP\Desktop\erpcloud\accounts\views.py" in change_password 31. if form.is_valid(): File "C:\Users\HP\GST\lib\site-packages\django\forms\forms.py" in is_valid 179. return self.is_bound and not self.errors File "C:\Users\HP\GST\lib\site-packages\django\forms\forms.py" in errors 174. self.full_clean() File "C:\Users\HP\GST\lib\site-packages\django\forms\forms.py" in full_clean 376. self._clean_fields() File "C:\Users\HP\GST\lib\site-packages\django\forms\forms.py" in _clean_fields 397. value = getattr(self, 'clean_%s' % name)() File "C:\Users\HP\GST\lib\site-packages\django\contrib\auth\forms.py" in clean_old_password 366. if not self.user.check_password(old_password): File "C:\Users\HP\GST\lib\site-packages\django\contrib\auth\models.py" in check_password 396. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") Exception Type: NotImplementedError at /accounts/change-password/ Exception Value: Django doesn't provide a DB representation for AnonymousUser. My view looks like this: def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, user) return redirect(reverse('company:Dashboard')) else: return redirect(reverse('accounts:change_password')) else: form = PasswordChangeForm(user=request.user) args = {'form': form} return render(request, 'accounts/change_password.html', args) Firstly, I thought that this was due to the fact that I didn't have Django updated, but now I have, and I receive the same error. I've looked at some solutions that other users asked, but none applied in my case Any help, please ? -
sending the list of posts without description in django rest framework
I'm creating a blog with django rest framework for the backend . I have a Posts model that has a 'description' TextField. I want to use this model for both 'showing a list of all posts' and 'showing a single post'.I don't want the description fields to be sent for the blog page and send it just for the single posts pages. this is my code : Post Model: class Posts(models.Model): title = models.CharField(max_length=255) subtitle = models.CharField(max_length = 255) description = models.TextField(default = "") Post ViewSet: class PostsViewSet(viewsets.ModelViewSet): serializer_class = serializers.PostsSerializer queryset = models.Posts.objects.all() Post Serializer: class PostsSerializer(serializers.ModelSerializer): class Meta: model = models.Posts fields = '__all__' Note: when I go to http://example.com/Posts , I like to see all posts without the Description. but for http://example.com/Posts/1, I want the description as well as other Fields. -
Django cms fails creating project
I followed the tutorial presented in http://docs.django-cms.org/en/latest/introduction/install.html and it goes well until I want to create a project using pip install djangocms-installer then it is followed by these errors: (venv) C:\Users\Akbar\Desktop\djangocmsTest\tutorial-project>djangocms mysite Creating the project Please wait while I install dependencies If I am stuck for a long time, please check for connectivity / PyPi issues Dependencies installed Creating the project The installation has failed. ***************************************************************** Check documentation at https://djangocms-installer.readthedocs.io ***************************************************************** Traceback (most recent call last): File "c:\python\python37\Lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\python\python37\Lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Akbar\Desktop\djangocmsTest\venv\Scripts\djangocms.exe\__main__.py", line 9, in <module> File "c:\users\akbar\desktop\djangocmstest\venv\lib\site-packages\djangocms_installer\main.py", line 44, in execute django.setup_database(config_data) File "c:\users\akbar\desktop\djangocmstest\venv\lib\site-packages\djangocms_installer\django\__init__.py", line 407, in setup_database command, env=env, stderr=subprocess.STDOUT File "c:\python\python37\Lib\subprocess.py", line 376, in check_output **kwargs).stdout File "c:\python\python37\Lib\subprocess.py", line 468, in run output=stdout, stderr=stderr) subprocess.CalledProcessError: Command '['c:\\users\\akbar\\desktop\\djangocmstest\\venv\\scripts\\python.exe', '-W', 'ignore', 'manage.py', 'migrate']' returned non-zero exit status 1. And as you see there is no questions to respond. -
Initial value for dropdown menu
I'd like to set an initial value on my dropdown form of "Select an Industry". Once the user selects a valid value from the dropdown AND saves the form, ideally, this option wouldn't be visible anymore within the list if the user were to go back to the form. If there is no way to do this, that's fine. Models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(blank=True, null=True, max_length=100) industry = models.IntegerField(default=0) Forms.py class EditUserProfileForm (forms.ModelForm): industry = forms.ChoiceField() def __init__(self, *args, **kwargs): super(EditUserProfileForm, self).__init__(*args, **kwargs) self.fields['industry'].choices = [(t.industry, t.industryname) for t in Industry.objects.all()] class Meta: model = UserProfile fields = ( 'phone', 'industry', ) Is it possible to set a default value without creating an instance of the Industry object whose industryname is "Select and Industry"? Thanks! -
celery periodic task data available for the celery workers
I am getting data by periodic task using celery beat. this I have to share remaining workers. I am new to celery, how can I achieve? please give me a brief. thank you in advance. -
Django Rest Framework - Pagination data URL's showing http instead of https
I am hitting on https://xyz.abcd.com/api/users&page=3 from browser. But data I am getting consists of http URL's. { "count": 410, "next": "http://xyz.abcd.com/api/users&page=4", "previous": "http://xyz.abcd.com/api/users&page=2", "results": [<data goes here>] } I have set USE_X_FORWARDED_HOST = True in settings.py. However it didn't work. -
Django 2.1 - 'functools.partial' object has no attribute '__name__'
I recently upgraded Django from 2.0.7 to 2.1.1, a new error occurs in which I get this error 'functools.partial' object has no attribute '__name__'. I'd like to understand if my fix is right and what caused this new error to happen, I couldn't find anything on the django release notes related to this issue, maybe I missed it. decorators.py def auth0_login_required(function): def wrap(request, *args, **kwargs): if request.isAuthenticated or request.user.is_staff: pass else: raise Http404() return function(request, *args, **kwargs) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ # ERROR HERE return wrap How it is used, views.py: @method_decorator(auth0_login_required, name='dispatch') class Dashboard(View): ... For the fix I just removed wrap.__name__ = function.__name__, but I'm not sure if it'll break something else. Can someone explain? -
Form resubmits data django
I have a view function that resubmits data when I refresh the page. def home(request): if request.method == 'POST': form = ListForm(request.POST or None) if form.is_valid(): form.save() all_items = List.objects.all messages.success(request,('Item has been added to List')) return render(request, 'home.html', {'all_items': all_items}) else: all_items = List.objects.all return render(request, 'home.html',{'all_items':all_items}) Any ideas on how to prevent this please. render_to_response is now deprecated from what Ive read. Thank you -
Django using temporary files
I want to create a view in Django for uploading a file and deleting after use. I have the upload related functionality ready. Users can upload the files. Now I want the uploaded file to be deleted after use. How can I achieve that. Regards, Jaiswal -
Javascript set timeout to bootstrap alert
My alerts are dynamically created. Is it possible to assign a function to the alert to self destroy in 3 seconds? {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> <a class="close" data-dismiss="alert">×</a> {{ message }} </div> {% endfor %} {% endif %} I am using Django as a backend. The end product looks like this <div class="alert alert-success"> <a class="close" data-dismiss="alert">×</a> My message </div> Summary Is it possible to make a timeout function like setTimeout(function(this){ $(this).remove() }, 3000); into the tags? -
How to show images in Django Template with out static?
I have an API which gives me a list of movies, and there images are in http links like https://d2gx0xinochgze.cloudfront.net/5/public/public/system/posters/12/thumb/Tevar-Movie-Opening-Day-Box-Office-Collection-Report-1140x752_1482917123.jpg So in django we use static file {% static 'image.jpg' %} to display images in templates, But how to display api images links in template? -
Saving category_id for new post in django
I have a problem when saving/creating new post for blog. I already have Post model and each post has it's own category. so I have Category model too. In CreateView template I already got all categories from DB and displayed in select/option tag. The issue is I want to save category_id when I create new post. But I don't know how? How can I say if form POSTED get category_id and save it for Post model that has category_id field? View: class PostCreateForm(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'short_text', 'long_text', 'post_pic'] def get_context_data(self, **kwargs): context = super(PostCreateForm, self).get_context_data(**kwargs) context['categories'] = Category.objects.all().order_by('id') return context def form_valid(self, form, **kwargs): form.instance.author = self.request.user return super().form_valid(form) Model: class Category(models.Model): title = models.CharField(max_length=255) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=255) short_text = models.TextField() long_text = models.TextField() post_pic = models.ImageField(default="post_pic.jpg", blank=False, upload_to='post_pics') date_published = models.DateTimeField(default=timezone.now()) date_upadated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, default=None, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk})` post_form.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block title_head %} New Post {% endblock title_head %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 pb-2">New …