Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to display a message when a product is added or removed from the cart in django
I am doing an ecommerce with django and I want to add a message when they add or remove a product, but I don't know where to put it or how, I am using the message framework. The messages work only that I don't know how to add them so they appear when I delete or add a product to the cart. I show you my simplified code views.py def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'store/cart.html', context) def updateItem(request): data =json.loads(request.body) productId = data['productId'] action = data['action'] print('Action', action) print('Product',productId) customer=request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) messages.success(request, 'the product was added successfully') if action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() elif action == 'delete': orderItem.delete() return JsonResponse('Item was added', safe=False) In order not to repeat the code several times, I created a utils.py file that is … -
Two Factor verification being called twice on from post
I'm implementing django-two-factor-auth into a project I'm building. I've gotten two factor to work with a base project without issues. I'm currently running into a problem where the verification check for the token is run twice during post which causes authentication to fail. To generate this issue subclass LoginView and add override post code below: class Custom_Login_View(LoginView): template_name = 'two_factor/core/login.html' def get_form(self, step=None, data=None, files=None): return super().get_form(step, data, files) def post(self, *args, **kwargs): form = self.get_form(data=self.request.POST, files=self.request.FILES) form.is_valid() return super().post(*args, **kwargs) It appears the issue is that is_valid is called both in my form and it's parent forms, which is why authentication happens twice. It's very likely I'm doing something to cause my own issue, but I can't figure out how to prevent it, without editing something in django-two-factor-auth. Am I missing something? Is there a good workaround for this? I think I know a good place to patch django-two-factor-auth to fix it, but I'd rather not have to do that. -
How to solved error "Invalid default value for <field> " in django
I using django framework to devlop my site. When i running on development server with sqlite database. database migrate everything work well. but i got a problem when i running on production server with mysql database. in console is running OK in few line then display error "Invalid default value for 'state'". what happend to got this error. this is my model in models.py class Order(models.Model): ref_order = models.CharField(max_length=25,verbose_name="ref_code") member = models.ForeignKey('Member',on_delete=models.CASCADE,verbose_name="member") order_product = models.ManyToManyField('OrderProduct',verbose_name="order_product") reciver_name = models.CharField(max_length=30,verbose_name="reciver") reciver_location = models.CharField(max_length=30,verbose_name="reciver location") submit_order = models.BooleanField(default=False,verbose_name="order submit") evidence = models.FileField(upload_to='slip',null=True,verbose_name="evidence transfer") money_transfer = models.FloatField(null=True,verbose_name="money") verified = models.BooleanField(default=False,verbose_name="verified transfer") state = models.CharField(max_length=500,verbose_name="state") create_at = models.DateTimeField(auto_now_add=True,verbose_name="create at") payment_at = models.DateTimeField(blank=True,null=True,verbose_name="transfer_data") -
channels how to know the name of the group an event is sent inside?
So I have a websockets consumer like this import json from channels.generic.websocket import AsyncWebsocketConsumer class GatewayEventsConsumer(AsyncWebsocketConsumer): """ An ASGI consumer for gateway event sending. Any authenticated user can connect to this consumer. Users receive personalized events based on the permissions they have. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) async def connect(self): user = self.scope['user'] if user.is_anonymous: # close the connection if the # user isn't authenticated yet await self.close() for member in user.member_set.all(): await self.channel_layer.group_add(member.box.id, self.channel_name) await self.accept() async def disconnect(self, close_code): for member in self.scope['user'].member_set.all(): await self.channel_layer.group_discard(member.box.id, self.channel_name) async def fire_event(self, event: dict): # need to implement caching formatted = { 'data': event['data'], 'event': event['event'], } required_permissions = event.get('listener_permissions', []) overwrite_channel = event.get('overwrite_channel', None) # need to know which group the event is being sent inside # to get the box-id, and thus get the member to check perms member_permissions = [] if not required_permissions or required_permissions in member_permissions: await self.send(text_data=json.dumps(formatted)) on websocket connect, I put the user into groups according to the boxes they are a part of. On disconnect, I remove them all. Now, this is how I fire my events. @receiver(post_save, sender=api_models.Upload) def on_upload_save(instance=None, **kwargs): if kwargs.pop('created', False): return async_to_sync(channel_layer.group_send)( instance.box.id, { 'type': 'fire_event', 'event': … -
Write to Django sqlite database with external script
I don't know if what I am trying to do makes the most sense or if there is a better way to do this. However, I am learning how to build a website using django. I am wondering, can I use an external python script that runs daily to get stock information, and publish it to my django website database? I have created a Stock class as follows: class Stock(models.Model): def __str__(self): return self.name name = models.CharField(max_length=50) ticker = models.CharField(max_length=5) price = models.DecimalField(max_digits=100, decimal_places=2) date = models.DateField() I then run a python script that pulls stock data down and tries to write to the database as follows: dfDatabase = dfCurrentDay[['Ticker', 'Company', 'Close', 'Date']] con = db.connect(r'C:\Users\shawn\Dev\stockshome\trying_django\src\db.sqlite3') dfDatabase.to_sql('Stock', con=con, if_exists='replace') data = con.execute("SELECT * FROM Stock").fetchall() print(data) When I print data, it returns the appropriate values. However, when I go to the webpage, it shows up blank. Is that because I have done something wrong with my view, or am I doing something wrong trying to write to the database? Is there a different way I should be approaching this idea? I envision having various pages based on stock sector, or market cap sizes, etc and I'd like to have a … -
Django rendering different templates in one class based view
I'm starting to use class based views for an application I'm creating but I'm nots sure how it works. What I need is to have three different templates, and each template will show different information depending on a model field. My question is if there's a way to have only one class view that can render three different html templates with 3 different contexts, or if I need to create 3 different classes. Using function based views, I would just do this: # def humanResourcesView(request): # context = { # 'data' : Document.objects.all().filter(documentType='humanResources'), # } # return render(request, 'main/hr.html', context) # #view to display training documents after click # def trainingView(request): # context = { # 'data' : Document.objects.all().filter(documentType='training'), # } # return render(request, 'main/training.html', context) # #view to display resource documents after click # def reportsView(request): # context = { # 'data' : Document.objects.all().filter(documentType='reports') # } # return render(request, 'main/reports.html', context) But I'm not sure how it works with class based views. Currently I have this, which renders and filters data correctly for one template, but I don't know how to do multiple templates. Do I need to create 3 different classes? class DocumentView(View): def get(self, request, *args, **kwargs): … -
python NameError: name 'Z' is not defined but just in some executions
I am having this error when I instantiate this class several times. When I instantiate a few times or give it time for new instantiations this error does not occur. Traceback (most recent call last): File "C:\Users\rafae\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "C:\Users\rafae\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\rafae\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\rafae\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_compat.py", line 39, in reraise raise value File "C:\Users\rafae\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\rafae\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 1936, in dispatch_request return self.view_functionsrule.endpoint File "C:\Users\rafae\dev\patient_simulator\Controllers\PatientController.py", line 18, in hello_world patients.append(Patient().dict) File "C:\Users\rafae\dev\patient_simulator\Services\PatientService.py", line 36, in init self.glicose = self.gerarGlicose() File "C:\Users\rafae\dev\patient_simulator\Services\PatientService.py", line 109, in gerarGlicose y = 1/((Z**2)+0.011)*10.3 NameError: name 'Z' is not defined class Patient: glicose = 0 def __init__(self): self.glicose = self.gerarGlicose() def gerarGlicose(self): utils = Utils() if self.diabetes: x = utils.generateNormalNumber(87.5, 12, 10, 900) z = random.uniform(0.0, 1.0) y = 1/((Z**2)+0.011)*10.3 return (self.volemia*(X+Y))/100 else: x = utils.generateNormalNumber(87.5, 8.93, 65, 110) return (self.volemia * x)/100 -
Django REST Framework: Paginating a queryset with a changing sort order
For simplicity, let's say I'm creating a web application that allows users to create and delete Posts on their personal Profile. Along with its content, each Post has a score, representing the number of times another user has upvoted that Post. Since a user could have hundreds of Posts on their Profile, the associated API endpoint needs to be paginated. However, using Django REST Framework's PageNumberPagination brings two issues: If a post is added or deleted to a Profile while another user is paginating through its posts, they may see the same Post twice or miss a Post, since the results belonging to a particular page in the results set will have changed. Similarly, if the user decides to sort the posts by their score, new upvotes could cause the ordering of the posts to change while the user is still requesting new pages, leading to the same issue. Adopting CursorPagination solves the first issue, but means we can no longer sort by score, since: Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. Is there any pagination scheme that can address both issues, while still allowing the user to sort by … -
Django form not updating using django signals
My django form is currently not updating, it also doesnt seem to be fetching the user's id to update their info from the database, i am trying to update my fields using django signals and it doesn't seem to be working, for my django signals it is fetching the info from the 'booking' model but i would like to user an i don't really understand django signals as i am only a beginner, here is my code. signals.py def save_booking(sender, instance, created, **kwargs): if created: Appointment.objects.create( user=instance.user.id, booking=instance, ) instance.save() post_save.connect(save_booking, sender=Booking, dispatch_uid="my_unique_identifier") views.py def updateUser(request, pk): update = Appointment.objects.get(id=pk) book = BookingForm(instance=update) if request.method == 'POST': book = BookingForm(request.POST, instance=update) if book.is_valid(): book = book.save(commit=False) book.save(update_fields=['booking']) book.user = request.user return redirect('userpage') context = {'book': book} return render(request, 'update_user.html', context) models.py class Booking(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) PACKAGES_CHOICES = [('FULL DAY SPA', 'Full Day Spa'), ('HALF DAY SPA', 'Half Day Spa'), ('MOONLIGHT SPA', 'Moonlight Spa')] packages = models.CharField(max_length=100, choices=PACKAGES_CHOICES, default='FULL DAY SPA', null=True) PEOPLE_CHOICES = [('ONE', '1'), ('TWO', '2'), ('THREE', '3'), ('FOUR', '4'), ('FIVE', '5'), ('SIX', '6'), ('SEVEN', '7'), ('EIGHT', '8'), ('NINE', '9'), ('TEN', '10'), ] people = models.CharField(max_length=100, choices=PEOPLE_CHOICES, default='ONE', … -
How come Django QuerySet returns more values than number of objects in database (repeated objects)?
I am attempting to run a complex query with Django. The below query should return an ordered queryset where the users with the most resources as well as resources that contain same tags to the ones in "common_tags" list should show up on top. The code is below: is_in_query = Q(resources__tags__name__in=common_tags) is_not_in_query = ~Q(resources__tags__name__in=common_tags) #All user count is used to compare number of objects all_user_count = User.objects.filter(is_private=False) #len(qs_full) should equal len(all_user_count) qs_full = (User.objects.filter(is_private=False).annotate(count_resources=Count('resources')) .annotate( search_type_ordering=Case( When(Q(count_resources__gte=6) & is_in_query, then=1), When(Q(count_resources__gte=3) & Q(count_resources__lte=5) & is_in_query, then=2), When(Q(count_resources__gte=0) & Q(count_resources__lte=2) & is_in_query, then=3), When(Q(count_resources__gte=3) & is_not_in_query, then=4), When(Q(count_resources__gte=0) & Q(count_resources__lte=2) & is_not_in_query, then=5), When(Q(count_resources__isnull=True), then=6), default=7, output_field=IntegerField(), )) .order_by('search_type_ordering',) ) The problem: The output of len(all_user_count) is 104. The output of len(qs_full) is 128. There are duplicates in qs_full. I do not know why. -
How to pass a parameter date to url dispatcher but as named parameter
I've been reading lots of tutorials and stackoverflow questions, but I haven't found how to do this. I need to pass a parameter of type Date in a GET call on the URL. I know it sounds easy, but I'm new to Django and what I have found is mostly something like this: Django url that captures yyyy-mm-dd date All those answers solve the issue if I want to have an URL like http:www.myweb.com/2021/09/02 That is great if I want to write an url for a blog or website, but I'm doing it for an endpoint, and in my case, I need something like this /some-action-endpoint/?created_at_gte=2020-01-01 So, I need to capture a parameter (hopefully named created_at_gte) with the value 2020-02-01 (It will awesome if I could capture that immediately as a Date object, but I'm fine with a string) So, my questions are: 1.- It will be enough to create a group like this url(r'^my-endpoint/(?P<created_at_gte>[(\d{2})[/.-](\d{2})[/.-](\d{4})]{4})/$', views.my_view), Note_: by the way, the previous one is not working, if someone knows why it'll greatly appreciate it. 2.-The endpoint needs two parameters: created_at_gte and created_at_lte. How can I handle this? Do I need to add two url's to the url pattern? I'm using … -
instance is not updated, using forms save () Django
instance is not updated, using forms save () Django. Could anyone help? save() got an unexpected keyword argument 'cpnj' views cliente = Cliente.objects.get(user=request.user.id, pk=pk) if request.method == 'POST': form = ClienteForm(request.POST) if form.is_valid(): form.update(instance=cliente, validated_data=form.cleaned_data) return redirect('clienteEdit', pk) Forms def update(self, instance, validated_data, context): print(instance) instance.save(**validated_data) -
Nginx redirecting subdomain calls to a different VPS
I have a site that has been up and running for awhile. I use an nginx proxy to point at my Django app inside of some Docker containers. I want to add a subdomain of "test" to point at a different DigitalOcean droplet, so that I can run pre-production code. On the main domain, I have an A record set for test.example.com to the secondary VPS. I also have an A record for www.example.com for the main VPS. However, whenever I type in http://test.example.com it does a hard 301 redirect back to https://example.com. I have to imagine there is something in my main nginx.conf, but I can't figure it out. My nginx.conf for the 1st main server (www.example.com) is: server { listen 80; server_name example.com www.example.com; return 301 https://example.com$request_uri; } server { listen 80; server_name test.example.com; } server { listen 443; server_name example; charset utf-8; ssl on; ssl_certificate /etc/nginx/example_com_cert_chain.crt; ssl_certificate_key /etc/nginx/example.key; client_max_body_size 4G; location ~ /input.php$ { return 301 http://example.com/$1; } location /media { alias /code/media/; } location /static { alias /code/static/; } location ~ /.git/ { deny all; } location ~ /cgi/ { deny all; } location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For … -
502 bad gateway django elastic beanstalk
I got the django app deployed with elastic beanstalk on aws, I setup postgresql for it as well to work with one on aws. Unfortunately, following https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I am getting 502 bad gateway after eb open I'm not really getting any errors, my app runs on local. I'm using the debug server, I also managed to run it on waitress. I was reading the oceans of info online and the only thing I can think of - do I need to actually deploy to a production server locally or can I just use EC2 for that? I'm learning about AWS as I go, so sorry if I'm not understanding something here :) Thank you! -
Capture values for dinamic inputs in Django
Currently I´m working in a LMS based on chamilo with Django. Now, I´m facing a problem with the form from quiz exercises, because not all exercises have the same number of questions. My problem is how to get the data. Here is my actual code forms.py class Ejercicios(forms.Form): c_id = forms.CharField() lp_id = forms.CharField() item_id = forms.CharField() item_viewId = forms.CharField() exe_id = forms.CharField() time = forms.CharField() total = forms.CharField() views.py (main part for the forms) def post(self, request, *args, **kwargs): print(request) try: form = Ejercicios(request.POST) if request.method == 'POST': if form.is_valid(): user_id = self.request.session.get('user_id') username = self.request.session.get('username') apiKey = self.request.session.get('apiKeyUser') c_id = form.cleaned_data.get("c_id") lp_id = form.cleaned_data.get("lp_id") itemId = form.cleaned_data.get("item_id") item_viewId = form.cleaned_data.get("item_viewId") exe_id = form.cleaned_data.get("exe_id") time = form.cleaned_data.get("time") total = 0 return redirect('core:home') else: return redirect('core:home') except: return redirect('core:home') My main problem is how to fill the variable total with different number of values because the exercises have different number of questions Template $('#quiz_start').click(function () { $('#quiz_start').hide(); var sec = 0; function pad(val) { return val > 9 ? val : "0" + val; } setInterval( function(){ $("#time").attr("value", pad(++sec)); }, 1000); $('#exercise_form').append( '<input type="hidden" name="c_id" value="'+link['c_id']+'">' + '<input type="hidden" name="lp_id" value="'+link['lp_id']+'">' + '<input type="hidden" name="item_id" value="'+link['lp_item_id']+'">' + '<input type="hidden" name="item_viewId" … -
Django-allauth and cookiecutter add buttons for social acc login
By default django allauth shows added social media login options in a list: <div class="socialaccount_ballot"> <ul class="socialaccount_providers"> {% include "socialaccount/snippets/provider_list.html" with process="login" %} </ul> <div class="login-or">{% trans 'or' %}</div> </div> I want to add good looking buttons for google/twitter/etc. but I cannot find provider_list.html anywhere in my project. I know that this template exist in allauth's repo Does anyone know how I add these buttons? -
Django import-export ManyToManyWidget fields appearing blank in export
I have the following models and M2M relationships: class Market(models.Model): marketname = models.CharField(max_length=500) market_id = models.CharField(max_length=100, blank=True) def __str__(self): return self.marketname class TeamMember(models.Model): firstname = models.CharField(max_length=100, default= "First Name") lastname = models.CharField(max_length=100, default= "Last Name") email = models.EmailField(max_length=254) def __str__(self): return self.email class EmailReport(models.Model): name = models.CharField(max_length=1000) recipients = models.ManyToManyField('team.TeamMember', related_name="teamrecipients") frequency = models.CharField(max_length=1000, blank= True) markets = models.ManyToManyField('opportunities.Market', blank=True) def __str__(self): return self.name The following is my admin.py for the EmailReport registration. class EmailReportResource(resources.ModelResource): recipients = fields.Field(widget=ManyToManyWidget(TeamMember, field="email")) markets = fields.Field(widget=ManyToManyWidget(Market, field='marketname')) class Meta: model = EmailReport fields = ['id', 'name', 'recipients', 'markets'] class EmailReportAdmin(ImportExportModelAdmin): resource_class = EmailReportResource admin.site.register(EmailReport, EmailReportAdmin) I am able to export- and all char fields export normally- however, my M2M fields all appear blank. Can anyone please point out my mistake? Thank you so much! -
Filtering dates in a calendar in Django,
I am trying to filter my object in such a way that the link to it displays on the correct date displayed in the calendar, I am using a date field in my model, the problem is that in an earlier model where I used DataTimeFiled everything works correctly and the link to the object details displays on a given date in the calendar. this is my models.py file class HomeworkersEvent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) start_day = models.DateField(auto_now_add=False, auto_now=False, auto_created=False) end_day = models.DateField(auto_now_add=False, auto_now=False, auto_created=False) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('sytoapp:homeworkers_event-detail', args=(self.id,)) @property def get_html_url(self): url = reverse('sytoapp:homeworkers_event-detail', args=(self.id,)) return f'<a href="{url}"> {self.user} </a>' class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField(auto_now_add=False, auto_now=False, auto_created=False) end_time = models.DateTimeField(auto_now_add=False, auto_now=False, auto_created=False) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('sytoapp:event-detail', args=(self.id,)) @property def get_html_url(self): url = reverse('sytoapp:event-detail', args=(self.id,)) return f'<a href="{url}"> {self.user} </a>' Calendar displaying events where I used DateTimeFiled works flawlessly Here is the code on how to filter it in the calendar def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' def formatmonth(self, request, withyear=True, ): current_user … -
How to add auto number column in the tables?
I am learning Django and my first project I am doing a To do application. My idea is that I put the content from the database(models.py) into tables in html ,but also on the side of the table I wanna put a auto number column that which is added in the number of items in table. I tried to do that function with count() function in views.py, but the problem is that when i add a new item in the table the number item column is the same in the number in first row, and second, etc... This is a screenshot of the page to understand it easily This is views.py: from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from .models import * from .models import __str__ # Create your views here. def home(request): count_item = todo.objects.count() all_items = todo.objects.all().order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) def add_todo(request): current_date = timezone.now() new_item= todo(content = request.POST["content"]) new_item.save() return redirect('/') def delete_todo(request, todo_id): item_to_delete = todo.objects.get(id=todo_id) item_to_delete.delete() return redirect('/') This is home.html: <div class="container"> <div class="jumbotron"> <div style="background-color: #0d2e72;" class="card"> <div class="card-header" style="border: none;"> <p style="font-size: 25px; text-align: center; color: white;">TASKS TO DO</p> </div> … -
Multiple ChartJS scripts are not working at the same time
When I am using a Single Chart in ChartJS, it works well but whenever I use more than a Chart, only the last chart works, the others don't longer display. I am not sure of what the problem might actually be as I have checked the console and terminal if I would get any error or so so as to debuy it. index.html {% block content %} <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> # The Script for the first chart <script> // Driver Status var config = { type: 'doughnut', data: { datasets: [{ data: [{{pending}},{{hired}},{{terminated}}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', ], label: 'Population' }], labels: ['pending', 'hired', 'terminated'] }, options: { responsive: true } }; window.onload = function() { var ctx = document.getElementById('pie-chart').getContext('2d'); window.myPie = new Chart(ctx, config); }; </script> # The Script for the Second chart <script> // EVR STATUS var config2 = { type: 'doughnut', data: { datasets: [{ data: [{{done}},{{partial}},{{not_started}}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, … -
How to send CSV to Django Usaing API REST?
How can I send a 220,000-line CSV file to Django using the Rest Framework API? Thank you. -
On Windows 10 Django is not installing properly under the project folder - unable to find manage.py
I am a new developer. I'm following instructions from to Django for Beginners book. When I run C:\Users\User\Desktop\HelloWorld>pipenv install django~=3.1.0 The message I got: Installation Succeeded When I typed C:\Users\User\Desktop\HelloWorld>pipenv shell I got the following result: (User-jBUq-HwN) C:\Users\User> However, in the book the result looks like: (helloworld) $ From the book on page 34. When I try to run the server: (User-jBUq-HwN) C:\Users\User\Desktop\HelloWorld>python manage.py runserver C:\Users\User\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory Any reasons why it can't find manage.py? -
Only show objects where the total ammounts of rows of a subquery is less than a certain value in django queryset
I'm trying to generate a list of a certain model where only the instances from another query. So Here's my models: class Waiter(models.Model): id = models.AutoField(primary_key=True) waiter = models.CharField(max_length=200) class Service(models.Model): id = models.AutoField(primary_key=True) arrival = models.DateTimeField(auto_now_add=True) exit = models.DateTimeField(null=True, blank=True) waiter = models.ForeignKey('Waiter', on_delete=models.CASCADE) article = models.ForeignKey('Table', on_delete=models.CASCADE) total_ammount= models.DecimalField(max_digits=15, decimal_places=2) class Table(models.Model): id = models.AutoField(primary_key=True) table_no = models.CharField(max_length=200) The idea is there can only be four waiters assigned at a service at a single time. How can I filter the results of waiters based on weather they have less than four services at a single time? Thank you in advance :) -
How to update context in an inherited base class?
I am trying to reuse context code in my Django views but the context variable goes missing when I try to move the code around. Here is one that works, with the get_context_data in the class itself: # Works. Views that inherit from FirstContentCreateView # have 'smurf' in the context class FirstContentCreateView(CreateView): model = None form_class = None template_name = None # ..... other stuff here .... def get_context_data(self, **kwargs): """ An override of the default get_context_data method that adds a smurf to the context. """ context = { 'smurf': "Jokey Smurf" } context.update(kwargs) return super().get_context_data(**context) class SmurfyView(FirstContentCreateView): # Works! This view has 'smurf' in the context pass But if I move get_context_data to another base view and dual class, that does not work: class BaseSmurfView(View): """ Moved get_context_data from FirstContentCreateView into here so I can use it elsewhere. That's the only change. """ def get_context_data(self, **kwargs): """ An override of the default get_context_data method that adds a smurf to the context. """ context = { 'smurf': "Jokey Smurf" } context.update(kwargs) return super().get_context_data(**context) class SecondContentCreateView(CreateView, BaseSmurfView): """ This is just like FirstContentCreateView, but instead of having get_context_data in here, it is now coming from BaseSmurfView. Supposedly. """ model = None … -
Django admin page not showing contents in admin_app_description.html
I'm working on upgrading an existing Django project, the source code includes files like application/templates/auth/admin_app_description.html, the contents of which will show up on Django's admin page as introductions beside the item. However, after upgrading to Python 3, the admin page no longer shows the introductions although the admin_app_description.html files still exist in repository. I hope to show the contents, and any hints will be highly appreciated.