Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error message is not showing as form validation message in django
I have created the validation in the models itself and it's working fine for me. The problem is it is not showing in the form view instead shows as Django default error view.Here I attach the image -
Django: Revert or bypass "ValueError: Dependency on app with no migrations"
while attempting to separate the models in different apps, I bumped to an issue I would need support on: I have 2 models: class SeriesCompletion(models.Model): series = models.ForeignKey( 'Series', blank=True, null=True, on_delete=models.SET_NULL, ) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL,) and class Series(models.Model): ... users_who_completed = models.ManyToManyField( settings.AUTH_USER_MODEL, through='app1.SeriesCompletion',) which were both located in app1 the idea (that worked well in dev environment) was to do a dumpadata, move SeriesCompletion to app2 and do the migrations, than a loaddata to repopulate properly however, when moving to prod environment, I ran the app1 migration with the Series model with a reference to app2: class Series(models.Model): ... users_who_completed = models.ManyToManyField( settings.AUTH_USER_MODEL, through='app2.SeriesCompletion',) It passed in prod, and when moving to do the makemigration for app2, it blocked because of a circular reference: ValueError: <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x7f3e531f4400> contains a lazy reference to app2.seriescompletion, but app 'app2' isn't installed. I've tried a lot of things since, but I'm always blocked, and I am not able to move forwards doing a migration for app1 or for app2 ... or to move backwards returning to the previous migration with app1 I always end-up during the pre-migration/pre-makemigrations checks with the error message: ValueError: Dependency on app with … -
How to add extra command line arguments to createsuperuser - Django?
I have UserManager class below: class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) In the create_superuser function, i would like to add one more field to set tenant_id. This has to be taken from the command line, when using python manage.py createsuperuser. If i add tenant_id in create_superuser function like this create_superuser(self, email, password, tenant_id,**extra_fields), i'm getting the following error UserManager.create_superuser() missing 1 required positional argument: 'tenant_id'. Is there any way i can pass tenant_id from command line? -
How to get ceiling of seconds in a timedelta object
I'm working with Django and I fall into a problem that blocked me. I write this method to perform a duration as a difference between "end_time" and "start_time", the result is a timedelta object. @property def start_dt(self): if self.track and self.track.dt > 0 and not self.sample_intervals.is_empty(): try: return self.track.timestamp + datetime.timedelta(seconds=self.track.dt * self.sample_intervals.min()) except BaseException: return None else: intervals = self.get_datetime_intervals() return intervals.min() @property def end_dt(self): if self.track and self.track.dt > 0 and not self.sample_intervals.is_empty(): try: return self.track.timestamp + datetime.timedelta(seconds=self.track.dt * self.sample_intervals.max()) except BaseException: return None else: intervals = self.get_datetime_intervals() return intervals.max() @property def duration(self): return self.end_dt - self.start_dt It works well, but if I have, for example, 00:32:55.765000, the result is approximated down and I obtain 00:32:55 instead of 00:32:56. How can I approximate up or down depending on duration's microseconds? -
Run Command Line Inside Virtual Environment Using Python
I have a Django App running in a virtual environment on Windows 10. I am trying to create a Scheduled Job that allows to automatically start the Server when Windows Start. What I need to be done is the following command lines to be executed in this order: cd Django\project-name\ Scripts\activate.bat \\30 Seconds Later cd app-name\ python manage.py runserver 0.0.0.0:8000 What is the simplest way to do this ? Thanks -
how to serialize current user in django rest framework?
I wrote a custom user and defined the serializer for it, and now I have an endpoint that the user sent the get request. He should get the user information in json format. And since my response format is as follows { 'messages': msg, 'data': data } I do not know how to serialize the user or which generic view to use my code: class ProfileView(generics.RetrieveAPIView): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.user) if serializer.is_valid(): return successful_response( messages=_('User Profile'), data=serializer.data ) return unsuccessful_response(serializer.errors) and the error I get: { "errors": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got User." ] } } Anyone have an idea? -
How to restart Django-react frontend
Made a few changes in the jsx files on the frontend. The server uses django, react, apache2, python Now that i made a few change in the frontend, it wont show up in the website, untill i restart react How do I do? I tried. systemctl restart apache2 reboot . venv/bin/activate python ./manage.py runserver Server Files structure /var/www/backend /vaw/www/frontend -
do we need query set in CreateAPIView?
My question is quite straight forward. I'm actually not sure that queryset is required need for CreateAPIView or not.. ? class CreateNotificationAPIView(generics.CreateAPIView): """This endpoint allows for creation of a notification""" queryset = Notification.objects.all() #can we remove it, if we do so, will we face any issue in future ? serializer_class = serializers.NotificationSerializer -
Django Celery vs Django-Q
I'm relatively new into backend engineering (still learning). So, I have a question for which I didn't find any reliable answer searching on the internet. I wanna create a web-app with django. But I understand there is a need of task queuing system or similar worker tool for it. So I searched on the internet and found django-q, which I think would be easier to implement than django-celery (honestly I don't know much about any of them). But at the same time, I can see, most of the django developers are actually using django-celery. So my questions is, which one should I choose? Should I go with django-celery or django-q? And is there any key differences between them which should be considered? (or Am i asking the wrong question?) -
django: get HTML form value in view.py failed with empty <QueryDict: {}> and None value
I am new to django and follow the djangogirls tutorial. With a few modifications, I am trying to get the value from the form text field and print it in view.py and then display this value again in another "result" field in the html page. html: <!DOCTYPE html> <html> <body> <form> <div> <label>num_1:</label> <input type = "text" name="num_1" value = "1" placeholder="Enter value"> </div> <div> <label>num_2:</label> <input type = "text" name="num_2" value = "2" placeholder="Enter value"> </div> </form> <div> <label>result:</label> {{ result }} </div> <br> </body> </html> view.py: def post_list(request): # posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') num1 = request.POST.get('num_1') num2 = request.POST.get('num_2') result = int(num1)+int(num2) print(request.POST) print("num1 ", num1) # return render(request, 'blog/post_list.html', {'posts': posts}) return render(request, 'blog/post_list.html', {'result': result}) when I activate the local server, I got: Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. <QueryDict: {}> num1 None -
How to load an image file from my local hard drive to html page using python?
I want to load an image (.png file) from my local system to html page using python. -
Django Invalid Form
I have a modal with a form in it. The issue is that on invalid form it does return the form errors but it also closes the modal dialog box by rendering the home page again. It is also the home page so the return render is needed for the logging in. How would I just return to the screen if the post fails. def index(request): context = {} if request.method == "POST": print(request.POST) form = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user) if form.is_valid(): form.save() return redirect('home') else: form = UserProfileForm() context['form']= form return render(request, "home.html", context) modal {% block content %} <div class="modal fade" id="editProfile" tabindex="-1" role="dialog" aria-labelledby="editProfilelCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="editProfileLongTtitle">Edit Profile</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> {% include 'form.html' %} </div> </div> </div> </div> {% endblock %} -
How to create get or create object from serializer data
I'm passing two serializer with one view. On creating object I want to first create CaseId object which is why I'm poping out CaseObject from validated data. I want to get or create an object with the given data. Because I want to pass that to the CaseMessage object as a reference. class CaseMessageSerializer(serializers.ModelSerializer): case_id = serializers.IntegerField(required=False) case_object = CaseIdSerializer(required=False) message_type = ChoicesFieldSerializer(choices=CaseMessage.MESSAGE_TYPE) body_format = ChoicesFieldSerializer(choices=CaseMessage.BODY_FORMAT) class Meta: model = CaseMessage fields = "__all__" depth = 1 def create(self, validated_data): raw_case_object = validated_data.pop('case_object', None) # Not Getting or creating object with the given data. case = CaseId.objects.get_or_create(**raw_case_object) case_message = CaseMessage(**validated_data) case_message.caseid = case case_message.save() if not CaseAudience.objects.filter(case_id=case).exists(): case_audiance = CaseAudience( case_id = case, source_message = case_message, ) case_audiance.save() return validated_data The Errors are as follows: -
show/hidden field forms with condition in django
I have trouble when trying to hide and show form field in django. My code works well when showing form field <label class="col-md-8" id="sotien">{{form.so_tien}}</label> However I failed when trying hide the field with condition. If ma_code=="ptp", form.so_tien is hidden and vice versa my forms: class AddReportForm(forms.Form): list_ma_code=( ("skipcall","SKIP CALL"), ("ptp","PTP"), ) ma_code=forms.ChoiceField(label="Mã code",choices=list_ma_code,widget=forms.Select(attrs={"class":"form-control"})) so_tien=forms.IntegerField(label="Số tiền",widget=forms.NumberInput(attrs={"class":"form-control", "type":"number"}),required=False, initial=0) my html <label class="col-md-8" id="id_ma_code">{{ form.ma_code }}</label> <label class="col-md-8" id="sotien">{{form.so_tien}}</label> my js <script> function Hide() { if(document.getElementById('id_ma_code').options[document.getElementById('id_ma_code').selectedIndex].value == "ptp") { document.getElementById('sotien').show(); } else { document.getElementById('sotien').hide(); } } window.onload = function() { document.getElementById('id_ma_code').onchange = Hide; }; </script> There was not any error, but the code didnt work. Even if I change all to hide, it didnt hide anything I read some questions but fail to resolve my issue https://stackoverflow.com/questions/15136657/show-and-hide-dynamically-fields-in-django-form https://stackoverflow.com/questions/55893040/how-to-hide-fields-in-django-form-depending-on-the-selected-category Thanks for your reading and supporting me -
How to return data from two different models in django?
class RateList(core_models.TimestampedModel): centre = models.ForeignKey( Centre, null=True, on_delete=models.CASCADE, related_name="c_centre_rate_list" ) rate_type = models.ForeignKey( RateType, on_delete=models.CASCADE, related_name="c_rate_type_rate_list" ) test = models.ForeignKey("package.Test", on_delete=models.CASCADE, related_name="c_test_rate") class TestProcessingLab(core_models.TimestampedModel): centre = models.ForeignKey(Centre, on_delete=models.CASCADE, related_name='source_centre') test_category = models.CharField(max_length=50, null=True) test = models.ForeignKey("package.Test", on_delete=models.CASCADE, related_name='test') outhouse_centre = models.ForeignKey(Centre, on_delete=models.CASCADE, null=True, related_name='test_outhouse_centre') outsource_centre = models.ForeignKey("OutSourceLab", on_delete=models.CASCADE, null=True, related_name='test_outsource_source') I'm trying to get the desired output but i'm really stuck. The problem is RateList models contains all the tests. And In TestProcessingLab Model only those tests are there which are mapped means whether the tests is outhouse or outsource. [![TestProcessingLab Data][1]][1] [1]: https://i.stack.imgur.com/20ooR.png In this image only those tests are there which are mapped but I want all those tests also which are not mapped which are in RateList. How to achieve this? Any help would be really appreciated. -
how to fix connection refuse error using mail_sent function in Django
Hlo I m New in Django I Making a blog Project. I want to add sharing feature in my project via Email I m Having A Error Called Connection Refuse Error .Error Look Like that ConnectionRefusedError at /URL/ [Win Error 10061] No connection could be made because the target machine actively refused it Setting.py smtpserver = smtplib.SMTP("smtp.gmail.com", 587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo() smtpserver.login('xxyz, 'xyz') EMAIL_USE_TLS=True where I defined my views function my views file look like that views.py from django.core.mail import send_mail from Blog.forms import EmailsendForm def email_send_view(request,id): post=get_object_or_404(Post,id=id,status='published') sent=False if request.method=='POST': form=EmailsendForm(request.POST) if form.is_valid(): cd=form.cleaned_data send_mail('hello','how are you','xyz.d@gmail.com',[cd['to']]) sent=True else: form=EmailsendForm() return render(request,'blog/emailshare.html',{'form':form}) -
Foreign key field not rendering in serializers django
I am trying to show up the foreign key fields name instead of object id but not able to get through it. Tried using the related_name and then binding that to the serializer but still no luck, models.py class Employee(base_models.BaseDateModel): """ DB model to store employee data """ name = models.CharField(max_length=50) level = models.SmallIntegerField(choices=LEVEL_CHOICES, default=L1) def __str__(self): return f'{self.name} - {self.get_level_display()}' class Room(base_models.BaseDateModel): """ DB model to store available rooms in the building """ name = models.CharField(max_length=15) def __str__(self): return f'{self.name}' class Seat(base_models.BaseDateModel): """ DB model to store available seats in a given room """ room = models.ForeignKey('seating.Room', on_delete=models.CASCADE) def __str__(self): return f'{self.room} - {self.id}' class EmployeeSeating(base_models.BaseDateModel): """ DB model to store the seating details of any employee """ name = models.ForeignKey('seating.Employee', on_delete=CASCADE, related_name='emp_name') room = models.ForeignKey('seating.ROOM', on_delete=CASCADE, related_name='emp_room') seat = models.ForeignKey('seating.SEAT', on_delete=CASCADE, related_name='emp_seat') def __str__(self): return f'{self.name} - {self.room} - {self.seat}' serializers.py class EmployeeSeatingSerializer(serializers.ModelSerializer): emp_name = serializers.StringRelatedField() emp_room = serializers.StringRelatedField() emp_seat = serializers.StringRelatedField() class Meta: model = EmployeeSeating fields = ('id', 'emp_name', 'emp_room', 'emp_seat') views.py def listemp_api(request, pk=None): """ Method to return the list of employee in a given room """ if request.method == 'GET': room_id = pk if room_id: employee_data = EmployeeSeating.objects.filter(room_id = room_id) serializer = EmployeeSeatingSerializer(employee_data, many=True) … -
Django: Generating multiple similar tables and link them with another table
I want to store the historical stock price data in a database. E.g. I want a table which will contain the historical data of AAPL stock. In this table I'll have columns like date, open_price, close_price, etc. and this table will be linked to another table which will hold the fundamental information of the stock. Now, I want to do this for multiple stocks. As there are thousands of stocks, it'll be a very time consuming process to create a model for each stock. So, I want something like the following: class StockData(models.Model): date = models.DateField() open_price = models.DecimalField() close_price = models.DecimalField() high_price = models.DecimalField() low_price = models.DecimalField() adj_close_price = models.DecimalField() volume = models.PositiveIntegerField() class StockInfo(models.Model): stock_name = models.CharField(max_length=30) # other fundamental information # How to do this: link the instance of StockData here, which will hold the data of particular stock with name 'stock_name' How should I go about doing this in django? -
In Django, how does passing in a reference to the views function eventually get called by the path function?
I know my question is very similar to what is "request" in Django view but I can't make sense of the answers provided. I have also read the documentation that is related to my question, but still don't understand. I would greatly appreciate any elaboration to the other answers in addition to anything I ask that isn't covered in that question. In views.py, we can have something like this: from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("Hello, World") And in urls.py we have something like this: from django.urls import path from . import views urlpatterns = [ path('', views.home, name='hello-world-home'), ] My question involves views.home being passed in as a parameter to path. Based on one of the answers to a similar question, views.home is passing the "function object" as a parameter to path. If it's not calling the function, don't we need pass it like this: views.home()? How does it eventually get called by path? If there is some documentation about being able to pass in a reference to a function in Python, I would appreciate it if you could link it. Is being able to pass in a reference to a function exclusive to … -
Django list_select_related gives me this error
#app/admin.py @admin.register(models.Product) class ProductView(admin.ModelAdmin): list_display = ['title', 'unit_price', 'inventory_status', 'collection_title',] list_editable = ['unit_price'] list_per_page = 10 list_select_related = ['collection'] #app/models.py class Collection(models.Model): title = models.CharField(max_length=255) featured_product = models.ForeignKey( 'Product', on_delete=models.SET_NULL, null=True, related_name='+') class Meta: ordering = ['title'] ''' def __str__(self) -> str: return self.title ''' class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotions = models.ManyToManyField(Promotion) #Error I got: SystemCheckError PS - I know I can use 'collection' in list_display directly as it is already a field in my product model, but I want to preload a related field/table using list_select_related and use 'collection_title' in list_display. Please help. Thank You. ERRORS: <class 'store.admin.ProductView'>: (admin.E108) The value of 'list_display[3]' refers to 'col lection_title', which is not a callable, an attribute of 'ProductView', or an attribute or method on 'store.Product'. -
Setting up OSRM on Heroku
Making a new thread for this post Setting up OSRM (Open Source Routing Machine) on Heroku because it's been 6 years and the older buildpacks don't seem to work, at least for me. Has anyone had recent success setting up OSRM in their Heroku apps? I've tried several different ways over the last couple days but nothing has worked. My situation may be specific because I already have a django heroku app and want to run OSRM inside so I can access it from the local host. I've tried using the following buildpacks separately, and they each fail when I try to push my code. I think they're just not maintained and outdated by now. https://github.com/chrisanderton/heroku-osrm-buildpack https://github.com/jpizarrom/osrm-heroku I currently already use the two below buildpacks and have added the osrm ones on top: https://github.com/heroku/heroku-geo-buildpack.git heroku/python [one of the osrm buildpacks] I was thinking that maybe there's no recent literature on setting up OSRM on Heroku because Heroku Docker is much easier to use now. But I've also tried setting up OSRM with Heroku Docker and failed. I would like to run the docker image inside my current app, but my app doesn't use Heroku's container stack. And I've also been … -
How to show data from cluster done by using k means on website
I have categoriesed cricket player using k-means clustering but now not able to show that particular player belongs to which category in my Website using html and django can anyone help -
In Django bootstrap project toast messages showing for the first card in loop element
I want to toast messages for all those cards. but it is showing for the first card only. I have attached a view of my page where I want to add a toast message to view the details of the card if a user is not logged in. ![Text]https://i.stack.imgur.com/cYSPW.jpg) document.getElementById("toastbtn").onclick = function() { var toastElList = [].slice.call(document.querySelectorAll('.toast')) var toastList = toastElList.map(function(toastEl) { return new bootstrap.Toast(toastEl) }) toastList.forEach(toast => toast.show()) } <section class="details-card"> <div class="container"> <div class="row"> {% for homes in home %} <div class="col-md-4 mb-4"> <div class="card-content"> <div class="card-img"> <img src="{{ homes.coverImg.url }}" alt="Cover Image"> <span><h4>{{ homes.pricePerMonth }}Taka</h4></span> </div> <div class="card-desc"> <p class="small mb-1"> <i class="fas fa-map-marker-alt mr-2"></i>{{homes.address}}</p> <h3>{{ homes.title}}</h3> {% if request.user.is_authenticated %} <a href="{% url 'HomeDetails' homes.id %}" class="btn btn-md btn-primary hover-top">Details</a> {% else %} <button type="button" class="btn btn-primary" id="toastbtn">XDetails</button> {% endif %} </div> </div> </div> {% endfor %} </div> </div> </section> <!-- Alert Message Popup--> <!--bottom-0 end-0 p-3--> <div class="position-fixed top-50 start-50 translate-middle p-3" style="z-index: 11"> <div id="liveToast" class="toast hide" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <img src="({% static 'img/icon.png' %})" class="rounded me-2" alt="..."> <strong class="me-auto">My Second Home</strong> <small>0.1s ago</small> <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button> </div> <div class="toast-body"> Hello!<br>You need to login first to see details. <div class="mt-2 … -
Ajax with knockout form is not working in django
productscreate.html <form> <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="value: title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image"></td> <br> </tr> <tr> <td><button type="button" id="submit" data-bind="click: mySubmit">Submit</button></td> </tr> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <script> var formData1 = new FormData(); $(document).on('click', '#submit',function(e){ e.preventDefault() var viewModel = { title:ko.observable(),description:ko.observable(), mySubmit : function(formElement) { var formData = { 'title' : viewModel.title() , 'description' : viewModel.description(), }; formData1.append('image', $('#image')[0].files[0]) $.ajax({ type: "POST", url: '{% url "productscreate" %}', data: formData,formData1, cache: false, processData: false, enctype: 'multipart/form-data', contentType: false, success: function (){ window.location = '{% url "productslist" %}'; }, error: function(xhr, errmsg, err) { console.log(xhr.status + ":" + xhr.responseText) } }); } }; ko.applyBindings(viewModel); </script> views.py class ProductsList(ListView): model = products context_object_name = 'products' template_name = "productslist.html" class ProductsCreate(CreateView): model = products fields = ['title','description','image'] template_name = "productscreate.html" success_url=reverse_lazy('productslist') class ProductsDetailView(DetailView): template_name = "productsdetail.html" queryset = products.objects.all() context_object_name = 'products' model = products Ajax with knockout is not working in this project I want to submit the form with help of ajax with knockout js code Now when i click submit button form value is not submitting. I want to submit form with ajax I don't know … -
how can we add data into database using migration files in django?
I am currently using Django 3.2 i wanted to add data to Database using migration files. from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sbimage', '0001_initial'), ] operations = [ migrations.CreateModel( name='AuthNumberR', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('auth_number_r', models.CharField(max_length=64)), ], ), migrations.RunSQL("INSERT INTO AuthNumberR (id, auth_number_r) VALUES (2, 'c');"), ] is this the proper way to insert data?