Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django adds an extra "/" in the url?
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/products/1// Using the URLconf defined in products.urls, Django tried these URL patterns, in this order: [name='home'] contact/ admin/ products/ [name='product-list'] products/ products/ <int:id>/ [name='product-detail'] products/ <int:id>/delete/ [name='product-delete'] products/ about/ The current path, products/1//, didn’t match any of these Why does it require an extra slash after the id? The more I deal with it, the more slashes it wants. I have urls.py like this: from django.urls import path from .views import ( product_detail_view, product_create_view, render_initial_data, dynamic_lookup_view, product_delete_view, product_list_view) app_name = 'product' urlpatterns = [ path('', product_list_view, name='product-list'), path('', product_create_view), path('<int:id>/', dynamic_lookup_view, name='product-detail'), path('<int:id>/delete/', product_delete_view, name='product-delete'), path('', product_detail_view), ] Also another urls.py with something like this: urlpatterns = [ path('', home_view, name='home'), path('contact/', contact_view), path('admin/', admin.site.urls), path('products/', include('product.urls')), path('about/', about_view), ] Here's the function: def dynamic_lookup_view(request, id): #obj = Product.objects.get(id=id) #obj = get_object_or_404(Product, id=id) try: obj = Product.objects.get(id=id) except Product.DoesNotExist: raise Http404 context = { 'object': obj } return render(request, "products/product_detail.html", context) So it raises the exception because it was looking for the additional "/", but where did it come from? -
S3 Bucket Configuration Problem, <Code>AccessDenied</Code>
I'm Unable to set up S3 Bucket Correctly. I followed the following steps to configure. Installed boto3 django-storages Created S3 Bucket with IAM User, And Block all public access is off Settings.py has the following related code. INSTALLED_APPS = [ #... 'storages', ] AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR / 'static'), os.path.join(BASE_DIR / 'build/static') ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) MEDIA_URL = 'https://%s/%s/images/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Now the problem is When I go to the URL of the Uploaded file which is MEDIA_URL = 'https://%s/%s/images/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) I'm getting this error on accessing the Image file https://remote-hospital-v4.s3.us-east-2.amazonaws.com/static/images/IMG_18.jpg And also files are still getting stored locally and are not getting uploaded to S3 Bucket Help required to fix this, Or where the problem could be.Thanks! -
Handling dynamic IP in Django ALLOWED_HOSTS with nginx
I'm having issues with what i believe is my nginx.conf which is causing the instance to be restarted again and again, as the health-checks fail on my managed container service. I'm running my setup in AWS Lightsail Containers, where I have three containers running: nginx django nextjs When publishing a new release on my AWS Lightsail instance it runs fine for a few minutes, then I hit a 503 error, which causes the instance to reboot - run a few minutes then reboot again. Looking at the logs I can see that the health-check failed, and django throws and error saying that I should add the request IP to the allowed hosts: [28/Aug/2021:13:56:23] Invalid HTTP_HOST header: 'x.x.x.x'. You may need to add 'x.x.x.x' to ALLOWED_HOSTS. [28/Aug/2021:13:56:23] Bad Request: /health.txt The problem is that my lightsail container service does not have a static IP (nor do I believe I can get a static IP). My current nginx.conf is below (feedback is appreciated). My question here is how should I deal with this issue? I feel like setting ALLOWED_HOSTS = ['*'] is not a great approach. Can I hardcode the host for the healthcheck or similar? nginx.conf: upstream backend { server ${BACKEND_HOST}:${BACKEND_PORT}; … -
Why data from table is not recieving in djagno?
When i tried to retrieve data from table it is not showing any thing without giving error message. This is my model class staff(models.Model): id = models.AutoField name = models.CharField(max_length=250) role = models.CharField(max_length=250) salary = models.CharField(max_length=250) address = models.CharField(max_length=250) number = models.CharField(max_length=250) date = models.DateField() This is my views file def user(request): staffs = staff.objects.all() params = {'staff': staffs} return render(request, "salary/user.html", params) and this is my template <td> 02312 </td> {% for staff in staffs %} <td>{{ staff.name }} </td> {% endfor %} <td> $14,500 </td> -
Simplifying Django Query Annotation
I've 3 models and a function is called many times, but it generates 200-300 sql queries, and I'd like to reduce this number. I've the following layout: class Info(models.Model): user = models.ForeignKey(User) ... class Forum(models.Model): info = models.ForeignKey(Info) datum = models.DateTimeField() ... class InfoViewed(models.Model): user = models.ForeignKey(User) infokom = models.ForeignKey(Info) last_seen = models.DateTimeField() ... . I need to get all the number of new Forum messages, so only a number. At the moment it works so that I iterate over all the related Infokoms and I summerize all Forums having higher datum than the related InfoViewed's last_seen field. This works, however results ~200 queries for 100 Infos. Is there any possibility to fetch the same number within a few queries? I tried to play with annonate and django.db.models.Count, but I failed. Thanks. -
Django query return array data
I want to query some values from my Postgresql database in Django and want to show in my table. but problem is I am getting some array data like ['Dish', 'LNB Inverto']. I want to show values in my table like Dish| 1000 | 5 |5000 ------------------------- LNB | 500 | 10 |5000 ------------------------- my views: def purchaseDetails(request,pk): invo_data = PurchaseInvoice.objects.all().filter(invoice=pk) return render(request,'purchase/invoice_details.html',{'invoice':invo_data}) my html: {% for data in invoice %} <tr><td> {{data.product_name}} </td><td> {{data.price}} </td><td> {{data.quantity}} </td></tr> {% endfor %} I am getting like ['Dish', 'LNB Inverto'] ['810.00', '214.00'] ['8', '8'] -
drf user serializer return custom data
I've been trying to create a drf app and wanted to achieve a sign in view that does two things: set's the cookies automatically returns the url and the username of the user the issue is specifically in the validate function inside the serializer code views.py: class CookieTokenObtainPairView(TokenObtainPairView): def finalize_response(self, request, response, *args, **kwargs): if response.data.get("refresh"): # the cookie part works well # the part that doesn't is in the serializer below # tried to do the UserLoginSerializer(data=request.data) user = UserLoginSerializer.validate(data=request.data) if user.is_valid(): user = user.validate(data=request.data) response.data["user"] = user.data if user.is_valid() else user.errors else: response.data["user"] = user.errors return super().finalize_response(request, response, *args, **kwargs) serializers.py class UserLoginSerializer(serializers.HyperlinkedModelSerializer): password = serializers.CharField(style={"input type": "password"}, write_only=True) # class Meta: model = User fields = ( "id", "url", "username", "password", ) # read_only_fields = ("id") def validate(self, data): data["username"] = self["username"] data["password"] = self["url"] return super().validate(data) so as you can see the validate option is trying to get the username and the url data to return it, but I'm not finding a good way to get them each time it says that self doesn't have username value or something tried all of those variants: self.username self["username"] self.get["username"] self.get.username so whatever the good way to return the … -
Django makemigrations - No installed app with label '<appname>'
Beginner to Django Web Frameworks here...when I try to run python manage.py makemigration courses, it throws this error: $ python manage.py makemigrations courses ←[31;1mNo installed app with label 'courses'. Here is what I have in settings.py for INSTALLED_APPS INSTALLED_APPS = [ 'courses.apps', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] This is in my apps.py file: from django.apps import AppConfig class CoursesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'Courses' Here is what python manage.py showmigrations gives: $ python manage.py showmigrations ←[1madmin ←[0m [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices ←[1mauth ←[0m [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length ←[1mcontenttypes ←[0m [X] 0001_initial [X] 0002_remove_content_type_name ←[1msessions ←[0m [X] 0001_initial Also, why do I have these '←[31;1m' and '←[0m' symbols in the output on my terminal? I am using VSCode Thankyou! -
Django some css not working in production
I have a django app. In production I ran collectstatic and all good except a small piece of css. This css thing is a question mark which on hover shows some tips about the app feature. This also could be a nginx configuration issue maybe. But again, just this piece of css does not work properly. html <div class="help-tip"> <p> some text </p> </div> css /*------------------------- Inline help tip --------------------------*/ .help-tip-wrapper{ padding-top: 15px; padding-left: 5px; } .help-tip{ text-align: center; background-color: #BCDBEA; border-radius: 50%; width: 24px; height: 24px; font-size: 14px; line-height: 26px; cursor: default; } .help-tip:before{ content:'?'; font-weight: bold; color:#fff; } .help-tip:hover p{ display:block; -webkit-animation: fadeIn 0.3s ease-in-out; animation: fadeIn 0.3s ease-in-out; } .help-tip p{ display: none; background-color: #1E2021; padding: 20px; width: 300px; border-radius: 3px; right: -4px; color: #FFF; font-weight: normal; font-size: 10px; z-index: 100; line-height: 1.4; position: relative; } .help-tip p:before{ content: ''; width:0; height: 0; border:6px solid transparent; border-bottom-color:#1E2021; right:10px; top:-12px; } .help-tip p:after{ width:100%; height:40px; content:''; top:-40px; left:0; } settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' All css working fine except this one. -
I have an error: 'NoneType' object has no attribute 'price' error by rendering the template
I have these models: class Product(models.Model): name = models.CharField(max_length=200) category = models.CharField(max_length=300, choices=TOTAL) subcategory = models.CharField(max_length=300, choices=SUBPRODUCT) price = models.FloatField() image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total My views.py: def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'cartItems':cartItems, 'order':order, 'items':items} return render(request, 'store/store.html', context) It's my template: <div class="bottom"> <div class="total"> <span>Total</span> <span class="total-amount">${{order.get_cart_total|floatformat:2}}</span> </div> <a href="{ url 'checkout' }" class="btn animate">Checkout</a> </div> </div> As I mentioned above, I have this error: 'NoneType' object … -
after clearing cookies and other site data login with twitter is working
SOME of the clients are getting the following error while login in with Twitter. 403 Client Error: Forbidden for URL: https://api.twitter.com/oauth/request_token - can't sign in with Twitter The error does not come/resolved after clearing "Browser cookies and other site data". And in some of the client its work extremely good. So can you please help us out with the solution? We try all the troubleshooting, but it didn't resolve the problem. We are using this package pip install social-auth-app-django. -
Django: Provide count for related model's fields
I'm trying to design an API that would give me details about all models in the database with their fields and other statistics/count. These are the two related models: class Subject(models.Model): name = models.CharField() class Student(models.Model): name = models.CharField() join_year = models.IntegerField() graduate_year = models.IntegerField() strand = models.ForeignKey(Subject, on_delete=models.SET_NULL) This is how the API data for all Subjects is being generated at the moment: [ { "name": subject.name, "years": [ { "joined": Student.objects.filter(strand=subject).values("join_year").annotate(joined=Count("join_year")).order_by("join_year"), "graduated": Student.objects.filter(strand=subject).values("graduate_year").annotate(graduated=Count("graduate_year")).order_by("gradaute_year"), } ], } for subject in Subject.objects.all() ] This results in: [ "name": "Medicine", "years": [ { "joined": { "join_year": 2000, "joined": 123, }, "graduated": { "graduate_year": 2001, "graduated": 543 } }, { "joined": { "join_year": 2002, "joined": 123 }, "graduated": { "graduate_year": 2002, "graduated": 543 } } ] ] However, what I want is: [ "name": "Medicine", "years": [ { "year": 2000, "joined": 123, "graduated": 0, }, { "year": 2001, "joined": 0, "graduated": 543, }, { "year": 2002, "joined": 123, "graduated": 543, } ] ] -
running pinry inside docker on windows 10
I want to run a Pinry server on my local network so I can make pin boards in private. As per the instructions I installed docker and pulled the Pinry container: docker pull getpinry/pinry And then run it pointing to a local folder for it to store data docker run -d=true -p=8080:80 -v=c:\PinryData\:/data getpinry/pinry When I open a commandline inside the container, the file /data/local_settings.py already has the setting ALLOW_NEW_REGISTRATIONS = True. I see it running in docker but when I try to go to the localhost:8080 it does not respond. Why isnt Pinry running correctly / cant I access Pinry? I have not used any of the components (django, docker) before so it might be something simple. -
Custom validators in BaseSerializer
I want to use custom validators in BaseSerializer. First attempt: Custom validator: class UserIdExists: def __init__(self): self.MESSAGE_INCORRECT_USER = 'No user with this id.' def __call__(self, user_id): exists = User.objects.filter(id=user_id).exists() if not exists: message = self.MESSAGE_INCORRECT_USER raise serializers.ValidationError(message, code='invalid') and BaseSerializer: class QuestionBaseSerializer(serializers.BaseSerializer): def to_internal_value(self, data): user_id = data.get('user_id') user_validator = UserIdExists() user_validator(user_id=user_id) In case of a validation error, I received a message: '["No user with this id."]' But I would like to receive such a message: '{"user_id": "No user with this id."}' Second attempt: Custom validator: class UserIdExists: def __init__(self): self.MESSAGE_INCORRECT_USER = 'No user with this id.' def __call__(self, user_id, field=None): exists = User.objects.filter(id=user_id).exists() if not exists: if field: message = {field: self.MESSAGE_INCORRECT_USER} raise serializers.ValidationError(message, code='invalid') else: if not field: message = self.MESSAGE_INCORRECT_USER raise serializers.ValidationError(message, code='invalid') And BaseSerializer: class QuestionBaseSerializer(serializers.BaseSerializer): def to_internal_value(self, data): user_id = data.get('user_id') user_validator = UserIdExists() user_validator(user_id=user_id, field='user_id') I get the expected message: '{"user_id": "No user with this id."}' Am I doing the right thing? Can it be done more correctly? -
Social login in flutter
I'm trying to implement social login in my application, the front-end is built with Flutter and my backend with Django and Django rest framework. In flutter i'm using Google_sign_in package to connect users when i get access token i send it to the backend. after this i request informations of my user from google with the access token if the user exits in Django database i return authentication token if not i create new user and i return authentication token. My question is: is it safe or are there better ways to do it? -
I am unable to make migrations , its showing conflicting migrations
I cloned my proj from the repository to a different computer, but after DB restore now there are conflicting migrations, I have looked into other answers they have mentioned about chain dependency , i am having trouble understanding how will it fix this Below are my last 2 migration files class Migration(migrations.Migration): dependencies = [ ('orders', '0016_auto_20210817_1851'), ] operations = [ migrations.AlterField( model_name='placedorder', name='order_time', field=models.DateTimeField(auto_now_add=True), ), ] class Migration(migrations.Migration): dependencies = [ ('orders', '0016_merge_20210828_1519'), ('orders', '0017_alter_placedorder_order_time'), ] operations = [ ] Traceback (most recent call last): File "C:\Users\atifs\Documents\food_deliveryapp\fooddelivery\manage.py", line 22, in <module> main() File "C:\Users\atifs\Documents\food_deliveryapp\fooddelivery\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\commands\makemigrations.py", line 149, in handle loader.project_state(), File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\migrations\loader.py", line 335, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\migrations\graph.py", line 315, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\migrations\migration.py", line 89, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\migrations\operations\fields.py", line 162, in state_forwards old_field = model_state.fields.pop(self.name) KeyError: 'session_id' -
Django cannot serve files after moving to compose
Context Hi, we have a big project in Django. Up until now, we have used Vagrant to run it. Now, we have decided to move to a container and use docker compose. Everything has worked out fine except for the serving of static files. We have a directory called web where we have all our static assets. Inside there, there are more subdirectories with more static assets. Problem Right now static files are not being served. Is curious because only some files are being served. I think the ones from the web directory are not working for some reason. Current django config This config has worked well before moving to docker. # this is necessary because our settings file are stored inside a directoy PROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) PUBLIC_DIR = os.path.join(PROJECT_DIR, 'public') STATIC_ROOT = os.path.join(PUBLIC_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_DIR, 'web'), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) Additional information We are using django-1.11 and python 3.6.9. I know, it's not the latest. Compose configuration version: '3' services: web: image: "dev" container_name: web ports: - "8000:8000" volumes: - ./:/app depends_on: - db networks: - djangonetwork db: image: "postgres" container_name: db ports: - "5432:5432" networks: - djangonetwork networks: … -
Django music player not working in Heroku
I have a music player inside a django app, that uses js to fetch track url links from an api, the track files are uploaded into a AWS S3 bucket, when the app runs locally it works fine when loading tracks but after deployed to Heroku the tracks don't load, the music player just seems to be stuck on loading. Not sure what could be wrong? It may be something to do with the communication between AWS and Heroku, but not 100% sure, would appreciate some experienced advice. -
Django template: not showing product if the product has already been shown
Really sorry about the disturbing title, my case is a bit tricky to explain (and i'm not that good in english). I'll try to do my best. I have a django app where users can save paired food products - the first is the "product_to_substitute" and the second one is the "substitute_product". But the thing is that the "product_to_substitute" can actually have multiples "substitute_product". Here is what my "favorites" DB table can looklike (numbers are products IDs) : product_to_substitute_id substitute_product_id 3 5 3 50 3 45 58 124 12 98 So what I would like to do on my favorites html page is to show one section with the "product_to_substitute" and a second section that shows all the "substitute_product" that are paired with the "product_to_substitute". Here is a little bit of my code: {% for product in favorites %} {% if product.product_to_substitute %} ### Block where I want to show only once the product to substitute ### <section style="background-image: url('{{ product.product_to_substitute.image_url }}')"> ... </section> ### Block where I want to show all the substitutes products that are paired with the product to substitute ### <section> <img class="img-fluid" src="{{ product.substitute_product.image_url }}" alt="..." /> </section> {% endif %} {% endfor %} By … -
Javascript can't find static files passed on from Django template
I have an issue with passing on my css files to javascript code. I tried using the answer from Django {% static 'path' %} in javascript file however it seems not to work for me. I basically have a script, seen in the first picture who sets some colors based on css files. In order to provide access to these files I added the variables seen in a script tag as the answer from the mention question suggests, the second picture and use them in the script itself. In the tag I call the {% load static %} command, and the files have been collected with load static and I can see them in the root folder. When I try to use them in my website however, I get a 404 error "/PersonalWebsite/css/color/*.css not found". Any suggestions what's going wrong? -
Search controller is fetching the wrong template in Django
I'm trying to write the controller to search for articles. But the search does not find anything and a template appears that is not specified in the views.py. # views.py class SearchView(ListView): template_name = 'search_view.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Article.objects.filter(Q(title__icontains=query)) return object_list # urls.py urlpatterns = [ ... path('search/', SearchView.as_view(), name='search_view'), ] #search_view.html {% extends 'layout/basic.html' %} {% block content %} {{ object_list }} {% endblock %} The form looks like this <form action="{% url 'articles:search_view' %}" method="get"> <input type="text" name="q" placeholder="Search..."> </form> What am I doing wrong? -
Django Calculations within Model.py don't update without a Server Reset
I have a few calculations within my Models file. The premise of this is that I have a 'rate' which is updated on a weekly basis, and this has an impact upon 2/3 columns within my eventual HTML table. I bring forward the latest rate as such: class Hedge_rate(models.Model): id = models.IntegerField(primary_key=True) Hedge_rate = models.DecimalField(max_digits=10, decimal_places=5) def __str__(self): return "%s" % (self.Hedge_rate) V = Hedge_rate.objects.all().first() latest_rate = V.Hedge_rate Then, my primary calculations are as follows: @property def spot_amount(self): return self.usd_amount/latest_rate The problem I am facing is that, let's say the "latest rate" is current "2" - If I then update this figure to "5", the numbers within the calculation (as well as if I 'print' Latest Rate') will remain as if the Latest rate is still 2. It only updates to 5 upon a server reset. I suspect this is some sort of Caching issue? Is there a way I can trigger a cache 'wipe' upon each form submission when updating the rate? What is the best way to resolve this? -
Heroku django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
I am trying to run a django command on my heroku production server, but get the following error: Note: The same command works fine in my local dev environment. I took the following steps: ssh onto my django server: heroku ps:exec -a library-backend I run my custom command: python manage.py test_command Receive error above My environment variables are set in my settings.py as follows: import environ # Setting environment variables env = environ.Env(DEBUG=(bool, False)) environ.Env.read_env() DEBUG = env('DEBUG') SECRET_KEY = env('SECRET_KEY') DATABASE_URL = env('DATABASE_URL') My django app runs normally on the heroku server. I am only getting this error when I try to run a custom django management command. Can anyone see where I'm going wrong? For reference, the management command is specified in library/management/commands/test_command.py: from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): print("Testing management command") -
Facebook Final Check For Login
I have created a django app where i am checking that my social login for facebook is workingor not. When i click on my Facebook Button from Frontend its not getting login i am facing security connection problem though i have used ngrok link for creating a secure tunnel but still i am unable to login .. i am using django-all-auth library settings.py ALLOWED_HOSTS = ["582b-2405-201-a006-70b4-35e2-8cb3-b7e2-b9ec.ngrok.io"] LOGIN_REDIRECT_URL= 'dashboard' settings for facebook login inside the installed apps 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.twitter' site_id SITE_ID = 12 urls.py for django-all-auth path('socialaccounts/', include('allauth.urls')), register.html {% load socialaccount %} {% providers_media_js %} <a href="{% provider_login_url 'facebook' method='oauth2' %}" class="btn btn-primary form-btn w-100 mt-3">Facebook</a>`r code here images This is the error i am getting Provided a Valid OAuth Redirect URIs Basic settings for app inside facebook developers page -
Django no movie found matching the query
Hello i have this error , what is problem ? can not find Models.py # Create your models here. CATEGORY_CHOICES = ( ("A","ACTION"), ("D","DRAMA"), ("C","COMEDY"), ("R",'ROMANCE'), ) LANGUAGE_CHOICES = ( ("EN","ENGLISH"), ("GR","GERMAN") ) STATUS_CHOICES = ( ("RA","RECENTLY ADDED"), ('MW','MOST WATCHED'), ("TR",'TOP RATED'), ) class Movie(models.Model): title = models.CharField(max_length=100) title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) image = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES,max_length=1) language = models.CharField(choices=LANGUAGE_CHOICES,max_length=3) status = models.CharField(choices=STATUS_CHOICES,max_length=2) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) def __str__(self): return self.title Link_choice = ( ("D","Download LINK"), ("W","WATCH LINK"), ) class Movielinks(models.Model): movie = models.ForeignKey(Movie,related_name="movie_watch_link",on_delete=models.CASCADE) type = models.CharField(choices=Link_choice,max_length=1) link = models.URLField() def __str__(self): return str(self.movie) and this is views.py , what is problem? Views.py from django.views.generic import ListView,DetailView from .models import Movie,Movielinks class MovieList(ListView): model = Movie template_name = 'index.html' class MovieDetail(DetailView): model = Movie def get_object(self): object = super(MovieDetail,self).get_object() return object def get_context_data(self, **kwargs): context = super(MovieDetail,self).get_context_data(**kwargs) context["links"] = Movielinks.objects.first(movie=self.get_object()) return context i try everything but not working , when i change MovieDetail class as ListView working, but do not need this , error ; No movie found matching the query No movie found matching the query No movie found matching the query No movie found matching the query No movie found matching the query …