Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to prevent Throttling issue with celery workers?
I want to build script to pull data from amazon api, interesting thing in amazon api that they have strict Throttling rules by different endpoints, e.g.: Maximum request: quota 30 requests Restore rate: One request every two seconds Hourly request quota: 1800 requests per hour So for one account we can do 30 requests at one time without throttling, but not more than 1800 per hour. Restore rate means - that after we did 30 requests at once we have to wait 60 seconds(2 seconds * 30 request) to make again 30 requests at once. First I wanted to implement that with celery, but in this case need to use global lockers, which seems isn't best solution, and hard to maintain. In nodejs worlds we can use something like https://www.npmjs.com/package/bottleneck. const limiter = new Bottleneck({ maxConcurrent: 1, minTime: 333 }); limiter.schedule(() => myFunction(arg1, arg2)) .then((result) => { /* handle result */ }); Any similar libs in python, or maybe just good suggestion how to implement that, with ability to monitor, and reschedule if fail. -
Why i am see server error 500 in my website when Debug = False in django
I am see Server Error 500 in my website [www.softdlr.com] after i make Debug = Flase in settings.py this problem appear when i do search in other language ( except English ) when i use contact form how to fix this error (My priorities is to fix the contact form that i using gmail ) forms.py # contact form class ContactForm(forms.Form): contact_name = forms.CharField(required=True,label='Your name ') contact_email = forms.EmailField(required=True,label='Your email ') title = forms.CharField(required=True,label='The Subject') content = forms.CharField(required=True,label='Full Deatils ',max_length=500,widget=forms.Textarea(attrs={"rows":5, "cols":30}) ) views.py from django.core.mail import send_mail from first_app import forms from django.shortcuts import render from .forms import ContactForm from django.core.mail import EmailMessage # Contact form view def contact(request): Contact_Form = ContactForm if request.method == 'POST': form = Contact_Form(data=request.POST) if form.is_valid(): contact_name = request.POST.get('contact_name') contact_email = request.POST.get('contact_email') contact_content = request.POST.get('content') title = request.POST.get('title') template = loader.get_template('html_file/contact_form.txt') context = { 'contact_name' : contact_name, 'contact_email' : contact_email, 'title' : title, 'contact_content' : contact_content, } content = template.render(context) email = EmailMessage( "New contact form email", content, "Creative web" + '', ['myemail@gmail.com'], headers = { 'Reply To': contact_email } ) email.send() return redirect('Success') return render(request, 'html_file/contact_us.html', {'form':Contact_Form }) settings.py # email message contact EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST= 'smtp.gmail.com' EMAIL_HOST_USER= 'myemail@gmail.com' EMAIL_HOST_PASSWORD= 'mypass' EMAIL_USE_TLS= True … -
I want to beat goggle search which framework should i use django or flask
I wanted to create a search engine better than google. I did some research and found that search engine uses machine learning and deep learning, python is best at it. So i have chosen python but now which framework to use django or flask -
I want to get data based on header menu from the same table
Here is my code: models.py class HeaderMenu(models.Model): header_menu = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.header_menu class SubMenu(models.Model): header_menu = models.ForeignKey(HeaderMenu, on_delete=models.CASCADE) sub_menu = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.sub_menu class Category(models.Model): sub_menu = models.ForeignKey(SubMenu, on_delete=models.CASCADE) category = models.CharField(max_length=150, primary_key=True) def __str__(self): return self.category class Links(models.Model): header_menu = models.ForeignKey(HeaderMenu, on_delete=models.SET_NULL, null=True) sub_menu = models.ForeignKey(SubMenu, on_delete=models.SET_NULL, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) link_name = models.CharField(max_length=255) link_url = models.URLField() hits = models.IntegerField() def __str__(self): return self.link_name The table in my database: table whole data My requirement: let say there are 5 links in link_url under sports category under Home tab I want to render all the link name under the home(header_menu) > sports(category) > links like > home> home Submenu > Sports > and all the links name not whole table Help me out to write the view for this problem Thanks :) -
KeyError at /recommend/ in combined_features
why I am getting this error in combined features why this appears and show why df or local variables assigned def recommendation(Movie): Movie = Movie.lower() try: df.head() cosine_sim.shape except: cosine_sim = recommender_sim() if Movie not in df['title'].unique(): return('Search for another Movies') else: indices = pd.Series(df.index, index=df['title']) # Get the index of the movie that matches the title idx = indices[title] # Get the pairwsie similarity scores of all movies with that movie sim_scores = list(enumerate(cosine_sim[idx])) # Sort the movies based on the similarity scores sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) # Get the scores of the 10 most similar movies sim_scores = sim_scores[1:11] sim_scores = [] for i in range(len(sim_scores)): movie_indices = sim_scores[i][0] sim_scores.append(df['title'][movie_indices]) return sim_scores def recommend(request): if request.method == 'GET': movie = request.GET['movie'] movies = recommendation(movie) movie = movie.upper() if type(movies) == type('string'): return HttpResponse('recommend.html', movie=movie, movies=movies, t='s') else: return HttpResponse('recommend.html', movie=movie, movies=movies, t='sim_scores') return render(request, 'recommend.html') -
How to convert geojson file into class model in django
I have geojson data in the URL. Here is the URL: https://publoccityhealthdata.s3.us-east-2.amazonaws.com/chi_boundries.geojson I need to generate model class for Django using ogrinspect from django.contrib.gis.db import models -
How to return custom sql query that goes through the serializer in django
I am running a custom query through a serializer in Django so that I can use the data on the frontend. The serializer however returns the full objects or records from the database. How can I have it return only the fields that I want it to return as indicated in my query? views.py from .models import Property from .serializers import PropertySerializer from rest_framework import generics from django.views.generic.list import ListView from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status # class PropertyListCreate(generics.GenericAPIView): @api_view(['GET', 'POST']) def propertyListCreate(request): if request.method == 'GET': properties = [] # properties = Property.objects.all() properties = Property.objects.raw("SELECT id as 'id', suburb, COUNT(*) FROM properties_property group by suburb") serializer = PropertySerializer(properties,context={'request': request} ,many=True, read_only=True) return Response({'data': serializer.data}) models.py from django.db import models class Property(models.Model): Title = models.CharField(max_length=255) Price = models.IntegerField() Area = models.FloatField() Bedrooms = models.FloatField() Bathrooms = models.FloatField() Parking = models.FloatField() Suburb = models.CharField(max_length=255) Address = models.CharField(max_length=255) Link = models.CharField(max_length=255) Date = models.CharField(max_length=255) serializers.py from rest_framework import serializers from .models import Property class PropertySerializer(serializers.ModelSerializer): class Meta: model = Property fields = ('id', 'Title', 'Price', 'Area', 'Bedrooms', 'Bathrooms', 'Parking', 'Suburb', 'Address', 'Link', 'Date') Output that I am receiving: The desired output would be the following: -
'User' object has no attribute 'is_staff' Django
i am getting an AttributeError while creating superuser for my model, that's showing AttributeError at /admin/login/ it would be great if anybody could help me out where i am doing thing wrong. thank you so much in advance. here below is my working code; models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=50) last_name = models.CharField(_('last name'), max_length=50, blank=True) avatar =models.ImageField(upload_to='avatar' , blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] managers.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('email must me set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Super User must have is_superuser=True') return self._create_user(email, password, **extra_fields) -
Using Ajax to receive total amount due before submitting to database
Trying to use Ajax to calculate and display the sum before I submit anything to the database. At the moment this is what I have, but I can't seem to get anything to display. I'm trying to start small and see if I'm even able to display the values in the fields.. Is my view for final_price wrong? Or did I mess up somewhere in the Jquery? I'm still new to Ajax, so I'm not sure where I went wrong (following tutorials) Book Price: $10 (input field) Delivery charge: $3 (input field) Delivery type: $5 (input field) [calculate] [submit] Final Result: $18 (result of adding the fields above when user clicks the calculate button) calculate button will display $18 submit button will finalize the results and send the values to the database. This is my model for the table class book(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) book_price = models.IntegerField() delivery_charge = models.IntegerField() delivery_type = models.IntegerField() final_result = models.IntegerField() def save(self, *args, **kwargs): self.final_result = self.book_price + self.delivery_charge + self.delivery_type print(self.final_result) super(book, self).save(*args, **kwargs) views.py for the form def final_price(request): response_data = {} if request.method == 'POST': form = RequestForm(request.POST) book_price = request.POST.get('book_price') delivery_charge = request.POST.get('delivery_charge') delivery_type = request.POST.get('delivery_type') response_data['book_price'] … -
Get profile from user's foreign key django
I am trying to get my customer's details but, having issues filtering it in the serial from the foreign key Customer. Here is what I have now: Serializers: class CustomerOrderSerializer(serializers.ModelSerializer): customer = OrderCustomerSerializer() class Meta: model = CustomerDetails fields = ('id', 'current_selfie', 'customer', 'phone') class OrderSerializer(serializers.ModelSerializer): customer= OrderCustomerSerializer() driver = OrderDriverSerializer() dispensary = OrderDispensarySerializer() order_details = OrderDetailSerializer(many=True) status = serializers.ReadOnlyField(source="get_status_display") customer_details = CustomerOrderSerializer.OneToOneField(customer, related_name='customer_details') class Meta: model = Order fields = ("id", "customer", "customer_details", "dispensary", 'delivery_signature', 'order_rated', "driver", "order_details", "total", "status", "address", "created_at") Model class Order(models.Model): a = 1 b = 2 c = 3 d = 4 e = 5 STATUS_CHOICES = ( (a, "ah"), (b, "bb"), (c, "cc"), (d, "dd"), (CANCELED, "Canceled/Refunded") ) address = models.CharField(max_length=500) created_at = models.DateTimeField(default=timezone.now) customer = models.ForeignKey(CustomerDetails, on_delete=models.CASCADE) delivery_signature = models.ImageField( upload_to='delivery_selfie/', blank=True, default='') delivered_at = models.DateTimeField(default=timezone.now) dispensary = models.ForeignKey(Dispensary, on_delete=models.CASCADE) driver = models.ForeignKey( Driver, blank=True, null=True, on_delete=models.CASCADE) picked_at = models.DateTimeField(default=timezone.now) order_rated = models.BooleanField(default=False) status = models.IntegerField(choices=STATUS_CHOICES) total = models.FloatField() def __str__(self): return str(self.id) class CustomerDetails(models.Model): age = models.IntegerField(default="21", blank=True) address = models.CharField( default='', max_length=254, null=True, blank=True) nick_name = models.CharField(max_length=500, blank=True) average_order = models.FloatField(default="0.0", blank=True) completed_orders = models.IntegerField(default="0", blank=True) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name='customer') customer_type = MultiSelectField( choices=CUSTYPE, default=CUSTYPE, max_length=100) current_selfie = … -
Django API Log to LogStash
I am working on an API in Django and when the API call is finished, we need to log that data using the ELK stack. Here the Setup is Done Properly as I can see new logs showing up in the Logstash but not in Filebeat using which we push the Data to Kibanna. I am uploading screenshots for the configuration file and other details here. Please be Patient Code Segment from Django logger = logging.getLogger(__name__) logging.config.dictConfig( { "version": 1, "disable_existing_loggers": False, "formatters": { "console": {"format": "%(name)-12s %(levelname)-8s %(message)s"}, "file": {"format": "%(asctime)s %(levelname)s-%(message)s"}, }, "handlers": { "console": {"class": "logging.StreamHandler", "formatter": "console"}, "file": { "level": "DEBUG", "class": "logging.FileHandler", "formatter": "file", "filename": "/home/dhruv/elk_log/debug.log", }, }, "loggers": {"": {"level": "DEBUG", "handlers": ["console", "file"]}}, } ) # Create your views here. class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_data = request.data["file"] decoded_file = file_data.read().decode("utf-8").splitlines() file_serializer = FileSerializer(data=request.data) print("File data is", request.data["file"]) read_data = csv.DictReader(decoded_file) # s = smtplib.SMTP("smtp.gmail.com", 587) # s.starttls() id, password = settings.GMAIL_ID, settings.GMAIL_PASSWORD print(f"The gmail id and password is {id} {password}") # s.login(id, password) # Reading the Data as for item in read_data: # print(item) print( item["Email ID"], item["To"], item["cc"], item["bcc"], item["subject "], item["body"], ) # msg … -
how to create a django project using pycharm terminal
I created a project in the pycharm called pyshop. After that I downloaded the django 2.1 in my pycharm terminal. Then i went to create a project using the terminal of the pycharm. But it is showing an error like: (venv) C:\Users\shan\PycharmProjects\PyShop>django-admin startproject pyshop. CommandError: 'pyshop.' is not a valid project name. Please make sure the name is a valid identifier. what should i give as a valid identifier ? -
Service makemigrations has neither an image nor a build context specified
Hello I am trying to make workable a project. But when I run the following instruction : docker-compose up I got the following error : ERROR: The Compose file is invalid because: Service makemigrations has neither an image nor a build context specified. At least one must be provided. Here is the yml file docker-compose.yml : version: '3' services: db: image: postgres expose: - "5432" environment: - "POSTGRES_HOST_AUTH_METHOD=trust" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/myproject/ ports: - "8000:8000" - "3000:3000" depends_on: - db - makemigrations - migrations makemigrations: command: python manage.py makemigrations --noinput volumes: - .:/myproject/ depends_on: - db migrations: command: python manage.py migrate --noinput volumes: - .:/myproject/ depends_on: - db Could you help me please ? -
I want to group by the same date the errors (in django models)
I want to group together the errors that had been created on the same date class Error(models.Model): # Audit fields created_on = models.DateTimeField(auto_now_add=True) @classmethod def update_repeat_count(cls, app_error: 'Error'): # Sí el error es del mismo día que agrupe los errores sino nada if app_error.created_on.datetime.date[0] == app_error.created_on.datetime.date[1]:#I am not sure if the "if" is right because I can't try it in develop cls.objects.filter(pk=app_error.pk).update(repeat_count=F('repeat_count') + 1) app_error.repeat_count += 1 post_save.send(sender=cls, instance=app_error, created=False, update_fields=('repeat_count',)) Lots of thx for hellping me -
How can I use template blocks in django?
I'm trying to load a header template into my index with {% block %} but I can't get it to load index.html <body> <header> {% block header %}{% endblock %} </header> <h1>Hello</h1> </body> header.html {% extends "index.html" %} {% block header %} <div class="header"> <a href="/category/"><i class="fas fa-archive"></i></a> <a href="../"><i class="fas fa-home"></i></a> <h1>hey</h1> </div> {% endblock %} views.py def index(request): categories = Category.objects.all() context = {'categories': categories} return render(request, 'category/index.html', context) The app is installed in the settings. -
Django join models based on unique key
I have a situation where I can't join models based on foreign key. I want to join them based on common key that is basically foreign key to third table. Have a look at code: class Thread(models.Model): timestamp = models.DateTimeField(default=datetime.now) class Chat(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) message = models.CharField(max_length=2000) thread = models.ForeignKey(Thread, on_delete=models.CASCADE) read = models.BooleanField(default= 0) timestamp = models.DateTimeField(default=datetime.now) class User_Thread(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE) reciever = models.ForeignKey(User, related_name='reciever', on_delete=models.CASCADE) I want to join Chat and User_Thread models based on same thread. How can I achieve this? Any thoughts? -
MultiValueDictKeyError - stripeToken Django error
the error message i am receiving in my template is --MultiValueDictKeyError at /checkout/ 'stripeToken'-- I can't seem to find a solution anywhere online. i have highlighted areas in the code where stripeToken occurs. Any suggestions would be appreciated as I am stuck on this for quite some time now! views.py import time import stripe from django.contrib.auth.decorators import login_required from django.conf import settings from django.shortcuts import render, HttpResponseRedirect from django.urls import reverse # Create your views here. from users.forms import UserAddressForm from carts.models import Cart from .models import Order from users.models import Profile, UserAddress, UserAddressManager from .utils import id_generator try: stripe_pub = settings.STRIPE_PUBLISHABLE_KEY stripe_secret = settings.STRIPE_SECRET_KEY except Exception as e: raise NotImplementedError(str(e)) # stripe_pub = "pk_test_AueCfYJ1QIxjLej496MIA43t00BNIWgUb6" stripe.api_key = stripe_secret def orders(request): context = {} template = "orders/user.html" return render(request, template, context) @login_required def checkout(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse("cart")) try: new_order = Order.objects.get(cart=cart) except Order.DoesNotExist: new_order = Order() new_order.cart=cart new_order.user = Profile.objects.get(user=request.user) # new_order.user = Profile.objects.get(user=request.user) new_order.order_id = id_generator() new_order.save() except: return HttpResponseRedirect(reverse("cart")) try: address_added = request.GET.get("address_added") except: address_added = None if address_added is None: address_form = UserAddressForm() else: address_form = None current_addresses = UserAddress.objects.filter(user=request.user) billing_addresses = UserAddress.objects.get_billing_addresses(user=request.user) # if 'stripeToken' in request.POST: … -
Cannot upload photo to Django With Rest Framework
I am attempting to make a request to upload a photo and change one text field. When I call my api, I get an error: . This is what I am trying: @csrf_exempt def driver_complete_order(request): # Get token driver = CustomJWTAuthenticator().authenticate(request)[0].driver # driver = access_token.user.driver print(request.POST) order = CompletedOrderSerializer(Order.objects.get( id=request.POST['order_id'] )) order.status = Order.DELIVERED order.delivery_signature = request.FILES['delivery_signature'] if order.is_valid(): order.save(commit=False) print(order.validated_data) order.save() return JsonResponse({"status": "success"}) When I attempt to upload a delivery signature I get a "django.utils.datastructures.MultiValueDictKeyError: "'order_id'" but, when I print the value, I get <QueryDict: {'access_token': ['eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODg2MDcyMDUsInVzZXJfaWQiOjI2MSwidG9rZW5fdHlwZSI6ImFjY2VzcyIsImp0aSI6IjUwZmYzOGVmYjNlNzQ1YTdhYmNhN2QyYmM3YTg2ZDg4In0.kxUNYcQ99xSOwMBw1g6rZtwuF1BLM5YrGY5-ykUlzq0'], 'order_Id': ['9'], 'delivery_signature': ['iVBORw0KGgoAAAANSUhEUgAAAY4AAAM4CAYAAADbCAU9AAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAUPSURBVHic7cEBDQAAAMKg909tDjegAAAACAVwMIpAABbE5p6AAAAABJRU5ErkJggg==']}> So I know there is data hitting the server. Not sure why it will not let me upload the data. -
Django url showed error: unresolved reference
I have a url path in urls.py: urlpatterns = [ ... url(r'^accounts/', include('allauth.urls')), ... ] but the url will show: unresolved reference 'url'. Did I miss something to import? -
Separate AJAX Forms on Single Django View
I'm not using Django's built in forms to display the form: Inside view.html is: <div> <form id="note-form" method="POST"> {% csrf_token %} <input type="hidden" name="form_name" value="noteForm" /> <textarea id="note-body" class="uk-textarea" style="resize: none;"></textarea> <button type="submit" class="uk-button uk-button-primary uk-button-small uk-margin-small-top">Add Note</button> </form> </div> Inside veiw.py is: if request.POST.get('action') == 'post': note_body = request.POST.get('note_body') response_data.update(note_author = request.user.first_name + ' ' + request.user.last_name) response_data.update(note_time = datetime.now().strftime('%B %m, %Y at %I:%M %p')) response_data['note_body'] = note_body Note.objects.create(item_id = id, body = note_body, author = request.user) return JsonResponse(response_data) Inside view.js is: $(document).on('submit', '#note-form', function(event) { event.preventDefault() $.ajax({ type: 'POST', data: { note_body: $('#note-body').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function(json) { document.getElementById("note-form").reset(); $('#notes').prepend( '<div>' + json.note_body + '<div class="uk-text-meta">Created by ' + json.note_author + ' on ' + json.note_time + '</div>' + '</div>' ) }, error: function(xhr, errmsg, err) { console.log(xhr.status + ": " + xhr.responseText); } }); }); This works, and it works like a well-oiled dream, until I attempt to add another form to the page. I need a way, using this existing code (or as much as it as possible), to separate the POSTs and I can't figure it out. I've attempted to change my view.py to incorporate a hidden field: if request.method == 'POST': … -
Creating dynamic choice field in Django forms, based on a view
I have been stuck for a while on this rather simple yet complicated task. Its actually a bit difficult to describe the problem, so hopefully you'll bare with me. I have these 3 models: class Subject(models.Model): batch = models.CharField(choices=LEVEL_CHOICES, max_length=2) subject_name = models.CharField(max_length=50) ... class StudentRegistration(models.Model): subject = models.ManyToManyField(Subject) ... class Season(models.Model): season = models.CharField(max_length=2, primary_key=True) subject = models.ManyToManyField(Subject) running = models.BooleanField(default=False) I want to create a StudentRegistration form for a certain Subject on a certain Season. For this I have first created a form where the user selects the Season and the batch. The view looks like this: def admission(request): if request.method == 'POST': form = DeterminingForm(request.POST) if form.is_valid(): selected_season = form.cleaned_data['season'] selected_batch = form.cleaned_data['batch'] form = DeterminingForm() After this I want to create the StudentRegistration form, where the user will have the option to select the subject(s) that are available for that selected_season and selected_batch. I have created a ModelForm for this, but I don't know how to query the database by taking the value form the view into the form, and display the available options in the choicefield (or any other field that is applicable). Currently all I have for that is this form: class StudentRegistrationForm(forms.ModelForm): class … -
Weasyprint or Reportlab for generating Django reports on Heroku
Trying to decide on the best route for generating server-side pdf reports within my app currently deployed on Heroku. I've read several posts that say both require installation external libraries- but haven't found anything describing functionality & ease of install on Heroku. Does anyone here have experience installing either to an app on Heroku? Is it a difficult process- is one easier to setup on Heroku than the other? Or if I am able to install on my local system and run PIP Freeze, will that take care of any installs necessary on Heroku? Thanks!! -
how fix docker when goes to restarting status after docker-compose in django on ubuntu
I use postgresql and docker in my django project. after docker-compose my container goes to restarting status. I tried fix it by stop and remove but didn't work docker-compose.yml: version: '3' services: blog_postgresql: image: postgres:12 container_name: blog_postgresql volumes: - blog_postgresql:/var/lib/postgresql/data restart: always env_file: .env ports: - "5432:5432" networks: - blog_network volumes: blog_postgresql: external: true networks: blog_network: external: true and terminal show this: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e8aa3e604ba3 postgres:12 "docker-entrypoint.s…" 3 days ago Restarting (126) 14 seconds ago blog_postgresql -
Is django-CMS and cookiecutter-django compatible?
I just tried to port my Django-CMS project into Django Cookiecutter (cookiecutter-django) in ordert to get it to run in Docker. It seems Django-CMS is using the default Django user model and Cookie-Cutter is using a custom model (from allauth?). I found this https://github.com/pydanny/cookiecutter-django/pull/248 thread and it suggests changing the order in which the apps are loaded but that doesn't cut the mustard. Are Django-CMS and Cookiecutter at odds with each other? -
ValueError at /checkout/ The view accounts2.views.CheckoutView didn't return an HttpResponse object. It returned None instead
Can anyone please help me fix this error? I'm trying to develop an e-commerce website using Django. Why is this error being thrown? It's in my views.py. But what's the problem actually and what does this error mean? My accounts2.views.py: class CheckoutView(View): def get(self, *args, **kwargs): the_id = self.request.session['cart_id'] cart = Cart.objects.get(id=the_id) form = CheckoutForm() context = {"form": form, "cart": cart} return render(self.request, "orders/checkout.html", context) def post(self, *args, **kwargs): form = CheckoutForm(self.request.POST or None) try: the_id = self.request.session['cart_id'] cart = Cart.objects.get(id=the_id) order = Order.objects.get(cart=cart) except Order.DoesNotExist: order = Order(cart=cart) order.cart = cart order.user = self.request.user order.order_id = id_generator() order.save() if form.is_valid(): street_address = form.cleaned_data.get('street_address') apartment_address = form.cleaned_data.get('apartment_address') country = form.cleaned_data.get('country') zip = form.cleaned_data.get('zip') # same_shipping_address = form.cleaned_data.get('same_billing_address') # save_info = form.cleaned_data.get('save_info') payment_option = form.cleaned_data.get('payment_option') billing_address = BillingAddress( user = self.request.user, street_address = street_address, apartment_address = apartment_address, country = country, zip = zip ) billing_address.save() order.billing_address = billing_address order.save() return redirect('checkout') messages.warning(self.request, "Failed checkout") return redirect('checkout') except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect('/')