Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Storing sser info from HTML forms to postgresql
I want to store the user input from the html form, for example first and last name. And store these in my postgresql database. I created the html file: <form > First Name: <input type="text" name="fname"> Last Name: <input type="text" name="lname"> <input type="submit" name=""> </form> I have created the model: class User(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) I have also connected the postgre database in the settings.py file. I am bit confused about how to connect the frontend and database. I think I need to add the model to the views.py and get the POST request to get the user input and store in the models. Please nudge me in the right direction. Thanks -
use datetime objects to filter queryset in Django (truncate to days)
I have a question regarding filtering with datetime. I have a following code: def filter_by_transaction_date(self, queryset): if self.user_filter.from_date: queryset = queryset.filter(created_at__gte=self.user_filter.from_date) if self.user_filter.to_date: queryset = queryset.filter(created_at__lte=self.user_filter.to_date) return queryset where queryset is obviously a queryset, created_at = models.DateTimeField(auto_now_add=True), self.user_filter.from_date== models.DateTimeField(null=True, blank=True) self.user_filter.to_date = models.DateTimeField(null=True, blank=True) What in this case filtering does it that check whether or not created_at field contains between 2 datetimes, that is we basically operate timestamps here. Issue. For example if object is created 26 august 13-45 and self.user_filter.to_date is 26 august 03-00, then this object would be filtered out. What I want is to filter them based on days only. For example if object is created 26 august 13-45 and self.user_filter.to_date is 16 august 03-00 – both datetimes are still belong to one date , which is 26 august. I want to use only days and somehow truncate hours, minutes, seconds, etc on both created_at and ( self.user_filter.from_date , self.user_filter.to_date) and compare only year, month and day. Target result ; object is created 26 august 13-45 and self.user_filter.to_date is 26 august 03-00, we truncate time, keep only date we compare 26 august <= 26 august -True, object gets inside filter... Sorry for entangled explanation, if so Thanks... -
Passing Values Between Views in Django
Simple scenario - firstview has a form (firstform) which has a field 'reference'. In secondview, there is a separate form (secondform) which also has a field 'reference'. I would like to initialize the value of 'reference' in secondview to be = the value of 'reference' in firstview. Am I able to do this without passing that parameter through the URL? I am using python 2.7 for reference. This is what I've tried. It doesn't seem to work this way and I am getting a "does not exist" error which I know just mean that I'm not actually getting that value. views.py def firstview(request): if request.method == "POST": form = FirstForm(request.POST) #this form contains 'reference' if form.is_valid(): form.save() return redirect('secondview') def secondview(request): form = SecondForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() ... reference_id = request.POST.get('reference') #this is how Im trying to get reference from the firstview form = SecondForm(initial={ 'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist" error }) .... return render(request, 'manifest_readonly.html', context) -
Unable to get user object from token DRF
Using the following: from rest_framework.authtoken.models import Token user = Token.objects.get(key='token string').user I only get username from it when I print(user). Trying to iterate through it as if it were an object doesn't work either. Am I missing something? -
How to use Django's CSRF protection in axios for different host?
I am working on ReactJS project as frontend and Django as backend and having trouble with CSRF protection! I am using Django CORS headers and I have done all set up correctly. It works as long as I have localhost to access both front and back ends. My frontend is running on localhost:3006 and backend us running on localhost:8899 port. So frontend is setting csrftoken cookie and sending it with post request. I am using axios.create() with withCredentials = true and it works fine. Now when my co-worker is running same frontend code from his system, trying to connect to backend that is running on my machine, he is getting 403 csrf cookie not found! At this time, he is running his frontend on localhost:3006, his own localhost and connecting to backend of my-ip:8899. So I believe that we would have this problem too on production when we will have www.example.com serving frontend and api.example.com serving backend as cookies of frontend host wont get sent to api host! My cors header settings in django, # Origin white list CORS_ORIGIN_WHITELIST = [ 'http://localhost', 'http://127.0.0.1', 'http://192.168.1.165', 'http://192.168.1.165:3006', ] CORS_EXPOSE_HEADERS = ( 'Access-Control-Allow-Origin: *', ) # Allowed methods CORS_ALLOW_METHODS = ( 'DELETE', 'GET', … -
Django next page in pagination on form submission
def listing(request): contact_list = Contacts.objects.all() paginator = Paginator(contact_list, 25) # Show 25 contacts per page page = request.GET.get('page') contacts = paginator.get_page(page) return render(request, 'list.html', {'contacts': contacts}) Let's say in each page I have a form, and when the form submitted I need to go to the next page. I first tried to add a hidden field in the form, and manually calculate the next page, and put into HTTPResponseRedirect, but then I lose the pagination. So what should be my strategy? Do I need to create a seperate view for form action, or should I use listing as form action and check wheter it is a GET/POST method, I am kind of lost here. -
Manipulate python django dictionary content
I am developing a simple weather application using Django. I am able to display city name, temp, wind speed, description of condition, and add/delete cities. When a city is added, the web app displays a card with that City name and all of those weather information described above. Being a rower, I would like to add a "safeToRow" section to a cities card. That section will take in the temperature and wind of the city from the python dictionary and assign it to two variables. Then run those variables through some simple if and else if conditions to determine is it's safe to row and finally returning the final value of safeToRow. Views.py def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=APIKEY' if request.method == 'POST': form = CityForm(request.POST) form.save() form = CityForm() cities = City.objects.all() weather_data = [] safeToRow = "" for city in cities: r = requests.get(url.format(city)).json() city_weather = { 'city' : city.name, 'temperature' : r['main']['temp'], 'wind' : r['wind']['speed'], 'description' : r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } weather_data.append(city_weather) temp = r['main']['temp'] wind = r['wind']['speed'] def row(temp, wind, safeToRow): if temp < 32: return safeToRow == "No" elif temp > 40 and wind < 15: return safeToRow == "No" elif temp < 40 and … -
How to customize django-ratelimit 403 forbidden page
I'm using django-ratelimit 2.0 for rate limiting my views. I want different custom 403 forbidden page for different views. For example if it is a sign up view. It should give message try after 1minutes. If it is a forgot password view then message should be try after 12 hours. Basically I want different rate limit message for different views. -
Django ORM: Reverse relation query multiple model from single single models
I am in trouble querying reverse relation, I learned a lot about select_related and prefetch_related, yet I failed to achieve this. At first see my models: from django.db import models import uuid class Person(models.Model): alias = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=20) class Appointment(models.Model): patient = models.ForeignKey(Person, related_name="patient_for_appointment", on_delete=models.CASCADE) data = models.CharField(max_length=20) class Sales(models.Model): customer = models.ForeignKey(Person, related_name="customer_for_sales", on_delete=models.CASCADE) amount = models.FloatField() class Prescription(models.Model): patient = models.ForeignKey(Person, related_name="Patient_for_prescription", on_delete=models.CASCADE) details = models.CharField(max_length=100) I am trying to filter Person Model to check if the person has any prescription, sales, and appointment I want to get these all with single query like the person. will filter it with a person alias (primary key) I can filter it with separate query like patient_alias = '53fsdfsdf-fdsfds-df-fdf' queryset = Appointment.objects.filter( patient__alias=patient_alias ) But I don't want this, coz, it has a performance issue. I don't want this with separate query. I want to query only Person model to check if a person has Appointment, prescription or Sales like Person.objects.filter(alias='a person alias) Can anyone please help me to achieve this? Much appreciated -
Can you manage two discrete forms with formset?
I am a little unclear on whether two separate forms can be handled in the same view via formsets. For example, consider these two models: class Task(models.Model): title= models.CharField(max_length=30) approvers = models.ManyToManyField( get_user_model(), through='TaskStep') class TaskStep(models.Model): approver = models.ForeignKey( get_user_model(), null=True, on_delete=models.SET_NULL) task = models.ForeignKey(Task, null=True, on_delete=models.SET_NULL) Is it possible to render a single form that edits both the task model instance and associated task steps together, which I can update in a single submit? I know I can use inlineformset_factory to display the TaskStep child options, but there isn't much documentation on it. If I pass the following in a view: def manage_tasks(request, task_id): task = Task.objects.get(pk=task_id) TaskStepInlineFormSet = inlineformset_factory(TaskStep, Task, exclude=('',)) if request.method == "POST": formset = TaskStepInlineFormSet(request.POST, request.FILES, instance=task) if formset.is_valid(): formset.save() # etc This only appear displays the TaskStep objects and not the parent Task? -
django get_or_create depending on result from a custom manager method
I am trying to implement a safe method of creating instances of the model Bar. I have a custom manager method to search for any nearby existing Bar instances based on a x, y pair of coordinates: Bar.objects.circle_search(x, y, radius) These x, y values typically come from Foo. Upon creating a Foo instance it should then be associated via a foreign key with an existing Bar instance if Foo.x, Foo.y are within radius of Bar.x, Bar.y. If no Bar instances are found then create one. Each Bar instance has x, y columns that are defined by the Foo that created it. I had something simple like: bar = Bar.objects.circle_search(foo.x, foo.y, radius) if bar is None: # fill some kwargs bar, created = Bar.objects.get_or_create(**kwargs) however there is an obvious race here where two nearby foo's could create separate Bar instances that are close to each other (there shouldn't be any Bar instances within radius of each other). Is there anyway to chain/insert the circle_search method to be used as the get part of get_or_create? i.e. in plain English - get a Bar that matches the circle_search, if not then create one. # something like? Bar.object.get_or_create(circle_search(foo.x, foo.y, radius), **kwargs) The problem is … -
django-rest-framework- accepting id for submitted foreign key field
I have the following models: class Parent(models.Model): name = models.CharField() class Child(models.Model): name = models.CharField() parent = models.ForeignKey(Parent, on_delete=models.CASCADE) with serializer: class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = ('id', 'name', 'parent',) read_only_fields = ('id',) and ModelViewSet: class ChildViewSet(viewsets.ModelViewSet): serializer_class = ChildSerializer permission_classes = (IsAuthenticated,) queryset = Child.objects.all() paginator = None If I query the api, I get a json structure that looks like: { "id": 1, "name": "Child Name", "parent": 3 } Which is exactly what I want. However, if I try to PUT the same data back, I get the error: ValueError: Cannot assign "3": "Child.parent" must be a "Parent" instance. How can I make a submission like this work? I should be able to submit my data in the same way I receive it from the API. -
How to get length of TextField in Django
I'm trying to get length of TextField instance by wrapping it into len(), but it's not working for me, says: Expected type 'Sized', got 'TextField' instead. class Entry(models.Model): text = models.TextField() def __str__(self): if len(self.text) > 50: return self.text[:50] + "..." -
How to update ImageFiled with default image?
Hello I have a Profile model When user creates a Profile, I set an default image to image1 field and then the user can upload a new image in place of default. Now I need to implement in views.py function the update of user uploaded images with default image again, so when the user need to delete an image I put default-image instead. Thanks a lot models.py class Profile(models.Model): image1 = models.ImageField( default='default-image.jpg', upload_to='images', blank=True) views.py def update_image1(request): if request.method == 'POST': image1 = request.user.profile.image1 -
Django - Is it possible to create models (then migrate them) through a webpage?
I would like to know if there are examples or is it possible to design a webpage in which you can create a database (postgres) while the server is up (the app and page is for creating databases) thanks -
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>") …