Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Execute R scripts through Django hosted on AWS (Elastic Beanstalk)
I am currently building a project that uses Django Web Framework (hosted on AWSEB) but also needs to execute some R scripts. I have tried using subprocess.call(["Rscript", "R_django_test.R"]) but I get the following error "No such file or directory: 'Rscript': 'Rscript'". The code above works locally, but not on the project hosted on AWS. Any help would be greatly appreciated. -
How to send a email for user to sign up in django
I have been trying to search on google and stack overflow but can not seem to find what i'm looking for. In my django web app i would like users to signup with email invite only. I don't want just anyone to sign up. How would I go about doing this. Any help would greatly be appericated. -
Template in Flask vs Django
This is my code: {% for x in range(0,3) %} {% if x == 0 %} {% set YCode = "STAGE01" %} {% set stStage = "First Stage" %} {% elif x == 1 %} {% set YCode = "STAGE02" %} {% set stStage = "Second Stage" %} {% elif x == 2 %} {% set YCode = "STAGE03" %} {% set stStage = "Third Stage" %} {% endif %} <h3>{{ stStage }}</h3> {% for Product in dsStages %} {% if Product.3 == YCode %} <p>{{ Product.4 }}</p> {% endif %} {% endfor %} <br> {% endfor %} This works in a Flask (Jinja2) Template, but it doesn't work in a Django template ... How should it be done in Django? Thanks. -
not able to use cache in django python
i want to cache in django so I am using low level API caching but even after adding it shows none >>> from django.core.cache import cache >>> cache.set('my_key', 'hello, world!') >>> cache.get('my_key') >>> print(cache.get('my_key')) None >>> in my settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } even when i use cache.add('my_key', 'hello, world!', 30) it return false -
TemplateSyntaxError at /classes/aerobics/ Invalid block tag on line 6: 'set', expected 'endblock'. Did you forget to register or load this tag?
I'm trying to render a page using a for loop to show video objects over 3 columns on the page until there are no more videos to display Why am I getting this error? What tag do I register/load for this to work? what is wrong with this line ({% set count = 0 %}) on line 6? I believe I have the {% endblock %} in the correct spot(last line). Should there be another one? views.py @login_required def classes_aerobics(request): obj = Video.objects.filter(category='Aerobics') return render(request, 'clubex/aerobics.html', {'obj': obj }) aerobics.html {% extends "ClubEx/base.html" %} {% load embed_video_tags %} {% block content %} {% set count = 0 %} {% for i in obj.all %} {% if count == 0 %} <div class="row"> {% endif %} <div class="col-md-4"> <div class="thumbnail"> <div class="caption"> {% video i.video 'tiny' %} <p>{{ i.content }}</p> <div class="rw-ui-container"></div> </div> </div> </div> {% set count = count + 1 %} {% if count == 3 %} </div> {% set count = 0; %} {% endif %} {% endfor %} {% endblock%} Traceback error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/classes/aerobics/ Django Version: 2.2.5 Python Version: 3.8.2 Installed Applications: ['ClubEx.apps.ClubexConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'embed_video'] … -
how do i redirect to user profiles upon signup with django
I am trying to redirect users to their profiles once they sign up. i can't figure out how the url should be, should be written the same way it is in the urls.py or modified? i read some articles and they talked of using a reverse lazy argument, i am not sure that would work. my current profile url uses a slug field that contains the last name and surname. views.py def addpatient(request): form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.first_name = form.cleaned_data.get('first_name') user.profile.last_name = form.cleaned_data.get('last_name') user.is_active = True user.save() user.profile.id=pk username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') messages.success(request, 'Account was created for ' + username) user = authenticate(username=username, password=password) login(request, user) return redirect('profile/<str:slug>/<int:pk>') else: form = SignUpForm() return render(request, 'core/signup.html', {'form': form}) models.py class Profile(models.Model): username = models.CharField(max_length=50, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) last_name = models.CharField(max_length=100, blank=True) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) slug = models.SlugField(max_length=200,null=True) def save(self, *args, **kwargs): self.slug = slugify(f"{self.last_name}-{self.first_name}") super(Profile, self).save(*args, **kwargs) urls.py urlpatterns = [ path('profile/', profile, name='profile'), path('profile/<str:slug>/<int:pk>', profile, name='profilepk') -
Django form inheritance with Crispy Forms
I am trying to handle a form in Django in a more DRY way. I am using Django Crispy Forms to lay out and render the forms. I have a model: class Txn(models.Model): transaction_date = models.DateField() reference = models.CharField(max_length=12) arrived = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) used = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) sent= models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) adjust = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) For each of the 4 number fields (arrived, used, sent, adjust), I have a form that exposes just one of those fields. (BTW, this is based on a model that was inherited from another project - I know there are better ways to structure this, but I have to use this structure). So, I created 4 forms that look very similar: class TxnUseForm(forms.ModelForm): class Meta: model = Txn fields = ('transaction_date', 'reference', 'used') def __init__(self, *args, **kwargs): super(TxnUseForm, self).__init__(*args, **kwargs) # Layout definition for the form self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Row( Column(Field('reference', autocomplete="off", autofocus="autofocus"), css_class='form-group col-sm-4 mb-0 pb-0'), Column(Field('transaction_date'), css_class='form-group col-sm-4 mb-0 pb-0'), Column(Field('used', step='1'), css_class='form-group col-sm-4 mb-0 pb-0') ) ) # Validation for amount used - must be a positive number def clean_used(self): data = self.cleaned_data['used'] if data is None or data … -
Django - override model's default value in ModelForm
I'm trying to figure out how to override the (showing of the) default value that is provided on a model field. It seems using the 'placeholder' attribute does not work. I have an optional field that I want to present in a form, but if a user does not enter something then the default value should be stored in the database. However, I also don't want to present that default value to the user in the form. Assume: class SomeModel(models.Model): title = models.CharField(max_length=128, default="some default value here") and class NewSomeModel(forms.ModelForm): class Meta: model = SomeModel fields = ['title'] widgets = { "title": forms.TextInput(attrs={"placeholder": "My placeholder text"}) Upon rendering the form the text in the field always represents the model's default value, so "some default value here". How can I get the actual placeholder attribute to work? -
How to insert data to my DB when using another model's field in my form?
I have two different models: Trainer and User. I'm pulling in the trainer_price field from Trainer into my form in User. Please note that I'm also not using a foreign key. The problem I'm having is that the trainer_price is not getting inserted and the default value of 0 is there, which is not what I want. The way the User form works is they fill out their name, address, email and the trainer_price is automatically populated once they selected a trainer. It's also a read-only field. Here's what I've tried so far: user views.py def buyer(request): user_form = UserForm() trainer_listing = Trainer.objects.get(id=15).trainer_price context = {'user_form':user_form, 'trainer_listing':trainer_listing} if request.method == "POST": user_form = UserForm(request.POST) if user_form.is_valid(): user_form.save() return redirect("/success_page") return render(request, "user/user_form.html", context) forms.py class UserForm(forms.ModelForm): Fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'John Doe'})) Email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Email'})) Mobile = forms.CharField(widget=forms.TextInput(attrs={'placeholder': '312-222-2222'})) Address = forms.CharField(widget=forms.TextInput(attrs={'placeholder': '1234 Main St'})) City = forms.CharField() State = forms.ChoiceField(choices=STATES) zipcode = forms.CharField() trainer_price = forms.DecimalField(label="Trainer Price", required=False, widget=forms.TextInput(attrs={'readonly':'readonly'})) class Meta: model = User fields = ['Fullname','Email', 'Mobile', 'Address', 'City', 'State', 'zipcode', 'trainer_price'] Any help in the right direction would be great! -
Not able to iterate through QuerySet results with Django
I'm new to Django and I'm experiencing issues with QuerySets. I am experimenting and trying to get to a field using the Bid.objects.filter method. It's constantly coming up with none if I use any filters (even when I type in an exact match like itemID = "Monkey517"). But if I do an "all" search, it comes up with tons of query sets that I don't know how to iterate through. I'm using examples I found online and I get the error that "'QuerySet' object has no attribute 'itemID'" or 'QuerySet' object has no attribute 'highestBidder' I'm not sure exactly how to get at each Query set that is inside a larger query set. It's all kind of confusing to me. Can anyone clear this up for me? Thanks! Below is my relevant code: views.py: def closeAuction(request): username = request.POST.get("username") itemID = request.POST.get("itemID") query = Bid.objects.all() for queries in query.iterator(): print(query.itemID) return render(request, "auctions/index.html") Models.py: class Bid(models.Model): itemID = models.CharField(max_length=64) newBid = models.IntegerField() highestBidder = models.CharField(max_length=64) post.html: {% if user.is_authenticated %} <form name="closeAuction" action="/closeAuction" method="post" > {% csrf_token %} <input autofocus class="form-control" type="hidden" name="username" value={{user.username}}> <input autofocus class="form-control" type="hidden" name="itemID" value={{p.title}}{{p.price}}> <input class="btn btn-primary" type="submit" value="Close Auction"> {% endif %} </form> -
Easiest way to add {{ variable }} from different related model in one template
I got a question. I'm wondering what's the easiest way to add different {{ variable }} from different related model in one template. I'd like to add some information related to seller rating: def total_seller_ratings(self): return self.seller.rating_seller.count() def avg_seller_ratings(self): return self.seller.annotate(avg_ratesugar=Avg('rating_seller__ratesugar')).order_by('-avg_ratesugar') Create a template tag from Middleware? Or is any fastes solution to add another model on my view? I got a main view for my main page: #Channel MAIN PAGE @method_decorator(login_required(login_url='/cooker/login'),name="dispatch") class ChannelMainPage(generic.DetailView, FormMixin): model = Channel context_object_name = 'channel' template_name = 'channel_detail.html' form_class = ChannelChatForm def get_context_data(self, **kwargs): context = super(ChannelMainPage, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def form_valid(self, form): if form.is_valid(): form.instance.channel = self.object form.instance.user = self.request.user form.save() return super(ChannelMainPage, self).form_valid(form) else: return super(ChannelMainPage, self).form_invalid(form) def post(self,request,*args,**kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_valid(form) def get_success_url(self): return reverse('channel:channel_detail',kwargs={"slug":self.object.slug}) models.py class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") image = models.ImageField(null=True,blank=True,default='user/user-128.png', upload_to='channel/') date_created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField('Make it happen', default=False) class Rating(models.Model): channel = models.OneToOneField(Channel,on_delete=models.CASCADE,related_name="rating_channel") consumer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_consumer') seller = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_seller') is_rated = models.BooleanField('Already rated', default=True) comment = models.TextField(max_length=200) publishing_date = models.DateTimeField(auto_now_add=True) ratesugar = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) … -
how can I filter out the geometry field in the request using django-rest-framework-gis
I have this serializer: serializer.py from rest_framework import serializers from rest_framework_gis.serializers import GeoFeatureModelSerializer from .models import UsStatesG class UsStatesSerializer(GeoFeatureModelSerializer): class Meta: model = UsStatesG geo_field = "geom" id_field = False fields = ('st_fips', 'st_name', 'st_abbr') read_only_fields = ('st_fips', 'st_name', 'st_abbr') auto_bbox = True views.py from .models import UsStatesG from .serializer import UsStatesSerializer class StatesViewSet(viewsets.ModelViewSet): queryset = UsStatesG.objects.all() serializer_class = UsStatesSerializer I'm using the django-rest-framework-gis I want to dynamically decide if i want to include the geometry (geo_field) in the response or not. Sometimes I just want to get the names of the spatial units, (i.e. states names, abbreviations, zip codes etc.) without also including the geometry. It makes the request faster this way. Is there any property like i.e. returnGeometry: True | False How can I do this? thanks! -
PyCharm doesn't resolve Django apps but the project works
This is the project structure generated from having runt django-admin startproject school and python manage.py startapp quiz: In INSTALLED_APPS I've added: "quiz.apps.QuizConfig", In order for this project to execute correctly, in school/quiz/views.py I have to import e.g. models from quiz.models instead of the commonly seen school.quiz.models. Otherwise the project fails to run: As you can see above, PyCharm doesn't recognize quiz. It wants me to use school.quiz instead, but when I do that the project doesn't run: File "/.../Code/breather/school/school/urls.py", line 19, in <module> from quiz.views import QuestionView File "/.../Code/breather/school/quiz/views.py", line 6, in <module> from school.quiz.models import Question ModuleNotFoundError: No module named 'school.quiz' I'd really prefer to use school.quiz, but I can live with using quiz if needed. I just want PyCharm and runserver to reconcile on one way so that I can get on with my project. These are my Django settings in PyCharm: -
Google Cloud Django App Deployment - Permission Issues
I'm following this tutorial, yet I get stuck at the very end when I'm trying to deploy the app on the App Engine. I get the following error message: Updating service [default] (this may take several minutes)...failed. ERROR: (gcloud.app.deploy) Error Response: [13] Flex operation projects/responder-289707/regions/europe-west6/operations/a0e5f3f4-29a7-49d8-98b5-4a52b7bf04ca error [INTERNAL]: An internal error occurred while processing task /app-engine-flex/insert_flex_deployment/flex_create_resources>2020-09-21T20:32:48.366Z12808.hy.0: Deployment Manager operation responder-289707/operation-1600720369987-5afd8c109adf5-6a4ad9a9-e71b9336 errors: [code: "RESOURCE_ERROR" location: "/deployments/aef-default-20200921t223056/resources/aef-default-20200921t223056" message: "{\"ResourceType\":\"compute.beta.regionAutoscaler\",\"ResourceErrorCode\":\"403\",\"ResourceErrorMessage\":{\"code\":403,\"message\":\"The caller does not have permission\",\"status\":\"PERMISSION_DENIED\",\"statusMessage\":\"Forbidden\",\"requestPath\":\"https://compute.googleapis.com/compute/beta/projects/responder-289707/regions/europe-west6/autoscalers\",\"httpMethod\":\"POST\"}}" I don't really understand why though. I'm have authenticated my gcloud, made sure my account has App Engine Admin/Deployment rights. Have everything in place. Any hints would be much appreciated. -
Querying Many To Many relationship by number of joins using Django
I have two models: ActorModel and FilmModel joined as follows: FilmModel(models.Model): actors = models.ManyToManyField(Actor, blank=True, related_name='film_actors') ActorModel(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.imdb_id I want to filter my ActorModel for any instance which has more than 5 joins with the FilmModel. I can do this as follows: actors = ActorModel.objects.all() more_than_five_films = [] for actor in actors: actor_film_list = FilmModel.objects.filter(actors__imdb_id=str(name)) if len(actor_film_list)>5: more_than_five_films.append(actor) However, using the above code uses lots of processing power. Is there a more efficient way of finding the actors with more than 5 joins? Could I do this at the filtering stage for example? -
WebSocket connection to 'ws://127.0.0.1:8000/ws/chat//' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
I am having this error message with Django channels please i need help. WebSocket connection to 'ws://127.0.0.1:8000/ws/chat//' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET. -
Save date on every form submission Django
Would it be possible to save the exact date when a specific user submits the form without updating existing data? So basically I'd have every date when a user submitted the form. I'd want to use these dates for a graph. When I submit the form now it updates the users data, such as weight, height, and goal. It works fine, but i want to be able to save submission days like "2020.09.12". And if the user submits the form again to change his data the date should containt "2020.09.12" + the new date. -
Django view: redirect user to template based on schema name (got from URL)
I am trying to redirect users to various apps based on their schema name. I have written this so far: def loginUser(request, url): schema_list1 = ['pierre'] schema_lsit2 = ['itoiz'] if request.method == 'POST': form = AuthenticationForm(data=request.POST) t = urlparse(url).netloc dbschema = '"' + t.split('.', 1)[0] + '"' if form.is_valid(): user = form.get_user() login(request, user) if dbschema in schema_list1: print('yes') redirect = '/upload.html' return HttpResponseRedirect(redirect) elif dbschema in schema_list2: print('yes') redirect = '/dash2.html' return HttpResponseRedirect(redirect) else: form = AuthenticationForm() context = { 'form': form, } return render(request, 'loginUser.html', context) my problem is that I get the error: TypeError at /loginUser loginUser() missing 1 required positional argument: 'url' Request Method: GET Request URL: https://itoiz.exostock.net/loginUser Django Version: 3.0.5 Exception Type: TypeError Exception Value: loginUser() missing 1 required positional argument: 'url' Exception Location: /home/ubuntu/exo/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response, line 113 I am fairly new to django and I am confused about why do i get this error, especially because I used the exact same method somewhere else and it worked fine. I am wondering if someone can see what I am missing. By the way is there another way to get the user's url? -
POSTGRES: FATAL: role "postgres" does not exist
for my django project i wrote a docker-compose.yml, Dockerfile file and a build_dev.sh script after going through various reference and guides. after the build is complete i can access the hello world page by going to the url http://0.0.0.0/ Now I want to create the database i the running docker container docker exec -it django_docker_db_1 bash using this command i get access into the db container then i run the command su - postgres Now when i try to run createuser --createdb --password myproject it asks for a password. I entered the same password that i defined the script (in the guide it was written "When asked, enter the same password for the database as in the build_dev.sh script.") , but it throws me an error saying createuser: error: could not connect to database postgres: FATAL: role "postgres" does not exist. please help me with this! build_dev.sh #!/usr/bin/env bash DJANGO_SETTINGS_MODULE="myproject.settings.dev" \ DJANGO_SECRET_KEY="3!^3%bro*!)=1s_g49eqb5&q^4*-m^7p_)q7xkond_b6*lc&&6" \ DATABASE_NAME="myproject" \ DATABASE_USER="myproject" \ DATABASE_PASSWORD="testpassword" \ EMAIL_HOST="localhost" \ EMAIL_PORT="25" \ EMAIL_HOST_USER="" \ EMAIL_HOST_PASSWORD="" \ PIP_REQUIREMENTS="dev.txt" \ docker-compose up --detach --build docker-compose.yml version: "3.7" services: nginx: image: nginx:latest ports: - "80:80" volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/home/myproject/static - media_volume:/home/myproject/media depends_on: - gunicorn gunicorn: build: context: . args: PIP_REQUIREMENTS: "${PIP_REQUIREMENTS}" … -
How to best setup smtp using Gmail in DJANGO?
I have been using the SMTP module in python (DJANGO specifically) for quite a while now. However, even after turning on access to third party apps in my Google account, sometimes, Google automatically turns it off. This throws errors like Bad Credentials. Code in views.py after receiving email via a POST request upon form submission mail=('Sending email',"Hello ","A message",settings.EMAIL_HOST_USER,[request.POST['email']]) send_mass_mail((mail,),fail_silently=False,) Code in settings.py EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = 'password_here' Though the code works fine sometimes, I am specifically looking for a foolproof way to send emails via my webapp. Thanks in advance -
"AnonymousUser must be a 'User' instance" in perfom_create() method
I'm migrating my web server from Gandi to AWS. I set up my server like the old one: AWS (EC2 & Route53) Server Ubuntu 20.04 Django Rest Framework WSGI Apache2 When I run my server with python manage.py runserver 0.0.0.0:8000 my website works fine. But when I deploy it with apache2 the POST requests don't work because the request's token doesn't work. It's as if the token is missing. Below an example to a POST request to create a poll in my backend: Url : http://mywebsite.fr/api/polls/ Header : Authorization : token mytokenwithmanynumbers Body: { "question": "My poll", "categorie": 1, "answers": [{ "text": "my answer" }] } In my backend I have the following code: urls.py: router.register('api/polls', PollViewSet, 'polls') api.py: class PollViewSet(viewsets.ModelViewSet): permission_classes = [IsOwnerOrReadOnly, ] serializer_class = PollSerializer def get_serializer_class(self): if self.action == 'create' and not self.request.user.is_anonymous: return PollSerializerCreate return PollSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) serializers.py: class PollSerializerCreate(serializers.ModelSerializer): answers = AnswerSerializer(many=True) class Meta: model = Poll fields = '__all__' def create(self, validated_data): answers = validated_data.get("answers", None) categorie = validated_data.get("categorie", None) user = validated_data.get("user", None) question = validated_data.get("question", None) if answers and categorie: poll = Poll.objects.create(question=question, user=user, categorie=categorie) for answer in answers: new_answer = Answer.objects.create(text=answer['text'], poll=poll) return poll raise FieldMissingToCreatePoll But … -
Django-form wizard: How to choose a specific form by name
I'm trying to choose a specific form by its name not its step. Is it possible to use a template tag like {{wizard.advancedForm}} to fetch the advancedForm in my form_list? class BetaRcollection(LoginRequiredMixin, SessionWizardView): form_list = ( ('mainForm', UploadAlbum), ('advancedForm', UploadAlbumAdvanced) ) file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'WizardTmp')) template_name = 'creator/release/collection.html' def done(self, form_list, form_dict, **kwargs): print(f'form_list: ${form_list}') print(f'form_dict: ${form_dict}') print('FORMS ARE VALID') # advancedForm.save() # save musicName = self.condition_dict.mainForm['musicName'] -
Load an image from aws s3 bucket to django application
I made a django app that stores notes of different semesters and branches and I want to display the profile image of the uploader of the post right next to their name in homepage of my website. I am using my staticfiles directly from the S3 bucket The notes that the users upload is stored in the notes/models.py whereas the user's profile and their profile image is stored in users/models.py What I want to do is in home.html (below) use something like, {% static post.uploader.profile.image.url %} but suddenly it does not work. Settings.py AWS_ACCESS_KEY_ID='XXXXXXXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY='XXXXXXXXXXXXXXXXXXXXXXXXXXX' AWS_STORAGE_BUCKET_NAME='django-XXXXX' AWS_S3_REGION_NAME = "ap-south-1" AWS_S3_SIGNATURE_VERSION = "s3v4" AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None # s3 static settings AWS_LOCATION = 'staticfiles' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 public media settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'django_project.storage_backends.PublicMediaStorage' # s3 private media settings PRIVATE_MEDIA_LOCATION = 'private' PRIVATE_FILE_STORAGE = 'django_project.storage_backends.PrivateMediaStorage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' notes/models.py class Notes_Model(models.Model): """Store notes of different branches and semesters.""" uploader = models.CharField(max_length=200) title = models.CharField(max_length=200) date_posted = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=2500) branch_choice = models.CharField(max_length=50, choices=branch_choices, default='cse') file_semester = models.IntegerField(choices=semester_choice) file = models.FileField() syllabus = models.TextField(max_length=200, default='No Syllabus Availibe Yet') def __str__(self): return self.title def get_absolute_url(self): return reverse("notes-detail", … -
Supervisor error - gunicorn: ERROR (spawn error)
I am getting the error gunicorn: ERROR (spawn error) when trying to deploy django application with gunicorn wsgi in the supervisor. My supervisor.conf GNU nano 4.8 supervisord.conf [unix_http_server] file=/tmp/supervisor.sock ; the path to the socket file [supervisord] logfile=server/supervisor/logs/supervisord.log ; main log file; default $CWD/supervisord.log logfile_maxbytes=5MB ; max main logfile bytes b4 rotation; default 50MB logfile_backups=10 ; # of main logfile backups; 0 means none, default 10 loglevel=info ; log level; default info; others: debug,warn,trace pidfile=/tmp/supervisord.pid ; supervisord pidfile; default supervisord.pid nodaemon=false ; start in foreground if true; default false minfds=1024 ; min. avail startup file descriptors; default 1024 minprocs=200 ; min. avail process descriptors;default 200 [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL for a unix socket [program:gunicorn] command=/home/ubuntu/strategy_app/venv/bin/gunicorn strategy_server.wsgi:application -c /home/ubuntu/strategy_app/server/gunicorn/gunicorn.conf.py --chdir /home/ubuntu/strategy_app when I run the same above command outside of supervisor, it works /home/ubuntu/strategy_app/venv/bin/gunicorn strategy_server.wsgi:application -c /home/ubuntu/strategy_app/server/gunicorn/gunicorn.conf.py --chdir /home/ubuntu/strategy_app I also tried other options available in the official docs -
InterfaceError: Error binding parameter 3 - probably unsupported type
I have an error here with my Django backend: Environment: Request Method: POST Request URL: http://localhost:8000/MultipleChoiceQuestion/ Django Version: 2.2.11 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'db.apps.DbConfig', 'rest_framework', 'corsheaders', 'django_filters'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 383. return Database.Cursor.execute(self, query, params) The above exception (unrecognized token: ":") was the direct cause of the following exception: File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in execute 99. return super().execute(sql, params) File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in execute 67. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers 76. return executor(sql, params, many, context) File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Python37\lib\site-packages\django\db\utils.py" in __exit__ 89. raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 383. return Database.Cursor.execute(self, query, params) During handling of the above exception (unrecognized token: ":"), another exception occurred: File "C:\Python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python37\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Python37\lib\site-packages\rest_framework\viewsets.py" in view 114. return self.dispatch(request, *args, **kwargs) File "C:\Python37\lib\site-packages\rest_framework\views.py" in dispatch 505. …