Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am unable to install django from command prompt. I am attaching the error. please show the path to me
C:\Users\utkarsh>pip install django Fatal error in launcher: Unable to create process using '"c:\users\utkarsh\appdata\local\programs\python\python38-32\python.exe" "C:\Users\utkarsh\AppData\Local\Programs\Python\Python38-32\Scripts\pip.exe" install django': The system cannot find the file specified. -
Django mptt model not linking to parent
Hello I am in the process of implementing a hierarchical location model. I have also created a form to be able to add locations while not using the admin interface. Tp do this I am using mptt's TreeNoeChoiceField. However when I select the correct parent and then submit the new location's parent defaults to none. I am unsure why this is happening and can't seem to find anyone else having similar issues. forms.py class Location Form(forms.ModelForm): parent = TreeNodeChoiceField(queryset=Location.objects.all()) class Meta: model = Location fields = ("name", "description", "directions", "elevation", "latitude", "longitude") -
How to add condition on Django model foreign key?
I am new in Django, would you please help me, I have two models, by name of Continent and Country, in the Country form I want to only display the Continents in the dropdown list which their status is true? models from django.db import models from smart_selects.db_fields import GroupedForeignKey, ChainedForeignKey class Continent(models.Model): name = models.CharField(max_length=255) status=models.BooleanField(default=True) def __str__(self): return self.name class Country(models.Model): continent = models.ForeignKey(Continent, null=True, on_delete=models.SET_NULL) status=models.BooleanField(default=True) name = models.CharField(max_length=255) def __str__(self): return self.name forms class FormContinent(ModelForm): class Meta: model = Continent fields = '__all__' class FormCountry(ModelForm): class Meta: model = Country fields = '__all__' views def continent(request): form = FormContinent() if request.method == 'POST': form = FormContinent(request.POST) form.is_valid() form.save() return redirect('/continent') else: context = {'form': form} return render(request, 'continent.html', context) def country(request): form = FormCountry() if request.method == 'POST': form = FormCountry(request.POST) form.is_valid() form.save() return redirect('/country') else: context = {'form': form} return render(request, 'country.html', context) -
Django-channels: Send message after database update
I'm using django-channels to provide a chat app on websockets. I store messages in a database. I would like to be able to send new messages to the client as soon as they get written to the database. How can I do that? I guess I need to make a WebSocketConstructor that will recieve a post_save signal, but I don't know exactly how to send signals to django-channels consumers. -
Stream PDF file from http response directly to client with Python requests library using client certificate
I'm making a request to an endpoint that returns a PDF as streamable binary. This endpoint uses mutual TLS authentication so when I hit the endpoint I must send a client certificate. To achieve this I am using https://pypi.org/project/requests-pkcs12/ which supports the Python requests library. I would like to download this PDF from the client. Ideally when the end user clicks 'download' it hits the endpoint and directly streams the data and downloads it. I am struggling to do this in one single step. Currently what I'm doing is downloading the PDF to a file, then sending this file back to the client. Writing to the file is slow and I'd like to avoid the download-to-file step and simply send a streaming response back somehow. Is there a way to stream this directly using Python's Request? #hit the mutual tls authenticated endpoint response = post(f'{url}, stream=True, pkcs12_filename=client_certificate_path, pkcs12_password=client_certificate_passphrase) #Write the returned data to a file with open('/tmp/newfile.pdf', 'wb') as f: f.write(response.content) #Send the file back to client with Django's FileResponse return FileResponse(open('/tmp/newfile.pdf', 'rb')) While I am using Django which seems to handle this problem nicely with StreamingHttpResponse, I was unable to get this working as it doesn't allow me to … -
CRUD not able to displaly model instances in template to update
I have an app project. I am able to save instances to the model in the database no problem. But I cannot pull in the instance by pk to the html form to edit and update. please see setup below can anyone provide any guidence or help, as to why this is not happening and how I can resolve? views.py def edit_properties(request, id): properties = Properties.objects.get(pk=id) context = { 'properties': properties, 'values': properties, } if request.method == 'GET': return render(request, 'sub/edit_properties.html', context) -
Regex for match url in Django
I'm trying to match this url with a regexp in django/python (old liferay urls) http://127.0.0.1:8080/documents/34105/35593/prova+(1)+(1).jpg/da459266-ab36-faf1-726d-fc989385b0bd but I cannot decode the filename... This is the regexp that I use: documents/(?P<repo>[0-9]{5,10})/(?P<folder>[0-9]{5,10})/(?P<filename>[])/(?P<uuid>[\w-]+) This is the Pythex link -
How does form_valid work in django? How does it compare to save()?
The describtion of this in docs seems very sparse and unclear to me I am asking here. So what is exactly doing the form_valid method here? From what I understand, it gets triggered with POST method and it is kinda calling save() in the last line. form.instance.entry_author=self.request.user in this line I understand that we are setting the current user to be the author but I dont understand why form referances to instance and also where did the form get from? I suppose its in-built in the form-valid function? class CreateEntryView(CreateView): model = Entry template_name='entries/create_entry.html' fields = ['entry_title','entry_text'] def form_valid(self, form): form.instance.entry_author=self.request.user return super().form_valid(form) -
Django recursive serializing
Let's say I have models like this: class A(models.Model): ...some fields here class B(models.Model): ...some fields here a = models.ForeignKey(A, on_delete=CASCADE) class C(models.Model): ...some fields here b = models.ForeignKey(B, on_delete=CASCADE) ... And I want my API endpoint to return something like this { ...some fields here b: [ { ...some field here c: [{...}, {...} ...] }, { ...some field here c: [{...}, {...} ...] } ... ] } I know I can do something like this: class Bserializer(serializers.ModelSerializer): c = Cserializer(source="c_set", many=True, read_only=True,) class Meta: model = B fields = [...some fields, "c"] class Aserializer(serializers.ModelSerializer): b = Bserializer(source="b_set", many=True, read_only=True,) class Meta: model = A fields = [...some fields, "b"] But if this goes deeper or/and models have more foreign keys it starts to become really complicated. Is there a way to add recursively all instances referencing the model. -
Displaying a ChartJs chart within a bootstrap-modal in Django
I want to display a ChartJs chart within a modal.When I use static datas it is okay and the chart is displayed but by using ajax to get an specific object's datas, it shows just an empty modal. Views.py def getChart(request): if request.method == "GET" and request.is_ajax(): meterId = request.GET.get("meterId") try: meter = Meter.objects.get(meter_id=meterId) except: return JsonResponse({"success": False}, status=400) context = Report.objects.filter(meter=meter) return JsonResponse(context,safe=False) return JsonResponse({"success": False}, status=400) HTML $(".chart").click(function(e){ e.preventDefault(); var meterId = name; var data = {meterId}; $.ajax({ type : 'GET', url : "{% url 'get_chart' %}", data : data , headers: { 'X-CSRF-TOKEN': $("meta[name='csrf-token']").attr('content') }, success : function(response){ console.log(response) var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for each in power_data %}'{{ each.time }}',{% endfor %}], datasets: [{ label: "Power Consumption", data: [{% for each in power_data %}'{{ each.power }}',{% endfor %}], backgroundColor: [ 'rgba(54, 162, 235, 0.2)' ], borderWidth: 1 }] } }) }, error : function(e){ console.log(e) } }) }) I checked all parts so many times and also ajax call is doing well and there is no errors.Any ideas? Kind regards. -
Docker-compose: db connection from web container to neo4j container using bolt
I'm working on django project with neo4j db using neomodel and django-neomodel. I'm trying to containerize it using docker-compose. when I build the images everything seems fine, but any connection from web container to db using bolt is refused. although I can access the neo4j db from the browser on http, and even from local machine on bolt. this is the error I get: neo4j.exceptions.ServiceUnavailable: Failed to establish connection to ('127.0.0.1', 7688) (reason 111) I'm using the following configs: <pre>Django == 3.1.1 neo4j==4.1.0 neomodel==3.3.0 neobolt==1.7.17 </pre> this is my docker-compose file: version: '3' services: backend: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" depends_on: - neo4j_db networks: - mynetwork links: - neo4j_db neo4j_db: image: neo4j:3.5.17-enterprise ports: - "7474:7474" - "7688:7687" expose: - 7474 - 7687 volumes: - ./db/dbms:/data/dbms environment: - NEO4J_ACCEPT_LICENSE_AGREEMENT=yes - dbms.connector.bolt.listen_address=:7688 - dbms.connector.bolt.advertised_address=:7688 networks: - mynetwork networks: mynetwork: driver: bridge and here's connection configs in django settings: NEOMODEL_NEO4J_BOLT_URL = os.environ.get('NEO4J_BOLT_URL', 'bolt://neo4j:pass@123@127.0.0.1:7688') Thanks in advance.. -
Is there a way to call a function on a model field?
I have a model which has a FileField and I now need to call an API to convert the file. Not sure on how to implement the function and also, how to show the file to the user after it's converted. I was thinking of calling the function on each model object and then just changing the url in the model to the new file. Is there a way to call the function before the file is saved to the DB to make things easier? I'm not sure if this is possible because I'm guessing that the file must be saved before it's converted. -
Django views in modules in "views" package, call by module name - Namespacing problem
My views.py is getting large, and I'd like to organize different parts of my django website by functionality. I envision something like this: urls.py views ├── __init__.py ├── editor.py └── display.py In my urls.py I'd like to have seperated namespaces like this: url(r'^display_some_post/$', views.display.post, name="display_post"), url(r'^edit_some_post/$', views.editor.post, name="editor_post"), Note that every view is called by it's module name. But I can't quite figure out the correct way to set up init.py and / or import the modules into the urls.py. Any help is appreciated! -
Django with Angular - relative paths when font and back have different url
After two days I failed to setup (any form of) webpack working with django3 in the back and angular10 in the front, so I decided to just use gulp to start ng serve for frontend and python manage.py runserver for backend. I am new to this, so this is probably very stupid but really two days is a lot of time to give on setup and get nothing back .. Currently I am trying to call an API on the django server that is on http://127.0.0.1:8000 while ng serve is running on http://127.0.0.0:4200 @Injectable() export class EchoService { constructor(private httpClient: HttpClient) {} public makeCall(): Observable<any> { return this.httpClient.get<any>( 'http://127.0.0.1:8000/my-api/' ); } } ''' Is there a better way how to do this in Angular without using "http://127.0.0.1:8000" in every component call I do? How can I make it as close as possible to relative paths, that will be used in the prod version of this (for prod I will just put the bundles manually in the html, but I can not do that manually for dev) -
(1054, "Unknown column 'leçon_lesson.subject_id' in 'field list'")
i have been making some changes on my model 'lesson' and suddenly i couldn't use my model on my django website with MySql data base. when i try to use it on a view i got this error (1054, "Unknown column 'leçon_lesson.subject_id' in 'field list'") the commands makemigrations and migrate works fine but this error occurs when using the model only this is the model.py from django.db import models from .validators import * from scolarité.models.level import Level from scolarité.models.subject import Subject class Lesson(models.Model): level = models.ForeignKey(Level,on_delete=models.CASCADE) subject = models.ForeignKey(Subject,on_delete=models.CASCADE) chapiter = models.CharField(max_length=200) lesson = models.CharField(max_length=200) skill = models.CharField(max_length=200) vacations = models.IntegerField() link = models.URLField(max_length=700,null=True,blank=True) remarques = models.TextField(null=True,blank=True) order = models.IntegerField() created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now=True) state = models.BooleanField(default=False) def __str__(self): return self.lesson views.py #=========================== view lessons ===================== @login_required #use this to make the view accessible for logged in users only def view_lessons_list(request,subject_id): request.session['subject_id']= subject_id #assign subject id value to session level = Level.objects.get(id=request.session['level_id']) #getting the level model subject = Subject.objects.get(id=request.session['subject_id']) #getting the subject model lessons = Lesson.objects.filter(subject=subject ,level=level) #filtering the lesson based on the chosen level and subject context={'lessons':lessons,} return render(request,'leçon/view_lessons_list.html',context) the traceback Traceback (most recent call last): File "C:\Users\YAHYA-PC\Desktop\CourseCode\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File … -
Comment section in django blog won't show up under each individual post?
The comment successfully saves in the django admin but won't show up on the actual site. Here is the comment model: class comment(models.Model): linkedpost = models.ForeignKey(Post, related_name="postcomments", on_delete=models.CASCADE) commentauthor = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) This the html code for the blog home. the post for loop goes through all the post objects and prints them out. I created a comment loop to loop through all the comments for the linked post and print. Is the problem in my html code? {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> <div> <h2>Comments</h2> {% for cmnts in linkedpost.postcomments %} #<a class="mr-2" href="{% url 'user-posts' cmnts.author.username %}">{{ cmnts.commentauthor }}</a> <small class="text-muted">{{ cmnts.date_posted|date:"F d, Y" }}</small> <p class="article-content">{{ cmnts.body }}</p> {% endfor %} </div> </div> </article> {% endfor %} -
How to set a maximum no. for a Coupon can be used in Django Project
I have set a Coupon Payment System for my E-commerce project but I want to set a maximum no. of usage for this coupon for maximum 10 times. How do I do that? Here is the models.py class Coupon(models.Model): code = models.CharField(max_length=15,unique=True) amount = models.DecimalField(decimal_places=2, max_digits=100) valid_from = models.DateTimeField(blank=True, null=True) valid_to = models.DateTimeField(blank=True, null=True) active = models.BooleanField(default=True) def __str__(self): return self.code Here is the views.py class AddCouponView(View): def post(self, *args, **kwargs): now = timezone.now() form = CouponForm(self.request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = Order.objects.get( user=self.request.user, ordered=False) coupon_qs = Coupon.objects.filter(code__iexact=code, valid_from__lte=now, valid_to__gte=now,active=True) order_coupon = Order.objects.filter(coupon=coupon_qs.first(), user=self.request.user) if order_coupon: messages.error(self.request, "You can't use same coupon again") return redirect('core:checkout') if coupon_qs: order.coupon = coupon_qs[0] order.save() messages.success(self.request, "Successfully added coupon") return redirect('core:checkout') else: messages.error(self.request, "Coupon Does not Exists") return redirect('core:checkout') except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect('core:checkout') Here is the forms.py class CouponForm(forms.Form): code = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Promo code', 'aria-label': "Recipient's username", 'aria-describedby': "basic-addon2" })) -
Authenticate function not working in Django
I am trying to authenticate in Django using authenticate but my code is not running and showing errors. My code: def post(self, request): data = request.data username = data.get('name', '') password = data.get('password', '') if not username or not password: return Response({'ERROR': 'Please provide both username and password'}, status=status.HTTP_400_BAD_REQUEST) user = authenticate(request, username=username, password=password) if not user: return Response({'Error': 'Invalid name/Password'}) login(request,user) What's wrong in my code? I am getting both username and password from json but it's failing to validate. -
Django: FileField' object has no attribute 'attrs' in class Meta
I have a simple problem. Inside a modelForm, in my Meta class, inside widgets={} i have specified: 'video' : forms.FileField(allow_empty_file=True) however django complains that 'FileField' object has no attribute 'attrs'. What could be the issue -
Form and inline-form at the same time in Django UpdateView
I have the following models: class Product(models.Model): name = models.CharField(max_length=100) class ProductList(models.Model): name = models.CharField(max_length=100) users = models.ManyToManyField(User) products = models.ManyToManyField(Product, through='ProductAssignment') class ProductAssignment(models.Model): count = models.PositiveIntegerField() product_list = models.ForeignKey(ProductList, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) I have created an admin page for it with class ProductAssignmentInlineAdmin(admin.TabularInline): model = ProductAssignment fields = ('count', 'product') extra = 2 class ProductListAdmin(admin.ModelAdmin): model = ProductList inlines = (ProductAssignmentInlineAdmin,) admin.site.register(ProductList, ProductListAdmin) Now I want to allow the user to edit the ProductList the same way. Therefore, I have created an UpdateView class ProductListUpdate(LoginRequiredMixin, UpdateView): model = ProductList fields = '__all__' but it only shows the fields for the ProductList and not the m2m values. I have replaced fields with form_class: ProductAssignmentForm = inlineformset_factory(ProductList, ProductAssignment, fields=('count', 'product'), extra=2) class ProductListUpdate(LoginRequiredMixin, UpdateView): model = ProductList form_class = ProductAssignmentForm and this only shows the m2m section of the form. How can I show both (the ProductList properties AND the m2m inline properties from the ProductAssignment model)? -
Starting Django's runserver in a Docker container through docker-compose
I would like to have Django's runserver command running when I call docker-compose up Here is what I tried, firstly, my image is starting from a Python image customized following this dockerfile: # Dockerfile FROM python:3.8 MAINTAINER geoffroy # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Ports exposure EXPOSE 8000 VOLUME /data # Install dependancies RUN apt-get update && apt-get install -y \ vim \ git \ && rm -rf /var/lib/apt/lists/* # Setup python dependancies RUN git clone https://github.com/blondelg/auto.git WORKDIR /auto RUN cd /auto RUN pip install --no-cache-dir -r requirements.txt # Build the secret key generator RUN echo "import random" > generate_key.py RUN echo "print(''.join(random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@$^&*(-_=+)') for i in range(50)))" >> generate_key.py # Setup environment configuration RUN cp auto/config_sample.ini auto/config.ini RUN sed -i "s/SECRET_KEY_PATTERN/$(python generate_key.py)/gI" auto/config.ini RUN sed -i "s/django.db.backends.sqlite3/django.db.backends.mysql/gI" auto/config.ini RUN sed -i 's|{BASE_DIR}/db.sqlite3|autodb|gI' auto/config.ini RUN sed -i "s/USER_PATTERN/root/gI" auto/config.ini RUN sed -i "s/PASSWORD_PATTERN/root/gI" auto/config.ini RUN sed -i "s/HOST_PATTERN/database/gI" auto/config.ini RUN sed -i "s/PORT_PATTERN/3306/gI" auto/config.ini Then, I have my docker-compose.yml designed as follow: # docker-compose.yml version: "3" services: database: image: mariadb container_name: database ports: - "3306:3306" environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=autodb hostname: 'database' runserver: build: . command: python /auto/manage.py runserver 0.0.0.0:8000 container_name: runserver ports: - "8000:8000" depends_on: … -
django: adding a form to formset in template causing issues
I know this kind of question are recurrent here and I have searched around for hours for an answer but nothing this seems to solve the issue. I have a formset where the user can dynamically add a form. The formset works well when there is only form, but when the user adds a form, this newly added form does not get saved in the database table which lead me to think that there is an issue with the adding button. My limited skills in programming and especially Javascript prevent me from going further in understanding what is going on here is my view: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) elif request.method == 'POST': formset = form(request.POST) if formset.is_valid(): for check_form in formset: quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) check_form.save() return redirect('/dash2.html') #else: #form = form(queryset= historical_recent_data.objects.none()) return render(request, 'new_sale.html', {'formset':formset}) and here is the template: <form method="POST" class="form-validate" id="form_set"> {% csrf_token %} {{ formset.management_form }} <table id="form_set" class="form"> {% for form in formset.forms %} {{form.non_field_errors}} {{form.errors}} <table class='no_error'> … -
Restrict updating fields if object is deactivated DRF
I have a model: class Trade(models.Model): name = models.CharField(max_length=255, unique=True) is_active = models.BooleanField('Active', default=True) is_deleted = models.BooleanField('Deleted', default=False) And my view: class TradeViewSet(viewsets.ModelViewSet): queryset = Trade.objects.all() serializer_class = TradeSerializer permission_classes = [permissions.IsAuthenticated] def perform_destroy(self, instance): instance.is_deleted = True instance.save() serializer.py class TradeSerializer(serializers.ModelSerializer): class Meta: model = models.Trade fields = ( 'id', 'name', 'is_active', ) read_only_fields = ('id', 'is_deleted') And my question: how I can disable update and partial update all fields except is_deleted field if the value of is_deleted field of my object marked as True? I tried to override get_extra_kwargs, but it doesn't work Appreciate -
Can a file be converted with API before submitting the form?
I want to convert a PDF file using convertapi but I'm not sure if that can be done before the user clicks Submit on the django form i.e. before the file is saved through the form in Django. -
Use an app's model's object fields as form ChoiceField in another app
I have two apps,menu and table This is a model in app menu class Item(models.Model): name = models.CharField(verbose_name="Item Name", max_length=200, db_index=True) And in app table, I have a form.py as following: from django import forms class TableForm(forms.Form): item = forms.ChoiceField(choices= xxx) I would like to use the list of all object names in the model Item as a choicelist in the form. The objects of Item could be created both by admin and elsewhere in my project during runtime and updated in the database. Could someone advise? Thanks.