Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django:Uploaded images not showing in Heroku
I have deployed my app on Heroku and added some images through the admin panel. In my page the images are not showing. The database is working fine so I dont think theres anything wrong there. media and static urls in settings: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('management_app.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I guess the media_root file is not being created in heroku. I had to run python manage.py collectstatic manually for the static files to load. What should I do about this? -
Django+React rest-auth
I am using the rest-auth module to enable user authentication on my web app. Though I am facing some difficulties in fetching details about the user. The Django-rest-framework return a key when I post my username and password, while that's enough for logging in I also want to fetch additional details like user.is_staff, user.username and user.email. I tried to use Token serializer, but I am not sure if I am doing it right. ** settings.py ** REST_AUTH_SERIALIZERS = { 'TOKEN_SERIALIZER': '## How to define the path to my serializer ##', } ** serializers.py ** from rest_framework import serializers from lms.models.post_models import Post from django.contrib.auth.models import User from rest_auth.models import TokenModel class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email') class TokenSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = TokenModel fields = ('key', 'user') Please tell what piece is missing or if any piece is incorrect. Also, please help me figure out the part between ## ##. Thank you! -
How to restart a port 8080 in port 8080, 8081, 8082 in apache on Centos 7?
i want restart one port in multiple port of apache in Centos 7, how i can do this? thank you. -
Django - set a model CharField value to the name of a field from another model
I have a model when I want to field_name to be the name of any field from another model. I wrote this code: from providers.models import Organisation FIELD_CHOICES = [(x.name,x.verbose_name) for x in Organisation._meta.get_fields() ] class Score (models.Model): field_name = models.CharField(max_length=101, choices=FIELD_CHOICES) When I run makemigrations I get django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. This is the complete traceback: Traceback (most recent call last): File "./src/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/henry/Documents/Sites/Development/autumna-dev/autumna/src/scoring/models.py", line 7, in <module> FIELD_CHOICES = [(x.name,x.verbose_name) for x in Organisation._meta.get_fields() ] File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/db/models/options.py", line 733, in get_fields return self._get_fields(include_parents=include_parents, include_hidden=include_hidden) File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/db/models/options.py", line 793, in _get_fields all_fields = self._relation_tree File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] … -
How to add an element without changing the height of the card or disturbing position of other elements
How do I add an element(image) at the end without changing the height of the card, with card height set to auto is there any way to solve this? any help is appreciated, Thanks! .card { width: 540px; height: auto; border: 1px solid #707070; } .field2 { font-family: inherit; padding-top: 20px; padding-bottom: 25px; display: flex; justify-content: space-between; } .log_in_instead { padding-left: 60px; } .create { padding-right: 70px; } #img101 { position: relative; left: 490px; top: -150px; } <div class="card"> <div class="field2"> <span class="log_in_instead"> <a href="#">Log in instead</a> </span> <span class="create"><button id="create_button" type="submit">Create</button</span> </div> <span><img src="{% static 'main/images/img101.svg' %}" id="img101"></span> </div> This is what it should look like: [1]: https://i.stack.imgur.com/jkPg2.png This is what it looks like: [2]: https://i.stack.imgur.com/w1ROu.png -
How to put an if statement outside the functions in Django Views, Python
I have 3 functions. Each of them has the same line of code: if request.method == "POST" and 'url' in request.POST: Here are the functions: def checkurl(request): if request.method == "POST" and 'url' in request.POST: url = request.POST.get('url', '') url_response = "" if not url.startswith('http://') and not url.startswith('https://'): url_get = "http://" + url url_response = requests.get(url_get, headers=headers, allow_redirects=False) url_status_code = url_response.status_code if url_status_code == 200: url = url_get return url else: url = "https://" + url return url return url def netloc(request): url = checkurl(request) global url_scheme global url_port global url_netloc global url_path if request.method == "POST" and 'url' in request.POST: url_parsed = urlparse(url) url_scheme = url_parsed.scheme url_port = url_parsed.port url_netloc = url_parsed.netloc if url_netloc.startswith('www.'): url_netloc = url_netloc.replace('www.', '') if url_netloc.endswith('/'): url_netloc = url_netloc.replace('/', '') return url_scheme, url_port, url_netloc def tests(request): if request.method == "POST" and 'url' in request.POST: url = checkurl(request) netloc(request) var = { 'url':url, 'url_scheme':url_scheme, 'url_port':url_port, 'url_netloc':url_netloc, } return render(request, 'apptests/shots.html', var) else: return render(request, 'apptests/shots.html') I do not want to repeat the same line of code in each function and want to remove it and put it aside before these 3 functions. But I cannot do it Please help