Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For loop in for loop Django template
i want to set up 'send request/cancel request' function in template. The problem with displaying, if request exist 'cancel', if not 'send'. I don't get how to correctly get request and compare 'profile' with 'to_profile'. Now i got stuck with 'for' loop in 'for' loop... \ In template it shows 3 buttons( the same quantity requests from this event ) for one profile enter image description here Could you give me some tips how to fix, avoid, or do in another way please. Thank you! request model class EventInviteRequest(models.Model): from_event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='from_event', null=True) to_profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='to_profile', null=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"From {self.from_event} to {self.to_profile}" view i try to use def get_list_of_all_users(request, event_id): """Get list of all users""" event = Event.objects.get(id=event_id) profiles = Profile.objects.all() requests = EventInviteRequest.objects.filter(from_event=event) context = {'profiles': profiles, 'event': event, 'requests': requests} return render(request, 'events/invite_all_profiles_to_event.html', context) template {% extends 'base.html' %} {% load static %} {% block title %}All profiles{% endblock %} {% block content %} <h3>All profiles:</h3> {% for profile in profiles %} <div style="display: inline-block; margin-right: 10px; text-align: center;"> <a href="{% url 'account:profile' profile.id %}"> {% if profile.photo %} <img src="{{ profile.photo.url }}" width="70" height="100"> {% else %} <img … -
How to i18n translate url patterns Django 3.2
I'm stuck in url translation while adding language support to my app. Although I have applied the ones written in the documents one by one, I still have not solved this problem. Can you help me see where I went wrong? The problem is exactly that my application will have two languages (TR and EN) 12.0.0.0.1/tr-url when the application is in tr while in english It's hard to go to 12.0.0.0.1/en/en-url addresses. However, when switching from Turkish to English, the urls are as follows: en: 127.0.0.1/en/en-url en: 127.0.0.1/en/en-url Similarly, when switching from English to Turkish, en: 127.0.0.1/en/en-url en: 127.0.0.1/en/en-url is in the form. If anyone knows how to switch languages, I'd be very happy. from django.utils.translation import gettext_lazy as _ from django.conf.urls.i18n import i18n_patterns from New import views as new_views from Home import views as home_views from Home.views import change_language urlpatterns = [ path('admin/', admin.site.urls), path('change_language/', change_language, name='change_language'), path('i18n/', include('django.conf.urls.i18n')), ] home_patterns =([path('', home_views.Index, name="index"), path(_('sistem-cozumumuz/'), home_views.Solution, name='solution'), path(_('teklif-isteyin/'), home_views.OfferRequests, name="offer-request"), path(_('gizlilik-politikasi/'), home_views.PrivacyPolicy, name='policy'), path(_('iletisim/'), home_views.Contact, name='contact'), ]) news_patterns =([path('', new_views.Index, name="index"), path(_('referanslar/'), new_views.References, name="reference"), path(_('yorumlar/'), new_views.Comments, name="event"), path(_('basinda-biz/'),new_views.News,name="new"), path(_('dokumanlar/'), new_views.Downloads, name="download"), path(_('<slug:slug>/'),new_views.NewDetails,name="new-detail"), path(_('yorumlar/<slug:slug>/'),new_views.CommentDetails,name="comment-detail"), path(_('referanslar/<slug:slug>/'),new_views.ReferenceDetails,name="reference-detail"), ]) urlpatterns += i18n_patterns( path('', include(home_patterns),name="Home"), path(_('haberler/'), include(news_patterns), name="New"), path('change_language/', change_language, name='change_language'), path('i18n/', include('django.conf.urls.i18n')), prefix_default_language=False,) … -
how to set url like /<int:post_id>/apply?
url urlpatterns = [ path('company', views.CompanyAdList, name='CompanyAdList'), path('company/write', views.CompanyAdWrite, name='CompanyAdWrite'), path('company/<int:post_id>', views.CompanyAdDetail, name='CompanyAdDetail'), path('company/<int:post_id>/apply', views.CompanyAdApply, name='CompanyAdApply'), ] js in /company/1 function apply_request() { var queryString = $("form[name=applyForm]").serialize(); $.ajax({ type : 'post', url : "{% url 'CompanyAdApply' %}", data : queryString, dataType : 'json', success: function(data){ if(data.result==200){ openPopup("alert", data.result_text); }else{ openPopup("alert", data.result_text); } return; }, error: function (request, status, error){ var msg = "ERROR : " + request.status + "<br>" msg += + "content: " + request.responseText + "<br>" + error; console.log(msg); } }); } I want to make form in /company/1 to /company/1/apply how to do this? when I do what I think. showed error. ['company/(?P<post_id>[0-9]+)/apply$'] -
INNER JOIN in django orm
I have two tables that only contain the same product ids and they didnt have foreigh keys. So question is about how i can filter them both in query by id. In SQL i want to do something like this SELECT Url FROM pricehistory p INNER JOIN product d ON p.ProductID = d.ProductID -
Python is running perfectly on aws but not get any result showing site can't reachable . Port is working fine as we tested a nodejs
The code is working fine in local and we are using ec2 instance the server database is working fine the port also because I just run a node project on that port which is working and i can fetch data from server db. -
Creating a GIN index with a function specified in Django
I have created a model in Django. class MyModel(models.Model): features = TextField(blank=True, default='') There are several possible ways to store the data in the feature field. Some examples below. feature1;feature2 feature1, feature2 feature1,feature2 And so on. I need to create a GIN index for that field. I would probably do it in postgreSQL in the following way CREATE INDEX features_search_idx ON "mymodel" USING gin (regexp_split_to_array("mymodel"."features", E'[,;\\s]+')); Would it be possible to do the same thing by a migration? -
Define model and form through url dispatcher slug parameters
I have the code in urls.py: from django.urls import path from tables.models import subcomponentsTable, rawMaterialsTable from tables.forms import subcomponentsTableForm, rawMaterialsTableForm urlpatterns = [path('newEquipment', views.createTableView.as_view(model=subcomponentsTable,form_class=subcomponentsTableForm), name='newEquipment'), path('newRawMaterial', views.createTableView.as_view(model=rawMaterialsTable, form_class=rawMaterialsTableForm),name='newRawMaterial'), ... etc. and i would like to refractor it as follows to make it reusable for different models and forms: urlpatterns = [path('new/<slug:tableType>', views.createTableView.as_view(), name='newInstance'),... views.py: class createTableView(LoginRequiredMixin, CreateView): template_name = 'tables/createTableTemplate.html' what method in createTableView I should overload, so I could calculate appropriate form and model from slug:tableType, and use it in my view? To do it properly? Will be there any difference with UpdateView and DeleteView? Thank you in advance! -
create() takes 1 positional argument but 2 were given. Django rest framework,. How to slove it?
I am new to Django restframework I want to register a new student to school but it does not work. I have tried many solutions . what I got is:create() takes 1 positional argument but 2 were given when I try to post. I am not sure if my code in the viewset correct. Can someone help me? In my serializers.py: class StudentSerializer(serializers.Serializer): class Meta: model = Student fields = ['first_name'] class SchoolSerializer(serializers.Serializer): is_existing_student = = serializers.BooleanField() student = StudentSerializer(many=True) class Meta: model = School fields = ['is_existing_student', 'name', 'city', 'street', 'student'] def create(self, **validated_data): student_data = validated_data.pop('student') school_instance = School.objects.create(**validated_data) for student_data in student_data: Student.objects.create(school_instance=school_instance, **student_data) return school_instance In my views.py: class SchoolViewSet(mixins.CreateModelMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet): serializer_class = SchoolSerializer queryset = School.objects.all() @action(detail=True, methods=['POST']) def school(self, request, *args, **kwargs): school = self.get_object() if serializer.is_valid(): School.create(school=school, name='name', street='street', city='city', student='student') school.save() else: return Response(status=status.HTTP_204_NO_CONTENT) In my url: router.register(r'register', SchoolViewSet) -
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