Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service C:\Path\chromedriver.exe
All of a sudden I've started getting this error message, I've been using Selenium and Chromedriver for a while on this project with no issues and as far as I'm aware I've not changed anything to cause this error. I've read a few posts with this question but haven't been able to solve it. I've got two projects with the exact same Selenium code, one where I've just got the Selenium part and another that is a full Django project, using Celery to run the Selenium task. Chromedriver is working fine still in the selenium-only project (that has exactly the same code and setup as the Django project) Chromedriver has been working fine in my Django-Celery project for the past week (when I moved my selenium-only code over to run in celery tasks). I've not changed anything of note in my Django-Celery project to make it stop working I've checked and 127.0.0.1 is added to etc/hosts file (it was there already) I've got no idea what the problem is, this came up a few days ago but then only happened once and went away after I retried, now I can't start Selenium at all. -
Django - Form - ForeignKey - Hidden - Default value
I have a Hidden ForeignKey in an update form that I want to set to value of default value of 2 in my html form, but I can't get it to work. forms.py eval_sent_state = forms.ModelChoiceField(widget=forms.HiddenInput(), initial=2,queryset=models.EvalUrlSentState.objects.all()) Th Html output i get: <input type="hidden" name="eval_sent_state" value="1" id="id_eval_sent_state"> -
how to use django Serializer to update field in database
I create report Model that have a field report state i need a serializer that when user create report the state of report automatically change to pending or something else and when edit report body and save it then automatically set state to Edited or ... -
How to group a model data based on another model and paginate in django?
I have two models: Category - Zero or multiple books can be in one category Book - A book can have zero or one category if I do Book.objects.all() I'll get something like [book11, book10, book9, ...] normally but I don't want that. What I want is something like: [ [book11, book2, book1], [book10], [book8, book6], [book7], [book4, book3], ... ] Where Books are grouped according to their category. The books that don't have a category will also include in the list as a single element group Ordering would be according to book's creation in reverse For better understanding here is my model structure: class Category(models.Model): name = models.CharField(max_length=50) class Book(models.Model): name = models.CharField(max_length=128) category = models.ForeignKey(Category, on_delete=models.CASCADE,related_name='books', null=True, blank=True) -
Query Multiple Tables in Django and geta consolidated result
I am building a Blog application in Django and currently stuck at Querying the Data. I am creating a Post and then uploading multiple images to that post. This is my Blog Post Model. class Post(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) title = models.CharField(max_length=255) description = models.CharField(max_length=1000,null=True) Tags = models.CharField(max_length = 255,null=True,blank=True) Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) And this is my Images Model class Images(models.Model): Post = models.ForeignKey(Post,on_delete=models.CASCADE) image = models.ImageField(upload_to='media/') Now using this implementation I have 2 tables in DB in which data is stored as expected. In the first tables all the details related to Post are being stored and in the second Table ID, Post_Id, Image_URL is being stored. If I upload 3 images then three rows are being created. Now I want to Query the data that is -> I want all the posts and I want all the Images according to the Posts. I can get seprate queries for Post and Images but how can this be done in Django ORM? How can I query The data? -
Django dev server no longer reloads on save
I'm developing a simple Django app and things were going great until suddenly the dev server stopped reloading automatically on file change. Now I have to manually restart the server every time I change some Python file, which is pretty annoying. I've tried removing my virtual environment and reinstalling Django to no avail so I guess the problem is with the project itself. In settings.py I have DEBUG = True and also when I start the server it says Watching for file changes with StatReloader, which I assume means that it should reload. Can't think of what else it could be. I don't think I even touched any settings files, just views, urls and models. -
Django: continuing block after exception
How to continue the execution of a block after an exception. I have two vmware servers running I have created two functions, one that refreshes the information coming from the server and the other that populates the database. Except that when one of the servers does not respond an error occurs and the refresh is not done. def vm_refresh(request): vmware_list = Vmware.objects.all() for i in vmware_list: vmwarepopulatevm(i) i.save() # ... def vcsapopulatevm(vmware): # ... req1 = vmrequestsget() if 'value' in req1.json().keys(): for i in my req1.json()['value']: VirtualMachine.objects.update_or_create(vm=i['vm'] vmware=vmware, defaults=i ) # ... I tried somethink like this and it's works try: vmwarepopulatevm(i) i.save() except Exception: pass But I want to create a generic function because I will have to use it more often -
AJAX call to Django View returns None to data
I have been trying to get data that I send using AJAX with a Django view. I have this AJAX call $.ajax({ method: "POST", url: "{% url 'change_publish_status' %}", value: {"company_id": company_id, "published": published}, dataType: 'json', headers: {"X-CSRFToken": '{{ csrf_token }}'} }); and I'd like to access the company_id and the published variables from the django view. I have tried many things self.request.POST.get('company_id') --> returns None self.request.POST.get('company_id', None) --> returns None self.request.body --> returns b'' This is my view right now @method_decorator(login_required, name='dispatch') class ChangePublishStatus(TemplateView): def post(self, *args, **kwargs): company_id = self.request.POST.get('company_id', None) published_status = self.request.POST.get('published') == "true" print(company_id) return JsonResponse({"status": "ok"}) def get(self, *args, **kwargs): return redirect("list") -
How instances of Django's generic view classes created?
I am trying to understand how Django works and here is one question. Say we have this simple CreateView: class ListCreate(CreateView): model = ToDoList fields = ['title'] def get_context_data(self, **kwargs): context = super(ListCreate, self).get_context_data() context['title'] = 'Add a new list' return context Now, as far as I know, you create an instance of a class by my_instance = MyClass(). Untill then the code that describes the MyClass is just a code. So my question is, at what point in time the instance of ListCreate() is created and what is the name of that instance? -
populate a field with the result of subtracting two other fields
i have the following model class FeeModel(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,null=True) total_fee=models.IntegerField(default=100000) paid_fee=models.IntegerField() remaining_fee=models.IntegerField(default=0) i need the remaining_fee to be filled by the result of (total_fee - paid_fee). How would i do that? -
How to know wich page redirected to the login url with the @login_required decorator in django?
I have two page that need to be logued to be accessed, both of them redirect to the login url with the @login_required decorator @login_required def ask_question(request) @login_required def answer_question(request) and i would like to display a message on the login page that will be specific depending from the page that redirect to the login. Like : You need to be loggued to ask question (if the user came from the ask question redirection) You need to be loggued to answer question (if the user came from the answer redirection) Regards -
Dynamic reverse URL name supplied from model Django
I'm trying to reverse(just the way reverse_lazy works) the url_name stored in the SubMenu.link Here is my code My Model class SubMenu(models.Model): menu = models.ForeignKey(MainMenu, on_delete=models.CASCADE, related_name="submenus") title = models.CharField(max_length=50) link = models.CharField(max_length=50, null=True, default="null") def __str__(self): return self.title My root urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('bodys.urls')), path('blog', include('blogs.urls')), path('contact', include('contacts.urls')), path('services/', include('services.urls')), ] -
Djanga admin custom list_diplay
In the Django admin panel, how do I change admin.py so that each staff can see only their data in the list_display. For example, there is a news site. 2 staffs will add news to the site. A separate account is opened for each staff. Only the news added by that staff should appear in the list of added news. This is how it is done in list_display? Please help. -
How to test registration form in django?
I have a test to check if registration form works correctly but user doesn't create. I don't understand why. For example if in test I use assertEqual(Profile.objects.last().user, 'test1'), it is said that it's Nonetype object. If I check response's status code, it is 200. So I can be sure that page works. And finally If I go to this register page and create a user with the same information by myself it will be created successfully. What is the problem and how can I solve it? Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=36, blank=True) phone = models.IntegerField(blank=True) verification = models.BooleanField(default=False) quantity_posts = models.IntegerField(default=0) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('information', args=[str(self.pk)]) Form: class RegisterForm(UserCreationForm): city = forms.CharField(max_length=36, required=False, help_text='Город') phone = forms.IntegerField(required=False, help_text='Сотовый номер') class Meta: model = User fields = ('username', 'city', 'phone', 'password1', 'password2') View: def register_view(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() city = form.cleaned_data.get('city') phone = form.cleaned_data.get('phone') Profile.objects.create( user=user, city=city, phone=phone, ) username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('/') else: form = RegisterForm() return render(request, 'users/register.html', {'form': form}) part of main urls: path('users/', include('app_users.urls')) part of app urls: path('register/', … -
How to post file and parameter with Ptyhon requests?
I am creating a project with Django. I want to post a file and a parameter (sector) with python-requests. I created a function for that but I cannot add a parameter. Here is my code: def mytestview(request): form = PDFTestForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): pdf = form.save() sector = "default" file_address = ("C:/user/otc/"+pdf.pdf.name) url = 'https://api.myaddress.com/pdf' files = {'upload_file': open(file_address, 'rb')} values = {'upload_file': file_address} r = requests.put(url, files=files, data=values, headers={'Authorization': 'Bearer my_token'}) print(r) # <Response [415]> else: messages.error(request, 'Please, upload a valid file.') context = { 'form': form } return render(request, 'testthat.html', context) Note: { "sectorInfo": { "code": "string", "name": "string" }, "bill": { "id": 0, "name": "string", "size": 0 }, } -
Want to pass json array as django variable inside javascript
I have a json array and I want to pass this inside a javascript variable, inside the django template. I am able to access the variable inside django template {{variable}} . But not able to access this inside the javascript.This is my variable: [ {'Book ID': '1', 'Book Name': 'Challenging Times', 'Category': 'Business', 'Price': '125.60' }, {'Book ID': '2', 'Book Name': 'Learning JavaScript', 'Category': 'Programming', 'Price': '56.00' } ] I have used {{variable|safe}} inside the js but not working. Plz let me know where I am making the mistake. -
Django REST FRAMEWORK + django admin data save
I am not able to save my rest API data to my another Django Project. How I can populate another rest API data to my Django admin database ? -
Sorting by favorite category in Django
Good day all. I have a django problem.. I have a dashboard page where one of the field is the total number of items in a person's favorite category.. So in my model there will be a slot where user can pick their favorite category Like for example.. If I register. I can pick django as my favorite backend language.. Now I want to make sure that I get the total number of content in that django category on my dashboard.. If another user picks java.. It should bring out the total number of content in java. If another picks php it should bring out total number of content in php I was to know if it's possible to do Objects.filter(favorite_category) -
Python Django filter avoid overlapping between range dates
I'm having a bit of a logic blank this morning. I get 2 datetime objects from a user (a range), start_time and end_time. Idea is to return an exists if there's an overlap between the input range and an existing schedule time. I tried the following, but I'm far off with the logic. if Schedule.objects.filter(start_date__gte=ts_start, end_date__lte=ts_start).filter(start_date__gte=ts_end, end_date__lte=ts_end ).exists(): Any suggestions would be much appreciated. Thanks! -
django - Multiple uploads to later edit as multiple posts
I'm new to django and I'm doing a music project. I want to select multiple mp3 and upload it and then the form appears to me to edit the parameters for each mp3 separately (example, artist, title, image, etc). upload multiple files in one input, to edit later for separate post. Project https://github.com/Jimmy809/Multimedia/tree/Rama-1 Thx -
Is it possible to get all authors by single query in django
class Author(models.Model): name = models.CharField(max_length=50) class Chapter(models.Model): book = models.ForeignKey(Album, on_delete=models.CASCADE) author = models.ManyToManyField("Author") class Book(models.Model): author = models.ManyToManyField("Author") I am trying to show all related authors when I visit one author detail. To do that currently I do this to achieve this: authors = [] for chapter in Author.objects.get(id=id).chapter_set.all(): authors.append(chapter.artists.all()) Is there any other way to do this by djangoORM -
Django having problem in adding user to specific group
forms.py class UserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username','email','password1','password2') def save(self,commit=True): user = super(UserForm,self).save(commit=False) user.set_password = self.cleaned_data['password1'] user.email = self.cleaned_data['email'] if commit: user.save() views.py def register_view(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): user = form.save() customer_group = Group.objects.filter(name='CUSTOMER').exists() if customer_group: Group.objects.get(name='CUSTOMER').user_set.add(user) else: Group.objects.create(name='CUSTOMER') Group.objects.get(name='CUSTOMER').user_set.add(user) messages.success(request,'註冊成功! 請按指示登入!') return redirect('login') else: messages.error(request,'註冊無效! 請再試過!') context = {'form':form} return render(request,'customer/register.html',context) When I try to register a new user, the form can be successfully saved and the group CUSTOMER can be added but I have a problem if I want to add that user to the group so are there any methods in order to add the user to the group automatically after that user had registered a new account along with the User model? -
How to add multiple rows to a table in one submission in Django
I am adding an object through the submit button by making a template without using Forms.py. Here I want to add multiple rows in one submission. Because there are times when all but one field have the same value. So, I want to know how to add multiple rows in one submission without submitting every time. [add.html] <form id="add-form" class="forms-sample" method="post" action="/add/" enctype="multipart/form-data"> {% csrf_token %} {% include 'add_form.html' %} <div class="mt-2" style="text-align:right;"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> [add_form.html] <div> <label class="col-sm-3 font-weight-bold col-form-label pl-3 striped text-black">Date {% autoescape off %} <div class="text-danger small" style="line-height: 1rem;">{{ errors.date }}</div> {% endautoescape %} </label> <div class="col-sm-9 form-input-container"> <div> <input autocomplete="off" class="form-control col-sm-12 date" name="date" id="date" value="{{ supporting.date|date:'Y/m/d H:i' }}" > </div> </div> </div> <div> <label class="col-sm-3 font-weight-bold col-form-label pl-3 striped text-black">종류 {% autoescape off %} <div class="text-danger small" style="line-height: 1rem;">{{ errors.kinds }}</div> {% endautoescape %} </label> <div class="col-sm-9 form-input-container"> <div> <select id="kinds" name="kinds" style="margin-top: 4px; margin-bottom: 7px; padding: 1px 0.5rem 0 0.5rem; height: 2rem;"> <option value="">-------</option> <option value="A" {% if "A" == supporting.kinds %} selected {% endif %}>A</option> <option value="B" {% if "B" == supporting.kinds %} selected {% endif %}>B</option> </select> </div> </div> </div> <div> <label class="col-sm-3 font-weight-bold col-form-label pl-3 striped … -
Complex Tabular Data Representation in Angular from an API
I am trying to represent this table in angular13 I have created a backend API with Django Rest Framework with the following structure: FieldHead:{id,name} e.g Production FieldProperty: { id, name,FieldHead} e.g PRODUCTION in HRS Product: {id,name,weight} e.g.20ltrs Supplier: {id, name} e.g. ABZ, XYZ ProductPropertyCost:{FieldProperty,Product,Supplier,cost} I am trying to find the best format I can return the data inorder to represent it in this format for every Supplier and how to represent it like this -
Model serializer without any fields
I would like to have serializer which only validate instance field "default" and return nothing. I want do that without picking any fields but I'm receving an error that i need to pick some fields or use all_, can you please help me what i can do then ? class PaymentMethodDefaultSerializer(serializers.ModelSerializer): class Meta: model = PaymentMethod def save(self, **kwargs): instance = PaymentMethod.set_as_default(self.instance) return instance @staticmethod def validate_default(value): if value: raise serializers.ValidationError( 'There is an default payment' ) return value