Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Could not find the GDAL library
when I ran ./manage.py runserver i got django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. So, I find out GDAL is not installed by running brew list and I did not find it when I ran brew install gdal i got this error Error: gdal: Failed to download resource "gdal" Failure while executing; `git clone --branch master -c advice.detachedHead=false https://github.com/OSGeo/gdal.git /Users/apple/Library/Caches/Homebrew/gdal--git` exited with 128. Here's the output: Cloning into '/Users/apple/Library/Caches/Homebrew/gdal--git'... error: RPC failed; curl 18 transfer closed with outstanding read data remaining error: 715 bytes of body are still expected fetch-pack: unexpected disconnect while reading sideband packet fatal: early EOF fatal: fetch-pack: invalid index-pack output is there other ways to install gdal because my internet connection too slow, Also, where is the problem here. -
Django/Tastypie reverse relation not working
I'm trying to save and insert data into 2 related tables with a single POST request and the Tastypie framework. I sent a nested JSON, which is recieved by my Restaurents resource. This resource will then insert data into the Staff and create the OneToMany relation. Resources class RestaurantResource(ModelResource): staff = fields.ToManyField('api.resources.StaffResource', attribute='staff_set', related_name='staff_fk', blank=True, null=True, full=True) class Meta: authorization = Authorization() queryset = Restaurant.objects.all() resource_name = "staff" allowed_methods = ['get', 'post', 'patch', 'put'] def full_hydrate(self, bundle, for_list=False): initObj = Deserializers.buildResource(self, bundle, "initialisation") # Fetches each field from nested JSON and puts it into python object, so I can assign them to bundle.obj # Fields for Staff table bundle.obj.Name = initObj.Name bundle.obj.Gender = initObj.gender # Fields for Restaurant table bundle.obj.Postcode = initObj.postcode bundle.obj.Capacity = initObj.capacity return bundle def obj_create(self, bundle, **kwargs): set_info_obj = self.full_hydrate(bundle) set_info_obj.obj.save() # Here I'm expecting both tables to be populated with data. However, just Restaurant is populated. return bundle class StaffResource(ModelResource): staff_fk = fields.ToOneField(RestaurantResource, 'staff_fk') class Meta: queryset = Staff.objects.all() Models class Restaurant(models.Model): RestaurantID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Postcode = models.CharField(max_length=200) Capacity = models.CharField(max_length=200) # objects = InheritanceManager() class Staff(models.Model): StaffID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Name = models.CharField(max_length=200) Gender = models.CharField(max_length=200) RestaurantID = models.ForeignKey(SetInfo, on_delete=models.SET_DEFAULT, default=1, … -
Can I create Django models automatically?
I'm working on a resume website with Django in which, for the skill section I defined a model as below, from django.db import models class Skills(models.Model): name = models.CharField(max_length=50) level = models.DecimalField(max_digits=3, decimal_places=3) def __str__(self): return self.name But, for example, if I add a skill "Python" through admin in this model, I want to add a few slides for the skill, each containing a image and a paragraph, to give detailed information about my skill. In other words, I want to create a table for each skill I'll add with columns named image, and description. Is there any way I can achieve it? -
Trouble in querying deep nested related field in django serializer
I have models this deep nested related model that looks like this: class User(models.Model): username = models.Charfield(max_length=20) ... class Workspace(models.Model): ... class Folder(models.Model): workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE) class File(models.Model): folder = models.ForeignKey(Folder, on_delete=models.CASCADE) class Member(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) workspace = models.ForeignKey(Workspace, related_name="members", on_delete=models.CASCADE) class Post(models.Model): file = models.ForeignKey(File, on_delete=models.CASCADE) Now my question is how can I have a Post query result that looks like this: { "id": 1, "file" 2, "members" : [1,2,3] } And if possible, the solution must be a in serializer as I need it to be used together with Django rest framework -
Make model function to stop counting
I have a model function that counting the progress of an event between date time fields. Is it possible to stop the progress after reaching 100. For example: models.py start_appointment = models.DateTimeField(default=timezone.now, blank=True) end_appointment = models.DateTimeField(default=timezone.now, blank=True) model function def get_progress(self): if (self.status) == 'New' or (self.status) == 'Finished': now = timezone.now() progress = ((timezone.now() - self.start_appointment) / ((self.end_appointment - now) + (now - self.start_appointment)))*100` if progress > 100.0: ... return progress Thank you -
how do i combine two template views into on single view here?
I have implemented two views to display data according to the choice_fields but i have two views with slightly different logic in views and templates how do i combine them into one so that i take care of DRY views.py: class View1(LoginRequiredMixin,TemplateView): template_name = 'temp1.html' def get_context_data(self, **kwargs): context = super(View1,self).get_context_data(**kwargs) context['progress'] = self.kwargs.get('progress', 'in_progress') if context['progress'] == 'in_progress': context['objects'] = Model.objects.filter(progress='in_progress') else: context['objects'] = Model.objects.filter(progress__iexact=context['progress'], accepted_by=self.request.user) return context class View2(LoginRequiredMixin,TemplateView): template_name = 'temp2.html' def get_context_data(self, **kwargs): context = super(ManagerTicketView,self).get_context_data(**kwargs) context['progress'] = self.kwargs.get('progress', 'in_progress') if context['progress'] == 'in_progress': context['objects'] = Model.objects.filter(progress='in_progress',created_by = self.request.user) else: context['objects'] = Model.objects.filter(progress__iexact=context['progress'], created_by=self.request.user) return context -
Field 'id' expected a number but got '9dzlzyftu9k5fi5ta8omk1mxgx1lyvhg'
It works fine until the form is created, but if you enter a value and click the Submit button, the following error code is displayed. The long string of the error code is cart_id. How can I change it? models.py class Payment(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) card_number = models.IntegerField() validity = models.IntegerField() cvc = models.IntegerField() card_password = models.IntegerField() def __str__(self): return '{0} {1}'.format(self.cart, self.card_number) urls.py urlpatterns = [ path('add/<int:pk>/', views.add_cart, name='add_cart'), path('', views.cart_detail, name='cart_detail'), path('remove/<int:pk>/', views.cart_remove, name='cart_remove'), path('full_remove/<int:pk>/', views.full_remove, name='full_remove'), path('payment_charge/', views.payment_charge, name='payment_charge'), ] view.py def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def payment_charge(request): if request.method == "POST": form = PaymentForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.cart_id = _cart_id(request) post.save() return redirect('cart:cart_detail') else: form = PaymentForm() context = { 'form' : form } return render(request, 'cart/payment_form.html', context) forms.py class PaymentForm(forms.ModelForm): class Meta: model = Payment fields = ('card_number','validity','cvc','card_password') base.html <div class="mx-auto"> <a href="{% url 'cart:payment_charge' %}" type="button" class="btn btn-outline-dark my_custom_button"> Continue Shopping </a> </div> payment_form.html <form action="" method="POST"> {% csrf_token %} <table> {{form.as_table}} </table> <input type="submit" value="제출"> </form> -
Multiple database support for django-elasticsearch-dsl
We have a system where we are using a multi-database setup. E.g Multiple companies will have their own database. Django database setup example: { "default":{ "ENGINE":"django.db.backends.postgresql", "NAME":"default" }, "db_2":{ "ENGINE":"django.db.backends.postgresql", "NAME":"db_2" } } Also, we have decided to use Elasticsearch with Django Elasticsearch DSL. But we wouldn't be able to index like our relational databases. When I try to rebuild the index Django Elasticsearch DSL trying to index using only the default database. How I can route different databases on a different index or something same scenario like our relational database. -
Create complex order with Stripe payment
I am trying to allow my users to pay for their booking (for an event) on my website using Stripe. I've got most of the processing working well but I don't know how to connect the response I get from Stripe which indicates that the payment has been successful to my database so that it knows all the details required to make the booking. In the standard situation of "buying X number of products", I know that I can create an order on the server which contains those details. Then I can put that order ID into the Stripe request and I can use that when the payment is successful to go and fulfil that order. But in my case, I have to accept a load more information than that. Each booking can have multiple attendees attached to it - each attendee will have a name and load more information about them which needs to be used when the booking is created. Is the only way to do this to add ALL of this attendee information in to the request to Stripe so that it can be used when the payment succeeds? Or is there another way? If it helps … -
How can I concadenate 2 queryset in django to write in xlwt excel file?
I have 2 models class, i have to concadenate these qeurysetobjects and write one excel page. how can i do it ? I use whis code but it doesnt work def export_excel(request): response =HttpResponse(content_type = 'application/ms-excel') response['Content-Disposition'] = 'filename="persondatas.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('AllinOne') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['name', 'fulname', 'id', 'gender', 'country', 'birthdate', 'birthpace', 'departament', 'feature'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows =Person.objects.values_list('name', 'lastname', 'selfid', 'gender', 'country', 'dateofbirth', 'placeofbirth') jobs = Enrollment.objects.values_list('departament', 'feature') querysets = [rows, jobs] rows = list(chain(*querysets)) for row in rows: row_num+=1 for col_num in range(len(row)): ws.write(row_num, col_num, str(row[col_num]), font_style) wb.save(response) -
Writing warmup-script to manage deployment to production with database migrations in Azure web-application with slots for Django application
I have a Django app that I'm planning on hosting via Azure web-apps. I've seen that Azure offer the option to deploy via different deployment-slots, and would like to incorporate this into my deployment process, as this is by far the most stressful event - deploying to production for my client. However, I'm a bit unsure on how to do this when I'm going to do migrations to the production database. From my understanding you can compose a "warmup-script" to handle this sorts of things, but I'm not sure on how to actually write it. I want the startup-script to make the migrations, if they are successful, everything is fine and dandy and the slot 2 should be swapped to the production slot. However, if the migrations fail, I want to roll-back to the previous migrations and not do the swap for the code-base with slot 2 and production, but instead be able to look at the logs and see what was resulting in that the migration failed. By this process, the downtime on the client-side would be minimised, as I only would stop the server for "maintenance" for a short while, when trying to do the migrations to the … -
Google Cloud Debugger on Cloud Run Django "No code found at line..."
When trying to debug a Cloud Run Django application (Python 3.9) I get the No code found at line 30 in /app/djangotest/urls.py error. I looked at the docker image and the file seems to be in the right place, with debuggable code at the correct location: 29 class UserViewSet(viewsets.ModelViewSet): 30 queryset = User.objects.all() 31 serializer_class = UserSerializer This seems to be similar to: Flask: google cloud debugger snapshot reports "No code found at line...", python on managed cloud run FastAPI: Google Cloud Debugger snapshot reports error “No code found at line …” As it seems that there are no answers and no issue has been opened yet, I opened one here: https://issuetracker.google.com/issues/207626319 -
How to edit many objects of one class in Table View?
I want to prepare one form to update each object of one instance. It' easy in php but I want to do that in Django, but I have started learning and I realy dont know how to do that. It would be perfect, if I could manage to do that with based class like UpdateView. I In HTML it should look like this: -
What is the correct way to use multiprocessing and Django transaction blocks?
How can I use Multiprocessing in Python/Django management commands or views with transaction blocks. My intention is that in the view, for example, there's a lot of data being created but if any exception occur, I would like to rollback the transaction and nothing gets created. On the other hand, sometimes we create management commands-like scripts to run in migrations to fix data and we would also like to use multiprocessing to speed it up but with the option to do a dry-run of the script, so the transaction is rolled back. I can't use bulk_create in these situations because the models I'm interested in modifying/creating are inherited models and bulk create does not apply to these type of models. By wrapping either the handle(), some_func or the with Pool... block with transactions I get an error: django.db.utils.InterfaceError: connection already closed from multiprocessing import cpu_count, Pool def worker_init(): connection.close() class Command(BaseCommand): # arguments here... def handle(self, *args, **options): self.commit = options['commit'] try: # Wrapping the core of the script in a transaction block does not work # with transaction.atomic: items = [...] results = [] with Pool(processes=cpu_count(), initializer=worker_init) as pool: for result in pool.imap_unordered(some_func, items): results.extend(result) if not self.commit: raise … -
No version of django installs on a new win10 pc with a recent python version
I have a new Win 10 pro 64 bit machine with Python 3.8.8 installed, but no matter which Django I try to install, I always get the following errors: For the past two days, I have tried every tip and suggestion and proposed solution in the forum posts and blogs that I could find, to no avail... What could possibly be the reason? How do I install Django? -
docker- django build image, but don't run in linux server
in my ubuntu computer, I can build image and run with no error but in linux server, when running, it stop at showing notification in red circle, than it is off but doesn't showing any error I try building docker image with a simple django project (https://www.section.io/engineering-education/django-docker/) and it runs without error in linux server any idea to resolve this? My dockerfile: FROM ubuntu:20.04 RUN apt-get update \ && apt-get install -y python3-pip python3-dev\ && cd /usr/local/bin \ && ln -s /usr/bin/python3 python \ && pip3 install --upgrade pip ############################################################################################## #FROM python:3.8.3-alpine #FROM python:3.6.1-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies #RUN python3 -m pip install --ignore-installed --upgrade "Download URL" RUN python3 -m pip install --upgrade pip COPY ./requirements.txt /usr/src/app RUN python3 -m pip install -r requirements.txt #RUN python3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow_cpu-2.7.0-cp38-cp38-manylinux2010_x86_64.whl # copy project COPY . /usr/src/app EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] -
How to conver this PHP sql query to Django queryset?
How to convert this php sql to django query set? I've been stuck for 3 days. Please help me -
Video recorded through OpenCV not loading on html
I am recording videos with the help of OpenCV. Now after the video is saved, I am trying to load that video into HTML, with the help of video and iframe tags, but it is not loading in either of the tags. I have saved the video in .avi/.mp4 format. Locally in VLC the videos are playing fine, but are not loading in HTML. For recording video with openCV, I have referred to : https://www.dynamsoft.com/codepool/web-camera-recorder-oepncv-flask.html. -
Who to post multiple options to database in Django?
I have a table that contains items and another table with a foreign key referenced with that table to check the post operation. A user adds an item to the cart. I am unable to find the way to post all the <options> in <select>. My problem statement is to send all the add <options> to my table that contains a foreign key. Table that contain items: Table in which I want to post data: models.py: from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields.related import ForeignKey from datetime import datetime, date from django.core.validators import MaxValueValidator, MinValueValidator import uuid # Create your models here. class Tbl_Category(models.Model): cat_Id = models.AutoField(primary_key=True) cat_Name = models.CharField(max_length=20, unique=True) def __str__(self): return self.cat_Name # def __str__(self): # return [self.cat_Id, self.cat_Name] class Tbl_Item(models.Model): item_Id = models.AutoField(primary_key=True) item_Name = models.CharField(max_length=30, unique=True) cat_Idf = models.ForeignKey(Tbl_Category,on_delete=models.CASCADE) item_Price = models.IntegerField() def __str__(self): return self.item_Id class Tbl_postchk(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) itmid = models.ForeignKey(Tbl_Item, on_delete=CASCADE) HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" href="{% static 'css.css' %}"> <title>DATA COLLECTION</title> </head> <body> <div class="container"> <div class="order-screen"> <div class="element"> <label for="coffee-tea">Coffee-Tea</label> <select name="coffee-tea" id="coffee-tea" class="s"> {% for opt in all_A … -
django form gettting error while posting data
form.py while creating new data based on city getting error(\forms.py", line 709, in init super(IncentiveForm,self).init(*args,**kwargs) TypeError: init() got an unexpected keyword argument 'city_id') class IncentiveForm(forms.ModelForm): city_id = CityModelChoiceField( required=False, queryset=City.objects.all(), label='City', widget=Select2Widget) class Meta: model=Incentive fields= ['start_date','end_date','no_of_trips','incentive'] def __init__(self,*args,**kwargs): self.request = kwargs.pop('request', None) super(IncentiveForm,self).__init__(*args,**kwargs) views.py def incentive_form(request,city_id=None): city = City.objects.get(pk=city_id) create=Incentive.objects.filter(city_id=city_id) if request.method == 'POST': form=IncentiveForm(request.POST,city_id=city_id) if form.is_valid(): start_date=form.cleaned_data['start_date'] end_date=form.cleaned_data['end_date'] no_of_trips=form.cleaned_data['no_of_trips'] incentive=form.cleaned_data['incentive'] if create is not None: create.start_date=start_date create.end_date=end_date create.no_of_trips=no_of_trips create.incentive=incentive create.city_id=city_id create.save() messages.success(request,'Incentive data created successfully!') else: form=IncentiveForm() context={ 'menu_incentive': 'active', 'submenu_incentive_list': 'active', 'city_id': city_id, 'city': city, 'form':form, } return render(request,"hiringprocess/incentive.html",context=context) -
How to change table data with Django and Ajax
I have a pandas dataframe that I am displaying in a Django Template as follows views.py def display(request): if request.method == 'POST': temp_df_path = './temp_match.csv' option = 'all' animals_data = helper(temp_df_path, options=option) json_records = animals_data.reset_index().to_json(orient='records') data = [] data = json.loads(json_records) context = {'d': data, 'data_columns': animals_data.columns} return render(request, 'results.html', context=context) Here I am displaying a DataFrame filtered using the helper function. In the template I have a set of radio buttons with which I can change the option variable. Here is my template <div class="container center"> <div class="table_options action_panel_centered"> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" value="option3" checked> <label class="form-check-label" for="inlineRadio3">Show all animals</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1"> <label class="form-check-label" for="inlineRadio1">Show only carnivores</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2"> <label class="form-check-label" for="inlineRadio2">Show only herbivores</label> </div> </div> </div> <div class="container-fluid root center"> <div class="table_container"> <table class="table table-hover" id='results_table'> <tr> <th class="index_th">#</th> {% for col in data_columns %} <th>{{col}}</th> {% endfor %} <th class='action_cell'>Actions</th> </tr> {% if d %} {% for i in d %} <tr> <th scope="row"> {{forloop.counter}} </th> ... </table> </div> </div> I want to change the content using Ajax. How do I do that? I have an Ajax … -
form.html in Django CreateView
Below is my code. class ArticleCreateView(OwnerCreateView): model = Article fields = ['title', 'text'] class OwnerCreateView(LoginRequiredMixin, CreateView): """ Sub-class of the CreateView to automatically pass the Request to the Form and add the owner to the saved object. """ # Saves the form instance, sets the current object for the view, and redirects to get_success_url(). def form_valid(self, form): print('form_valid called') object = form.save(commit=False) object.owner = self.request.user object.save() return super(OwnerCreateView, self).form_valid(form) In my /home/JongRok/dj4e-samples/myarts/templates/myarts I have acticle_form.html {% extends "base_bootstrap.html" %} {% load crispy_forms_tags %} {% block content %} <p> <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <input type="submit" value="Submit"> <input type="submit" value="Cancel" onclick="window.location.href='{% url 'myarts:all' %}';return false;"> </form> </p> {% endblock %} I don't understand How Django CreateView find form. I don't put form in ArticleCreateView and I don't have form.py. How Django CreateView find it self has a model form?? -
auth_middleware.<locals>.middleware() got an unexpected keyword argument 'user_id'
I am trying to apply my custom auth middleware in the url path that has id . But getting this error. from .views import Profile app_name = 'account' from employer.middlewares.auth import auth_middleware urlpatterns =[ path('dashboard/pages-profile/<int:user_id>', auth_middleware(Profile.as_view()), name='profile'), ] And my auth middleware is this: from django.http import HttpResponseRedirect def auth_middleware(get_response): def middleware(request): return_url = request.META['PATH_INFO'] if not request.session.get('user_id'): return HttpResponseRedirect(f'{reverse("account:login")}?return_url={return_url}') response = get_response(request) return response return middleware -
How to convert doc to pdf supported by all the operating systems using python
I want to convert my word doc file to pdf using Python. Most of the modules I tried creates pdf on win and mac machines but not on linux. What module should I use which will convert doc to pdf supported on all the platforms? -
django app static files are not loading on shared hosting (cpanel)
static files or my django project are not working when i try to access via domain name I'm using Linux based shared hosting cpanel. Here is the settings.py for static files. I run collectstatic command and now all site statics are collect in home/username/project_static but those files are not working on my site. Please help me in this regard or guide me correct process of static files for production STATIC_URL = 'domain.net' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = 'home/username/project_static/' SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) MEDIA_URL = '' STATICFILES_DIRS =[ BASE_DIR/ 'static', "home/username/project_static/", ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')