Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make a property function to act like a real field in the database
i want to make a (group by) which depend on some other fields , models.py class Product(models.Model): pass class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') date_time = models.DateTimeField(default=datetime.now()) @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE,default='' ) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) views.py class View(ListView): pass def get_context_data(self , *args,**kwargs): context = super().get_context_data(*args , **kwargs) context['daily'] = Order.objects.values('date_time').aggregate(days=Sum('total')) return context (Cannot resolve keyword 'total' into field. Choices are:...) is it possible to make the property function act as a field in the db ? or if there another way to achieve the same thing i trying to implement ? i also tried to views.py from .models.Order import total context['daily'] = Order.objects.values('date_time').aggregate(days=Sum(total())) but doesnt work ! thanks for any advice .. -
Many - To - Many field changes - Too many api calls
Using Django, I'm encountering the known issue with the Many-to-Many field. In the post_save_event signal/hook, the value in the Event instance for the many-to-many field: categories does not get updated with the most recent values submitted on the admin form. It always shows the old values. This is my save hook where I have a parent "Event" and each event has a field for 0 or many categories. However, the instance.categories value is not updated with most recent value. @receiver(post_save, sender=Event) def post_save_event(sender, instance, **kwargs): success = events_api.create_or_update_event(instance) I'm aware of why this happens. Basically, the many-to-many field needs to save after the parent model because the many-to-many table needs to have the primary key of events. I did the fix that i found online below. This is the signal that gets sent after the many-to-many table transaction is committed. This sort of works as a workaround but obviously this means that if the categories change on the event, the api gets called multiple times, even worse the m2m_changed signal seems to fire twice when it happens. So I end up calling the api 3 times for one update. Any work around/ hook i can use to maybe just do … -
Django ORM: queryset with SIMPLE 'order by'
I'm trying to make this simple 'group by' expression using django ORM, but I'm not sure how it would be: SELECT id, title, hotel_id, booking_id, day_number FROM `bookings_booking_item` where hotel_id IS NOT NULL AND booking_id=xxx group by booking_id, hotel_id ORDER BY id asc What I want to achieve is to get only one (the first) 'item' result per booking and hotel. Can anyone please help me, please? Thank you! -
Django bootstrap4 tab to perform action (call python function) and stay on current page
I had a quick look around and couldn't find anything really that matches this. I have a bootstrap4 navbar in my base.html template which is then inherited by all other pages on the web app. Most of the tabs are drop downs, which have options to link to other pages which is fine and working. I have one drop down which has a couple of items which are not meant to navigate to a page but rather execute an action (e.g. generate a report). I can do the report generation fine, but I am unable to find a solution that results in me staying on the same page. Base.html <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> BDE Report </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="{% url 'bde_report' %}">Generate</a> <a class="dropdown-item" href="#">Download latest</a> </div> </li> url.py urlpatterns = [ path('', views.home, name='home'), path('bde_report/generate/', views.home, name='bde_report'), path('admin/', admin.site.urls), path('db_display/', views.db_display, name='db_display'), path('db_display/<str:table_name>/business_data_form', views.business_data_display, name='business_data_display'), path('db_display/business_data_form/new', views.business_data_new, name='business_data_new') ] views.py def home(request): # If the generate BDE button is pressed, return the report if request.path == '/bde_report/generate/': return generate_report() return render(request, 'home.html') With the current implementation it currently goes to the home page and generates the report, but ideally … -
How to know which sub module are in use with python module?? unable to create requirement.txt for docker image
I am in the process of deploying my flask solution over docker. To deploy my flask solution over docker I need to prepare requirement.txt file. Due to not having information about which version of python module I am using , I am unable to prepare requirement.txt file. As I am using python and flask, so I have version information about flask and python but how to know which submodules required by flask and what's their version ?? -
django view download zip file via HTTP Response
I have a Django view that properly creates a zip folder but I am having trouble serving it to website here is the view def download_shp(request): template="download_shp.html" if request.method=="GET": data=request.GET.get("file_id") ZIPFILE_NAME="" for x,y,z in os.walk(MEDIA_ROOT): for i in y: if data[:-4] in i: shutil.make_archive(os.path.join(MEDIA_ROOT,i),"zip",os.path.join(MEDIA_ROOT,i)) ZIPFILE_NAME=os.path.join(MEDIA_ROOT,i+'.zip') response = HttpResponse(ZIPFILE_NAME, content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename='+ZIPFILE_NAME return response this is a pic of the zip file when I go to download the file it download but i get this error when trying to open it -
Unable to create process django python
I just want to open my Django project and that is copy from another computer. when I install some module in the current computer, its show like that Fatal error in launcher: Unable to create process using '"c:\me\tmsweb~3\backend\env\scripts\python.exe" "D:\myproject 2\backend\env\Scripts\pip.exe" install drf-generators' this python.exe file path is old computer file path and how can I change this file path? I already checked the path in an environment variable and it's correct and points to the current computer. -
Django CORS ORIGIN WHITELIST and ALLOWED_HOST not filtering anything
I'm trying to deploy a Django application (to make REST Apis ) and a React application (who use my Apis ) on the same VPS. I'm setting up CORS for Django, and i still can use my API with postman as i shouldn't since i only allow my VPS IP and localhost. I've tried first with ALLOWED_HOSTS = ["*"] and CORS_ORIGIN_ALLOW_ALL = True and everything went like it should, i could use my API from anywhere but now when i replace "*" with my allowed hosts and set cors origin allow all at False it's like nothing changed. I tried to remove/set http from both allowed hosts and whitelist but it changed nothing. CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ["MYIP","127.0.0.1"] ALLOWED_HOSTS = ["MYIP"] I use python 3.6, django 2.2 and react 16.8. Thank for helping -
Django - empty form cannot be saved in database
I have a form in which, user specifies lawyer-spec and save the data to the database. However I get an error that **null value in column "lawyer_spec" violates not-null constraint** So the data from the form is not processed properly. forms.py class MakeAppointmentForm(forms.ModelForm): first_name = forms.CharField(required=True) class Meta: model = LawyersSpec fields = ['lawyer_spec'] def __init__(self, *args, lawyer_id, pk, **kwargs): super().__init__(*args, **kwargs) lawyer_id_from_kwargs = lawyer_id lawyer_specs = LawyersSpec.objects.filter(lawyer=lawyer_id_from_kwargs) choices = [(spec.lawyer_spec, dict(CASES)[spec.lawyer_spec]) for spec in lawyer_specs] self.fields['lawyer_spec'].choices = choices views.py @method_decorator(user_required, name='dispatch') class MakingAppointmentView(CreateView): template_name = "make_appointment.html" form_class = TestPy.forms.MakeAppointmentForm model = TestPy.models.CalendarAppointmentsReserved def form_valid(self, form): calendar_model = TestPy.models.CalendarFreeSlot.objects.get(pk=self.kwargs.get('pk')) calendar_model.is_available = False calendar_model.save() self.object = form.save(commit=False) self.object.users_id = self.request.user self.object.calendar_free_id = calendar_model self.object.case = self.object.spec self.object.save() return redirect('home') models.py class LawyersSpec(models.Model): lawyer = models.ForeignKey('MyUser', on_delete=models.PROTECT) lawyer_spec = models.SmallIntegerField(choices=CASES) class CalendarAppointmentsReserved(models.Model): calendar_free_id = models.ForeignKey('CalendarFreeSlot', on_delete=models.PROTECT) users_id = models.ForeignKey('MyUser', on_delete=models.PROTECT) case = models.SmallIntegerField(choices=CASES) How can I process the data properly and save in the database? -
How to fix "Forbidden (403) CSRF verification failed. Request aborted." error in django
I am getting this common error in django.i am doing a project in django in a virtual environment folder. here is my setting.py file MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] my html file {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Instapic</title> <link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/styles.css' %}"> </head> <body> <div class="login-clean"> <form method="post"> {% csrf_token %} <h2 class="sr-only">Login Form</h2> <div class="illustration"> <div style="display: none" id="errors" class="well form-error-message"></div> <img src="{% static 'assets/img/logo.jpg' %}"> </div> <div class="form-group"> <input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4"> </div> <div class="form-group"> <input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6"> </div> <div class="form-group"> <input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6"> </div> <div class="form-group"> <button class="btn btn-primary btn-block" id="go" type="submit">Create Account</button> </div><a href="#" class="forgot">Already got an account? Login here ...</a></form> </div> <script src="{% static 'assets/js/jquery.min.js' %}"></script> <script src="{% static 'assets/bootstrap/js/bootstrap.min.js' %}"></script> <script src={% static "assets/js/django-ajax.js" %}></script> <script type="text/javascript"> $(document).ready(function() { $('#go').click(function() { $.post("ajax-sign-up", { username: $("#username").val(), email: $("#email").val(), password: $("#password").val() }, function(data, status){ if (JSON.parse(data).Status == 'Success') { window.location = '/'; } else { $('#errors').html("<span>" + JSON.parse(data).Message + "</span>") … -
Python supervisord error: <class 'ConnectionRefusedError'>
I am trying to run my celery tasks in background using supervisor. I foolowed this article to setup celery and supervisor. However when I try to run below command : sudo supervisorctl reread I am getting following error : error: <class 'ConnectionRefusedError'>, [Errno 111] Connection refused: file: /usr/local/lib/python3.6/dist-packages/supervisor/xmlrpc.py line: 560 My environment details : Python 3.6.5 Django 1.11 (In a virtual environment) supervisord --version 4.0.4 -
How to use validate_unique validation in django form
Anyone know how to use validate_unique validate in django i used in view.py, it raise an validation error, that's good but this error is not showing me properly regist = UserModel(username=uname, email=email, name=name, password=password, status=1) regist.validate_unique() -
How to connect a Django rest framework into android app in testing environment?
I have built a django website for blog posts, and i have built rest APIs for it also so i can use it into my android app, but that website is working in my local host, now i have tried to connect it with an android app using retrofit and tried to make a simple call from the android app but it doesn't work, i just need the very basic steps to connect that local host to my android app and i will take care of retrofit calls and other coding stuff. I have already tried to create retrofit client passing BASE_URL = "http://127.0.0.1:8000" but it doesn't work too private static final String BASE_URL = "http://127.0.0.1:8000/api/"; private static RetrofitClient instance; private Retrofit retrofit; private RetrofitClient(){ retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } public static synchronized RetrofitClient getInstance(){ if(instance == null){ instance = new RetrofitClient(); } return instance; } public Api getApi(){ return retrofit.create(Api.class); } When making a simple call it the onFailure method triggers -
django images cannot be updated from defaults
I have an image upload function in django. However, images cannot be uploaded. The page is redirected to successURL. I don't understand the cause. The view is current because it uses multiple forms. #view def UserEdit(request): if request.method == 'POST': form = forms.UserUpdateForm(request.POST, instance=request.user) subform = forms.ProfileUpdateForm(request.POST, instance=request.user.profile) if all([form.is_valid(), subform.is_valid()]): user = form.save() profile = subform.save() return redirect('person:myaccount', username=request.user) else: form = forms.UserUpdateForm(instance=request.user) subform = forms.ProfileUpdateForm(instance=request.user.profile) return render(request, 'accounts/accounts_edit.html', { 'form': form, 'subform': subform, }) #form class ProfileUpdateForm(BaseModelForm): class Meta: model = profile fields = ('first_name','last_name','birthday','image',) class UserUpdateForm(BaseModelForm): class Meta: model = User fields = ('username','email',) #model class profile(models.Model): image = models.ImageField(upload_to='profile/',default='profile/default.jpg') #html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="text-center col-lg-6 col-md-6 col-sm-10 mx-auto"> <div class="form-group"> {{ form }} </div> <div class="form-group"> {{ subform }} </div> <button type="submit" class="fadeIn fourth btn btn-light">Submit</button> </div> </form> -
initializing Foreign Key models in code has no effect
I have a foreign key model like this: invite_discount_owner = models.ForeignKey('self', verbose_name='aaa', null=True, blank=True, on_delete=models.CASCADE, related_name='invited_customer') and in some part of my code, I want to initialize it with a correct data type: request.user.invite_discount_owner = discount_owner but it has no effect and this field stays empty! -
django: while files are preparing for download , show loading animation
I use Django , When files are preparing for download , I want to show loading circle animation , How can i understand files preparing finish time ? I try this code but its useless because it calculate is long for response request.start_time = time.time() print("start") print(request.start_time) print("final") print(time.time()) total = time.time() - request.start_time print("total unclear") print(total) print("total") print(int(total * 1000)) No error -
How to print the string value of a choices field
I have an integer field that provides 3 choices for a blog post: class Post(models.Model): STATUS_DRAFT = 0 STATUS_PUBLISHED = 1 STATUS_DELETED = 2 STATUS_CHOICES = ( (STATUS_DRAFT, 'draft'), (STATUS_PUBLISHED, 'published'), (STATUS_DELETED, 'deleted'), ) status = IntegerField(choices=STATUS_CHOICES, default=STATUS_DRAFT) When I render this in a template with {{ blog.status }} it prints the integer value (0, 1, 2). How can I call it to print the string value (draft, published, deleted)? -
Authorization model for REST API for ReactJs and Django
Hi I am trying to create an rest api using Django Framework and there is independent frontend part of ReactJs .Basically Reactjs will consume the Django rest_api .But I want to have authentication also provided to our api.So how can we proceed with it.Can anyone please explain? -
1054, "Unknown column 'user_account_id_fk_id' in 'field list'"
I focusing in insert log table that relate with user account and i have got a problem about inserting new row using django in views file. So it may came from my models. I Have no idea how to fixed this problem. I was change both of models settings and in views file by change queryset using get all and filter Models file class user_account(models.Model): user_account_id = models.IntegerField(primary_key=True, max_length=11, unique=True, null=False) username = models.CharField(max_length=50) password = models.CharField(max_length=255) display_name = models.CharField(max_length=100) mobile_no = models.CharField(max_length=50) email = models.CharField(max_length=255) is_delete = models.SmallIntegerField(max_length=1) create_date = models.DateTimeField() create_user_account_id = models.IntegerField(max_length=11) modify_date = models.DateTimeField() modify_user_account_id = models.IntegerField(max_length=11) delete_date = models.DateTimeField() delete_user_account_id = models.IntegerField(max_length=11) last_login = models.DateTimeField() is_authenticated = models.SmallIntegerField(max_length=1) class Meta: app_label = 'users' db_table = 'user_account' class user_account_log(models.Model): user_account_log_id = models.BigIntegerField(primary_key=True, max_length=20) user_account_id_fk = models.ForeignKey(user_account, unique=True, on_delete=models.DO_NOTHING, related_name = 'user_acc') action = models.CharField(max_length=100) title = models.CharField(max_length=100) description = models.TextField() refer_id = models.CharField(max_length=50) refer_table = models.CharField(max_length=50) class Meta: app_label = 'users' db_table = 'user_account_log' Views file user_log = user_account_log() user_log.action = "aaaa" user_log.title = "" user_log.description ="" user_log.refer_id = "AAAA" user_log.refer_table = "" user_log.user_account_id_fk_id = str(user_account.objects.get(user_account_id=request.user.user_account_id).user_account_id) # Save user_log.save() -
Django OperationalError: Parser Stack Overflow
I have a multi-page form for an accounting app in my project. The first page allows the user to select multiple creditors, the second to select multiple debtors, and the third generates a table so they can input the credit from each debtor to each creditor. Each page of the form passes the selected data to the next page via POST (using the UUID of the accounts in question), and the final page has the "submit" button that actually generates the transaction object in the database. When I use the form with a large number of debtors or creditors selected, I get an "OperationalError: Parser Stack Overflow." From the only other question on this topic I can find (django.db.utils.OperationalError: parser stack overflow) it looks like I need to either find a slimmer way of transmitting that data (perhaps by creating an "intermediary" model in the database to hold the data from each page so that each page need only be passed a single object). However, as you can see from the error below, it is the "account_list" that causes the overflow. This list comes from the query: Account.objects.all().order_by('type') So I am unsure that this would solve the problem. Alternatively, I … -
DRF formatting XLSX content
I am trying to set a different color on every second row in XLSX file. From the documentation I see that I can pass some conditions using body property or get_body() method, but this only allows me to set somewhat "static" conditions. Here is the ViewSet config responsible for rendering the XLSX file: class MyViewSet(XLSXFileMixin, ModelViewSet): def get_renderers(self) -> List[BaseRenderer]: if self.action == "export": return [XLSXRenderer()] else: return super().get_renderers() @action(methods=["GET"], detail=False) def export(self, request: Request) -> Response: serializer = self.get_serializer(self.get_queryset(), many=True) return Response(serializer.data) # Properties for XLSX column_header = { "titles": [ "Hostname", "Operating System", "OS name", "OS family", "OS version", "Domain", "Serial number", "Available patches", ], "tab_title": "Endpoints", "style": { "font": { "size": 14, "color": "FFFFFF", }, "fill": { "start_color": "3F803F", "fill_type": "solid", } } } body = { "style": { "font": { "size": 12, "color": "FFFFFF" }, "fill": { "fill_type": "solid", "start_color": "2B2B2B" }, } } -
form.is_valid() not working when using django forms for updating information to the databse
So I wanna be able to update information of a router in the database using a form, I wanna have a form pre-populated with that specific router details. The problem is that form.is_valid() is not working I tried using {{ form.errors }} {{ form.non_field_errors }} and print(form.errors) but none of them worked views.py (incomplete) def info_router(request, pk): rout = Routers.objects.get(sn=pk) if request.method == 'GET': # Insert the info in forms form = UpdateRouter() rout = Routers.objects.get(sn=pk) args = {'router': rout} return render(request, "router_info.html", args) if request.POST.get('delete'): # Delete router rout.delete() messages.warning(request, 'Router was deleted from the database!') return redirect("db_router") if request.method == 'POST': #Updating the form form = UpdateRouter(instance=Routers.objects.get(sn=pk)) print(form) print(form.errors) if form.is_valid(): data = UpdateRouter.cleaned_data mac = data['mac'] print(mac) return HttpResponseRedirect('db_router') else: print("Invalid form") return render(request, "db_router.html", {'form': form}) forms.py class UpdateRouter(ModelForm): class Meta: model = Routers fields = ['model', 'ip_addr', 'name', 'sn', 'mac'] template <form class="form-horizontal" action="" method="post"> {% csrf_token %} <div class="form-group"> <!-- Form with the router details --> <label class="control-label col-sm-2" for="text">Serial number:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="text" name="sn" value="{{ router.sn }}" readonly> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="text">Model:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="text" value="{{ router.model }}" name="model" readonly> </div> </div> <div … -
Django HoneyPot Change Password Issue
I would appreciate if you could give me any clue! As I don't have experience in this, probably I've misunderstood smth. I'm using honeypot, more specifically honeypot.middleware.HoneypotMiddleware with HONEYPOT_FIELD_NAME in my API (settings.py). As for the moment it's enough, I'm using the basic implementation for login, password change, reset from django.contrib.auth. In login I did a small customization so I added it in the url (authentication_form=CustomAuthenticationForm). So I don't konw what I'm missing because the login page works (it is also a form), but the password change, reset ones are returning 400 Bad Request. Honey Pot Error (honey_pot_fieldname). Request aborted. django: 2.1.2 django-honeypot: 0.7.0 Thanks in advance! -
django not responding via submit in frontend using post request in form
front end is not giving response to djangi function call via forms <form method="post" action="choose" class="login100-form validate-form" id="loginFrm"> {% csrf_token %} <span class="login100-form-title p-b-59"> Sign In </span> <div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex@abc.xyz"> <!-- <span class="label-input100">Email</span> --> <input class="input100" type="text" name="email" placeholder="Email address..."> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input" data-validate = "Password is required"> <!-- <span class="label-input100">Password</span> --> <input class="input100" type="text" name="pass" placeholder="Password"> <span class="focus-input100"></span> </div> <div class="flex-m w-full p-b-33"> <div class="contact100-form-checkbox"> <span class="txt1"> <a href="javascript:void(0)" class="txt2 hov1" id="goForgot"> Forgot Password? </a> </span> </div> </div> <div class="container-login100-form-btn"> <div class="wrap-login100-form-btn"> <div class="login100-form-bgbtn"></div> <button type="submit" class="login100-form-btn"> Sign In </button> </div> <a href="javascript:void(0)" class="dis-block txt3 hov1 p-r-30 p-t-10 p-b-10 p-l-30" id="goSignup"> Sign Up <i class="fa fa-long-arrow-right m-l-5"></i> </a> </div> </form> -
Django - How to use the exact same clean() method on multiple forms
I have multiple forms that uses the same clean() and clean_<field_name>() methods. My problem is that i write the exact same code for all my forms, something like: forms.py class FirstForm(forms.Form): ... clean(): <long clean code that repeats on all forms> clean_field1(): <clean_field1 code that repeats on all forms> class SecondForm(forms.Form): ... clean(): <long clean code that repeats on all forms> clean_field1(): <clean_field1 code that repeats on all forms> class ThirdForm(forms.Form): ... clean(): <long clean code that repeats on all forms> clean_field1(): <clean_field1 code that repeats on all forms> So my question is what it the best approach to write those clean() methods on 1 place and just call them on different forms?