Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Retrieve unique rows by latest date/column
I have the following table: class AccountData(models.Model): id = models.BigIntegerField(primary_key=True) date = models.DateField() last_update = models.DateTimeField() account = models.ForeignKey('Account', models.DO_NOTHING, db_column='account', related_name="values") value = models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, null=True) Given a queryset/list of ID's (unknown amount how many ID's, could be None/0) Is there a way to get the latest row for each account, then sum the value? The part I'm really struggling with is only retrieving the latest row per account. I know I can get the accounts that are in the given queryset by doing: accounts = [1, 4, 65] AccountData.objects.filter(account__in=accounts) Just need to figure out how I can only get the rows where "date" is as close to "now" as possible. Thus resulting in having unique rows (only 1 row per account) -
Must i install django every time am starting a project in pycharm
i am just starting a new project on my pycharm i start a new project and run my server but am getting this error message couldn't import django, Must i install django for every project am creating? -
Please help me how can i add some option like inserting images, bold italic inserting link in body
it is a screenshot I listen about markdown but I don't know how to use please suggest some good alternative or tell me about markdown Please check it and tell me a fix. -
Django set logged in user inlineformset_factory
hello Everyone I'm trying to build an application where I can add multiple forms but I am facing a problem when trying to add current logged in user Exception Value:'list' object is not callable @login_required(login_url='login') def addIncome(request, month_id): monthname = Month.objects.get(pk=month_id) monthnameid = Month.objects.get(id=month_id) monthes = Month.objects.all() newForm = inlineformset_factory(Month, IncomeAmount, fields=('income_Name','incomeAmount','incomeCurrency'),can_delete=False, extra=5) if request.method == 'POST': form = newForm(request.POST, instance=monthname) if form.is_valid(): newForm = form.save(commit=False) print(type(newForm)) newForm.user = request.user newForm.save() return redirect(home) else: monthes = Month.objects.all() monthname = Month.objects.get(id=month_id) month = newForm(instance=monthname) context = {'form': newForm, 'month': monthname, 'monthes':monthes} return render(request, 'add.html', context) -
How to count foreign keys in django
I have a project with courses where every Course has Sections, and every Section has Videos, I want to count number of sections in each course, and count number of videos in each Section. How to implement that? views def CourseView(request,slug): course = get_object_or_404(Course,slug=slug) sections = CourseSections.objects.filter(course__title=course.title) videos = SectionVideos.objects.filter(section__course__title=course.title) return render(request,'courses/course_detail.html',{'course':course,'sections':sections,'videos':videos}) models class Course(models.Model): title = models.CharField(max_length=255) class CourseSections(models.Model): title = models.CharField(max_length=50) course = models.ForeignKey(Course,on_delete=models.CASCADE,null=True) class SectionVideos(models.Model): title = models.CharField(max_length=50,null=True) video = models.FileField(upload_to='courses/course_videos',max_length=100) section = models.ForeignKey(CourseSections,on_delete=models.CASCADE,null=True) -
Redirecting To a New Angular Application After Login and Subscription Success
Good Day Everyone, Please I am working on a personal project on Angular, I have two angular applications, the main angular application and the second angular application to redirect to after login and subscription has been validated. The Only issue now is how to make use of the home.component.html of the second application which contains different menu or navbar items but each time i redirect to the second application, the items or menu showing on the navbar are the main or default application component.html but with the second angular application contents. I also discovered that second application was not generated with any index.html file. Please I need help on how to go about this. In summary two angular applications one acting as default (thriller page), the second to display the real contents for movies. How can i implement the default application having its own menu and the second application having its own menu as well. Thanks -
Repeated query in Django View
Good Morning, I have repeated Views in Django app, I am pretty sure there is a better solution to this situation. class BaseMixin: model = Post paginate_by = 9 class PostPostgresList(BaseMixin, ListView): template_name = "blog/postgres_field.html" def get_queryset(self): return Post.published.filter(field=Category.objects.get(name='PostgreSQL')) class PostDjangoList(BaseMixin, ListView): template_name = "blog/django_field.html" def get_queryset(self): return Post.published.filter(field=Category.objects.get(name='Django')) Field in model post is ForeignKey, so I need to put in query instance of the Category. Perhaps I should create some function where I could insert for instance name='Django' and put this function in utils? Thanks in advance for any advise. -
Django Password Validators: If any three of the validations pass user can go ahead
I am looking at how can we set the number of validations that must pass to allow the user to set the password. For example, we have these 5 validtors: AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, { 'NAME': 'registration.validators.CustomPasswordValidator',} ] We want if the user password passes any of the 3 requirements from them. Users can create an account. Any idea how can we do that in Django? -
how to migrate from postgres to phpmyadmin mysql django
our university has MySQL 5.6 server with phpMyAdmin, and my django project uses postgresql. and we cannot deploy project. any help? -
Django & React Deployment on VPS
I'm a newbie trying to deploy a Django backed react app. Please advise. What I've created: An app initiated with create-react-app, fully functional locally; A Django api serving the data They 'talk' perfectly to each other, but they are built separately Questions: I'm not sure how to incorporate them into one app for deployment. This post by VALENTINO GAGLIARDI is very helpful. But it seems like it's not suitable for an app initiated with create-react-app? Should I learn webpack for deployment? I have experience deploying a fully functional Django e-commerce website and it's up and running. Django handles both frontend and backend via many Django templates. I used Gunicorn and Nginx for serving the website on a VPS (Ubuntu 18). It's all quite confusing for me to deploy ONE website, and it seems to me, with having to serve TWO apps at the same time under one domain name? Any pointers for what knowledge should I acquire before completing this task? -
403 forbidden CSRF verification failed. Request aborted
for my pizza orders website, I am getting the above error on every time I try to make browser refresh cache by Ctrl^F5. the view for the login function goes as follows: @csrf_protect def login(request): username = request.POST.get("username") password = request.POST.get("password") myUser = authenticate(request, username=username, password=password) if myUser is not None: auth_login(request, myUser) context = { "toppings" : Topping.objects.all(), "subs" : Sub.objects.all(), "pastas": Pasta.objects.all(), "salads": Salad.objects.all(), "platters": DinnerPlatter.objects.all(), "username": username } return render(request, "orders/menu.html", context) else: return render(request,"orders/error_login.html") and the html code for the index.html and the menu.html both have {% csrf_token %} inside the forms as follows: index.html - <div class="login_box"> <form action="{% url 'register' %}" method="POST" class="p_signin_form"> {% csrf_token %} ... </form> <form action="{% url 'login' %}" method="POST" class="p_login_form"> {% csrf_token %} ... menu.html - <div class="make_an_order" id="order"> <h2>Pizza Order</h2> <form id="form_pizza_order" class="form_pizza_order" method="post"> {% csrf_token %} ... so what seems the problem? thanks. -
Django: Writing a custom UserManager for AbstractUser class, in order to handle foreign keys during superuser creation
I have an AbstractUser class as following in my models.py file: class UserModel(AbstractUser): some_field = models.ForeignKey(SomeOtherModel, on_delete = models.CASCADE) # other fields Since this is a user model, I am required to use the same to create a superuser but I am unable to handle the foreign key some_field while using the createsuperuser command. I have read at places that I need to add REQUIRED_FILEDS = ['some_field'] and also create a custom UserManager to handle it, but it is all very unclear to me: Can I create a custom UserManager for an AbstractUser class (and not an AbstractBaseUser class)? If yes then how to do it? Any code example or reference document will be helpful. Is there any other way to solve this problem? I just need to handle this one field during superuser creation. NOTE: I have initialized AUTH_USER_MODEL in settings.py I am a beginner at Django programming so any further reference, documentation or tutorials on handling user model will be very useful for me. Thanks in advance! -
How to integrate djangoCMS with existing django project
I am new to Django-CMS. I have a Django project with multiple apps to manage specific data. I want to add a CMS platform to my project to let some users contribute to publishing content. The content would be a simple contact page or a complicated page including text, images, as well as charts and report tables of data stored in DB via the existing Django project. I don't have any idea how to add djangoCMS to my existing project. How I can integrate djangoCMS as a new app in my project? Or is it a better idea to have a separate CMS and show data via REST API of the existing project? Can I use Django-CMS plugins to publish my reports via CMS? Is it needed to have a separate database for CMS? Many thanks in advance. -
Django URL gets called twice and crashes view
I am trying to implement a payment system now from the company documentation, I am expecting their api to call my project at http://127.0.0.1:5000/cart/payment/verify/?flwref=FLW-MOCK-5254aaf8272ae6c1ebbeaf754a75509b&txref=user-1-cart-40 and from the request tab the right url is returned. However there is no response to that url instead immediately see a get request with the url http://127.0.0.1:8000/cart/payment/verify/?resp={%22name%22%3A%22opop%22%2C%22data%22%3A{%22data%22%3A{%22id%22%3A1249370%2C%22txRef%22%3A%22user-1-cart-22%22%2C%22orderRef%22%3A%22URF_1588046289399_3226935%22%2C%22flwRef%22%3A%22FLW-MOCK-d92dbe44cad98158ebf026c29eaf91df%22%2C%22redirectUrl%22%3A%22http%3A%2F ...} I have no idea what is causing this and was hoping someone can help me track it down. Views @csrf_exempt def verifyPayment(request): # ref = json.loads(request.GET['resp']) # ref_code = ref['tx']['txRef'] ref_code = request.GET.get('txref') if ref_code != None: cart_id = ref_code.split('-')[3] cart = Cart(request, id=cart_id) data = { # this is the reference from the payment button response after customer paid. # "txref": "user-%s-cart-%s"%(request.user,cart.cart.id), "txref": ref_code, # this is the secret key of the pay button generated "SECKEY": "FLWSECK_TEST" } if cart.items_available(): r = requests.post( 'https://api.ravepay.co/flwv3-pug/getpaidx/api/v2/verify', data=data) response = r.json() if response['status'] == 'success': # confirm that the amount for that transaction is the amount you wanted to charge if response['data']['chargecode'] == '00': # a = cart.summary_delivery() if response['data']['amount'] == float(cart.summary_delivery()): print("Payment successful then give value") payment = response cart.mark_items_paid() cart.complete(request, cart_id) cart.sendResturantOrder(cart.groupCartOrders(), response['data']['meta'][0]['metavalue']) payment = 'success' else: payment = "failure" return render(request, 'payment/payment.html', {'payment': payment}) def processPayment(request): … -
django fullcalender refetching events not workig
I am trying to implement a fullcalendar in django. All the functions are working fine, but the calendar doesn't get refreshed if I use refetchevents or rerender events calendar.fullCalendar('refetchEvents');. If i reload the page the events are showing up, but i want to see the changes without reloading the page. Any idea why is it not working? Models: from django.db import models class Events(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255,null=True,blank=True) start = models.DateTimeField(null=True,blank=True) end = models.DateTimeField(null=True,blank=True) def __str__(self): return self.name urls: from django.contrib import admin from django.urls import path from calend import models from calend.views import * from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('', calendar, name='calendar'), path('add_event/', add_event, name='add_event'), path('update/', update, name='update'), path('remove/', remove, name='remove'), ] views: from django.shortcuts import render from .models import Events from django.http import JsonResponse def calendar(request): all_events = Events.objects.all() context = { "events":all_events, } return render(request,'calendar.html',context) def add_event(request): start = request.GET.get("start", None) end = request.GET.get("end", None) title = request.GET.get("title", None) event = Events(name=str(title), start=start, end=end) event.save() data = {} return JsonResponse(data) def update(request): start = request.GET.get("start", None) end = request.GET.get("end", None) title = request.GET.get("title", None) id = request.GET.get("id", None) event = Events.objects.get(id=id) event.start = start event.end = end event.name = title event.save() … -
Deployment error to AWS using psql and django
I am currently building a Django webapp as a front end to my Postgresql database. I am using elastic beanstalk to deploy to AWS (the database also lives on AWS). The website works locally (it's just a simple table at the moment) but whenever I run eb deploy I get the following error: >"2020-04-28 10:23:56 ERROR [Instance: i-0e140fa936b76bee1] Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001]. 2020-04-28 10:23:56 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]." Sorry in advance if this may lack info, any feedback would be much appreciated :) -
What is the best way to build API in python?
I'm trying to build API in python and i wondering what is the best way to do that. I consider: -django-rest-framework -graphene-django -aiohttp and I want to know what are pros and cons of using each of them and what is the best option in 2020 -
How to change 'name' in edit row in Django Admin?
How to make a different name for the model only in this line. It is necessary that in other places there is also an Author and Authors, and it was in this one that it was possible to change to something else. -
Time constraint in Django
I have a time constraint for creating something in Django. Consider the constraints: Constraint 1: Timings: the user will give the timings varying from 5:00 AM to 4:59 AM. Constraint 2: End - Time cannot be after 4:59 am of the next day. Cases: Case 1: creating slots from 2 am - 4 am should work fine. Case 2: Presently, The code what I have written works incorrectly for case: Start_time = 8:00 End_time = 6:00 Here, in front-end, the start_time = 8:00 means morning and end_time = 6:00 means the next day morning and violates our Constraint No:2. Case 3: When someone gives start_time = 5:00 and end_time = 2:00, we need to add the next day in end_time. The Code I have written is as below: start_time = request.POST.get('start_time') end_time = request.POST.get('end_time') dateTimeA = datetime.datetime.strptime(start_time, '%H:%M') dateTimeB = datetime.datetime.strptime(end_time, '%H:%M') dateTimeDifference = dateTimeB - dateTimeA dateTimeDifferenceInHours = dateTimeDifference.total_seconds() / 3600 if dateTimeDifferenceInHours <= 0: dateTimeB += datetime.timedelta(days=1) dateTimeDifference = dateTimeB - dateTimeA dateTimeDifferenceInHours = dateTimeDifference.total_seconds() / 3600 The Front-End Looks as below(The code is written in HTML): So, if someone can please help with the improvements in the code I have written so, that all my above cases … -
Pass js variable to django change admin view
Is it possible to pass js variable to custom change_form_template? I've override changeform_view to add this variable to template def changeform_view(self, request, object_id=None, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['var_name'] = request.build_absolute_uri(f'<url>/{object_id}/') return super().changeform_view(request, object_id, form_url, extra_context) Then I need somehow to declare it in my template -
Change default constraint for PositiveSmallInteregField
i want to change constraint that SmallPositiveIntegerField produces in Db during migration: last_watched_episode smallint constraint archives_seasonmodel_last_watched_episode_check check (last_watched_episode >= 0), I want to change check (last_watched_episode >= 0) to check (last_watched_episode >= 1). Do you know where is the souce code of this field in Django, that is in charge for making constraints? I need it in oredr to create mixin for this field. Thank you. -
How to make a request to local URL as part of automated tests?
I'm writing an automated test in Django to check that a webhook is working on the application. The test sends a bunch of JSON to the webhook and will check that the call has been logged in the database. The problem I'm hitting however is that the test calls the http://localhost URL and the data is thus saved in my local dev database and not in the temporary database created by the test. So I now have no way to check the call has been received. Whats the right solution for this? from django.test import TestCase import requests from monzo.models import Transaction, RequestLog class WebhookChecks(TestCase): fixtures = ['db.json', ] def test_simple_expense(self): my_json = '{"type": "transaction.created", REMOVED FOR SECURITY }' url = 'http://localhost/some_url/webhook/' headers = {'Content-Type': 'application/json'} r = requests.post(url, data=my_json, headers=headers) if not "200" in str(r): print("Something didn't work out. Error: "+str(r)) self.assertTrue("200" in str(r)) -
How to properly filter nulls_last on one_to_many field?
I'm trying to filter and order objects by existance of a related model with forcing nulls as last. Example models: class ModelA(models.Model): name = models.CharField(max_length=255) ... class ModelB(models.Model): model_a = models.ForeignKey(ModelA, related_name=model_b) date = models.DateField() time = models.TimeField() ... Now, I need to filter ModelA by some kwargs (normal operations), but I also need to order ModelA by nearest ModelB date and time (in future, not past) ascending or descending WITH A SINGLE QUERY PARAM and also NULLS need to be placed last regardless of ascending or descending order. I already came to a conclusion that I need to overwrite default QuerySet order_by: class ModelAQuerySet(models.QuerySet): def order_by(self, *field_names): if 'model_a_date' in field_names or '-model_a_date' in field_names: field_names = list(field_names) if 'model_a_date' in field_names: field_names.remove('model_a_date') return super().order_by( 'model_b__date', 'model_b_time', *field_names ) else: field_names.remove('-model_a_date') return super().order_by( '-model_b__date', '-model_b__time', *field_names ) else: return super().order_by(*field_names) It works fine when I'm ordering descending ('-model_a_date'), since NULLS are last, but I'm having a hard time placing nulls last in ascending order. I already tried: return super().order_by( F('model_b').asc(nulls_last=True), 'model_b__date', 'model_b__time', *field_names ) #### return super().order_by( F('model_b').asc(nulls_last=True) ).order_by( 'model_b__date', 'model_b_time', *field_names ) #### return super().order_by( 'model_b__date', 'model_b_time', *field_names ).order_by( F('model_b').asc(nulls_last=True), ) but that does not work at all. … -
Whatsapp bot with Twilio and Chatterbot not working properly
I have a Whatsapp bot using Twilio and Django server. For conversational replies, I have used ChatterBot package. The problem is it is giving the same message coming to it via sender. To begin testing, connect to your sandbox by sending a WhatsApp message from your device to +14155238886 with code join drove-provide You will see that the chatterbot is giving the same message and is not working properly. Please help me. This is Callback URL from Twilio and its working fine https://whats-app-bot-99.herokuapp.com/sms/ from twilio.twiml.messaging_response import MessagingResponse from django.views.decorators.csrf import csrf_exempt from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer chatbot = ChatBot( 'Ron Obvious', trainer='chatterbot.trainers.ChatterBotCorpusTrainer' ) trainer = ChatterBotCorpusTrainer(chatbot) # Train based on the english corpus #Already trained and it's supposed to be persistent #trainer.train("chatterbot.corpus.english") def home(request): return HttpResponse("Hello World!!") @csrf_exempt def sms_reply(request): """Respond to incoming calls with a simple text message.""" # Fetch the message if request.method=='POST': msg = request.POST.get('Body') phone_no = request.POST.get('From') reply = chatbot.get_response(msg).text # Create reply resp = MessagingResponse() resp.message(str(reply)) return HttpResponse(str(resp)) -
How to restore postgres database backup that is in my host system using Docker config from django-cookiecutter?
How to restore Postgres database backup .sql file that is in my host system using Docker config from django-cookiecutter? Where to copy file and what commend run?