Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django printing email instead send. I'm already using smtp backend
I'm using "django-rest-auth" to reset the password. But when I enter the email to reset the password, instead of sending the email, django displays the rendered html in the terminal. settings.py REST_AUTH_SERIALIZERS = { "PASSWORD_RESET_SERIALIZER": "emails.serializers.PasswordResetSerializer", } EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.mailgun.org" EMAIL_PORT = 587 EMAIL_HOST_USER = "postmaster@mydomain.com" EMAIL_HOST_PASSWORD = "my_secret" EMAIL_USE_TLS = True emails/serializers.py from django.contrib.auth.forms import PasswordResetForm from django.contrib.auth import get_user_model from django.conf import settings from rest_framework import serializers User = get_user_model() class PasswordResetSerializer(serializers.Serializer): email = serializers.EmailField() password_reset_form_class = PasswordResetForm def validate_email(self, value): self.reset_form = self.password_reset_form_class(data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError("Erro: dados inválidos") if not User.objects.filter(email=value).exists(): raise serializers.ValidationError("Endereço de email invalido") return value def save(self): request = self.context.get("request") opts = { "use_https": request.is_secure(), "from_email": "No Reply - Geeknoon <no-reply@geeknoon.com>", "subject_template_name": "emails/subject_template.txt", "email_template_name": "emails/reset_password.html", "request": request, } self.reset_form.save(**opts) Example of terminal output: https://imgur.com/a/w9pi78d -
Rendering a Django application with static pages
I have a Django web application, I want to show the application to clients with sending them multiple static pages (i.e. multiple HTML files and JS or CSS folders). I found django-distill package here but I am not sure should I add it to the installed applications of my project or are there other strait-forward alternatives. -
Convert javascripts' null to Django None when doing request
I am sending the following request to Django server: GET '/api/project/R0009_il/saved_variants/?categoryFilter=null' And in Django code: category_filter = request.GET['categoryFilter'] I expect the following check to fail but it does not: if category_filter: print(category_filter) Instead it prints null, so javascripts' null is True which is obviously wrong. How to fix that? I found the solution to the reverse task, but not to the current one: Convert Python None to JavaScript null -
How to add a button to update another model in Django UpdateView
I have ListView that shows list of Person Models for a Home Moldel. When I click on a respective link for a Person, an UpdateView is called for the Person. I can click a "Cancel" or "Update" button once I am view for the Person. When I click either buttons, I am brought back to the ListView of the Persons. Now, I want to add another button "Update Another". This button should bring the next Person in the ListView that should be updated. See, example below: ListView --Template (Project) Person1 <link1> Person2 <link2> Person3 <link3> Person4 <link4> UpdateView --Template (Person1) forms fields.... [Cancel] [Update] [Update Another] If a user clicks on "Update Another", the user should be seeing the UpdateView --Template for Person2 and so... It could be cyclic. -
'WSGIRequest' object has no attribute 'CustomUser'
I want to create a patient system. User can add patients but I want to users can see only their patients. I used patient_list = newPatients.objects.filter(current_user.id) `but I get an error. How can I fixed it? settings.py MIDDLEWARE = [ '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', ] views.py @login_required def patient_list(request): current_user = request.CustomUser patient_list = newPatients.objects.filter(current_user.id) query = request.GET.get('q') if query: patient_list = patient_list.filter( Q(first_name__icontains = query) | Q(last_name__icontains = query) | Q(dept__icontains = query) | Q(address__icontains = query) | Q(phone__icontains = query) | Q(notes__icontains = query)) paginator = Paginator(patient_list, 5) # Show 5 contacts per page page = request.GET.get('page') try: patients = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. patients = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. patients = paginator.page(paginator.num_pages) return render(request, "patients.html", {'patients':patients}) Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/patients/ Django Version: 3.0.3 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'patients', 'widget_tweaks', 'crispy_forms', 'ckeditor'] Installed Middleware: ('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 (most recent call last): File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response … -
How to always listen for amazon sqs in python django rest framework
I am new to python django rest framework and I need to listen amazon sqs continuously in framwwork. where I can run while loop infinitely or Can I use Celery[sqs] for this purpose? Thanks in advance. -
How to fix "the `.create()` method does not support writable nested fields by default" in Django API
I have a problem with creating new ratings for cars. When i try to send a post request from Postman in order to create/add a new rating for a specific car i get the error: The `.create()` method does not support writable nested fields by default. These are my models: class Car(models.Model): name = models.CharField(max_length=50) symbol = models.CharField(max_length = 5) def __str__(self): return self.name class Type(models.Model): name = models.CharField(max_length = 50) fuel = models.CharField(max_length = 1)##1 or 2 for fuel type car = models.ManyToManyField(Car) def __str__(self): return self.name class Rating(models.Model): rating = models.IntegerField(validators=[ MaxValueValidator(10), MinValueValidator(0) ]) car = models.ForeignKey(Car, on_delete=models.CASCADE) type = models.ForeignKey(Type, on_delete=models.CASCADE) def __int__(self): return self.rating My serializers: class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('id','name') class TypeSerializer(serializers.ModelSerializer): car = CarSerializer(many=True) class Meta: model = Type fields = ('id','name', 'fuel', 'car') #depth=2 class RatingSerializer(serializers.ModelSerializer): module = ModuleSerializer() class Meta: model = Rating fields = ('id','rating', 'car', 'type') When i try to do a post request to rating such as : {"rating":5, "car": 2,"type":{"id":1,"name":"OffRoad","fuel":"1","car":[{"id":2,"name":"Ford"}] } } I get: The `.create()` method does not support writable nested fields by default. -
How do I write a custom tag in my `views.py` and call it in my template
This is the method I want to call. def is_liked(post, user): *post is a single instance of a post model* *user is the current logged in user* return post.likes.filter(username = user).exists() I've tried register = template.Library() @register.simple_tag def is_liked(post, user): *rest of method* and called it with {% if is_liked post user %} *Something* {% else %} *Something else* {% endif %} and I get the error Unused 'post' at end of if expression. -
Are making relationships between tables like this is correct? Are there better ways to make relationships between tables than this way?
[ enter image description here ]1 CREATE TABLE Users ( user_id integer ); CREATE TABLE Schools ( schoole_id integer PRIMARY KEY AUTOINCREMENT, address_id integer ); CREATE TABLE ِِAcademic_year ( year_id integer ); CREATE TABLE Employees ( employee_id integer PRIMARY KEY AUTOINCREMENT, user_id integer, address_id integer ); CREATE TABLE Addresses ( address_id integer PRIMARY KEY AUTOINCREMENT ); CREATE TABLE Students ( student_id integer PRIMARY KEY AUTOINCREMENT, user_id integer PRIMARY KEY AUTOINCREMENT, address_id integer PRIMARY KEY AUTOINCREMENT ); CREATE TABLE Center ( center_id integer PRIMARY KEY AUTOINCREMENT, student_id binary, school_id integer PRIMARY KEY AUTOINCREMENT, year_id integer PRIMARY KEY AUTOINCREMENT, mark_id integer, classroom_id integer, level_idclassroom_id integer, material_id integer, user_id integer, employee_id integer, degree integer, grade text ); CREATE TABLE Marks ( mark_id integer PRIMARY KEY AUTOINCREMENT ); CREATE TABLE Classroom ( classroom_id integer PRIMARY KEY AUTOINCREMENT ); CREATE TABLE Levels ( level_id integer ); CREATE TABLE Material ( material_id integer PRIMARY KEY AUTOINCREMENT ); Each of the tables is related to many to many relationships across the center table I use Django What is best, making one table that links all the tables that have a lot to many relationship, or making a table specific to each relationship many to many. Noting the … -
Django dropdown showing model Fields
I want to display a dropdown that contains the string values of the Field names in one of my models. models.py : class MyModel(models.Model): meat = models.CharField() veggies = models.CharField() fish = models.CharField() forms.py: class MyModelForm(ModelForm): class Meta: model = MyModel fields = ['foodTypes'] The dropdown should then show meat veggies fish -
Django get_or_create ValueError
Trying to add rows from a DataFrame into Django model. models.py: class CreditIndex_TEST(models.Model): loanBook = models.ForeignKey(LoanBooks, on_delete=models.CASCADE) run_date = models.DateField() index_date = models.DateField() index_CD = models.IntegerField() Index_value = models.FloatField() class Meta: constraints = [ models.UniqueConstraint(fields= ['loanBook','run_date','index_date','index_CD'], name='unique_CreditIndexPair') ] views.py: for index, row in tempDf.iterrows(): obj, created = CreditIndex_TEST.objects.get_or_create( loanBook=dbname, run_date= run_date, index_date=row['Date'], index_CD=1, Index_value=row['CreditIndex_CD1'] ) ERROR:: ValueError: Field 'id' expected a number but got 'Botswana_TU'. I don't understand why I am being asked to specify id. The record I am trying to add to the model does not exist and therefore Django should create it and assign id, not expect it from me? -
AssertionError: Expected a `date`, but got a `datetime`. Refusing to coerce, as this may mean losing timezone information
I am facing some issues while creating an API Here is my model class Education(AuditFields): user = models.ForeignKey(User, on_delete=models.CASCADE) school = models.CharField(max_length=255, blank=True) field_of_study = models.CharField(max_length=255, blank=True) start_year = models.DateField(default=datetime.now) end_year = models.DateField(default=datetime.now) This is my serializer : class EducationSerializer(ModelSerializer): class Meta: model = Education fields = '__all__' views : class EducationCreateView(CreateAPIView): def get_queryset(self, *args, **kwargs): queryset_list = Education.objects.filter( user=self.request.user) return queryset_list serializer_class = EducationSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) If I am post something it shows the following message { "user": [ "This field is required." ] } if I change my serializer like this class EducationSerializer(ModelSerializer): class Meta: model = Education fields = '__all__' extra_kwargs = {'user': {'required': False}} I am getting an error like this Expected a date, but got a datetime. Refusing to coerce, as this may mean losing timezone information. Use a custom read-only field and deal with timezone issues explicitly. How to resolve this . -
Django Forms with dynamic field values
First time using Django Forms. I'm stuck trying to get the dropdown choices to reload. My forms.py is below. When the database state changes, the choices do not. I suppose that this is because they are defined at a class level, which means the query happens at initialisation of the module? I've found that the only way to get my dropdowns to update is to restart the webserver. How can I have the database queries evaluate on every request? forms.py from django import forms from app.models import Collection, ErrorMessage, Service class FailureForm(forms.Form): collections = [(collection.value,)*2 for collection in Collection.objects.all()] error_messages = [(message.value,)*2 for message in ErrorMessage.objects.all()] services = [(service.value,)*2 for service in Service.objects.all()] collection = forms.CharField(label='collection', max_length=100, widget=forms.Select(choices=collections)) error_message = forms.CharField(label='error_message', max_length=400, widget=forms.Select(choices=error_messages)) service = forms.CharField(label='service', max_length=100, widget=forms.Select(choices=services)) -
DJango - NoReverseMatch Error - What is wrong?
I am trying to set up a user password change from built on this tutorial. Unfortunately, on success, this tutorial just returns the user to the change password form, which doesn't seem very satisfactory. So, I am attempting to redirect the user user to a success template. My code is in an app called your_harmony base.py INSTALLED_APPS = [ ... 'your_harmony', ... ] urls.py urlpatterns = [ ... url(r'^your-harmony/', include('your_harmony.urls')), ... ] your_harmony/urls.py urlpatterns = [ url(r'password/$', change_password, name='change_password'), url(r'password_changed/$', password_changed, name='password_changed'), ] views.py def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Your password was successfully updated!') return redirect('password_changed') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) url = 'registration/change_password.html' return render(request, url, {'form': form}) def password_changed(request): url = 'password_changed.html' return render(request, url, {}) When I use the form to change the password and submit, the password is changed correctly, but I get the error NoReverseMatch at /your-harmony/password_changed/ However, when I hover over the link to call the change password form, the url displayed in the browser is 127.0.0.1:8000/your-harmony/password Can someone please point what I am doing wrong? -
Django test error in command line: <model name> matching query does not exist
This is my tests.py file: from django.test import TestCase from .models import * from django.contrib.auth.models import User class ArticleTestCase(TestCase): @classmethod def setup(self): Article.objects.create( article_title="title1", article_content="content of article", ) def test_article_title(self): a1 = Article.objects.get(pk=1) article_name = a1.article_title self.assertEquals(article_name, 'title1') But, i'm always getting this error: Traceback (most recent call last): File "F:\Django_Blog_Live\swagato_blog_site\blog_api\tests.py", line 16, in test_article_title a1 = Article.objects.get(pk=1) File "F:\Django_Blog_Live\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "F:\Django_Blog_Live\env\lib\site-packages\django\db\models\query.py", line 415, in get raise self.model.DoesNotExist( blog_api.models.Article.DoesNotExist: Article matching query does not exist. And the error description is pointing at this statement: a1 = Article.objects.get(pk=1) -
How do you apply the styling of text fetched from the database in Django?
I'm creating a blog. In the post page, I am fetching the text from the database, but the styling is not being applied. Instead, I am getting the "raw" output. I am using {{post.text}} to fetch the post content and I am getting: <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus eget leo cursus, tempus leo non, sodales sem.</p> Instead of the text with the <p> styling. I am using django-ckeditor. -
django taggit-serializer not create tags in rest framework
here is my models.py class Post(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="post") title=models.CharField(max_length=128,null=True,blank=True) rate=models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)],default=True,null=True,blank=True) # rating=models.IntegerField(null=True,blank=True) content=models.TextField(null=True,blank=True) review=models.CharField(max_length=250,null=True,blank=True) url=models.URLField(null=True,blank=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name="post_voters") tags = TaggableManager() in my serializers.py i have imported from taggit_serializer.serializers import (TagListSerializerField, TaggitSerializer) and here is the post serializer class Spost(serializers.ModelSerializer,TaggitSerializer): tags = TagListSerializerField() author=serializers.StringRelatedField(read_only=True) # likes_count=serializers.SerializerMethodField(read_only=True) # user_has_voted=serializers.SerializerMethodField(read_only=True) ## for string related field without displaying it as numerics , it displays the direct object of that object" # user=Scomments() class Meta: model = Post fields = ('id','title','rate','author','content','review','url','tags') def get_likes_count(self,instance): return instance.voters.count() def get_user_has_voted(self,instance): request=self.context.get("request") return instance.voters.filter(pk=request.user.pk).exists() but what issue i have been faceing right now is whenever i trigger a post request with tags the object is being created im getting that the object along with tags being created but when i see in the admin panel the tags part isnt being updated { "rate": 4, "content": "content", "review": "dsfdf", "url": "http://google.com", "tags": [ "django", "python" ] } this is the post request and in postman i can see the updated request { "id": 122, "title": null, "rate": 4, "author": "User", "content": "content", "review": "dsfdf", "url": "http://google.com", "tags": [ "django", "python" ] } but when i see the same thing in django admin panel and json list of all objects i … -
How to make django use two different databases based on debug
i want to be to use the simple db.sqlite3 on my local environment and use a postgresql in production. how can i configure the settings file to know which databse to use based on the value of DEBUG -
Django: Generate constant article profile
so far, as I was doing a blog in Django, I would generate all the data, link, only when we enter through such a thing path("/article/<slug:article_title>", ArticleView().as_view()) but this is not visible in google searches. I want to permanently generate this article so I can look it up on Google. -
Django Attribute Error - object has no attribute 'get'
I am trying to create a multiple file upload form using inlineformset factory. I followed the process defined in https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#django.forms.models.BaseInlineFormSet. I am getting following errow. Attached the views.py and model.py file. please help. Error: Request Method: GET Request URL: http://127.0.0.1:8000/tagging/UploadMultipleFile/1/ Django Version: 3.0.2 Exception Type: AttributeError Exception Value: 'UploadMultiFile' object has no attribute 'get' Exception Location: Python Version: 3.8.1 #MODELS.PY class UploadInputFile(models.Model): process=models.ForeignKey(Process,blank=False,on_delete=models.CASCADE,related_name="inputfile") inputfilepath=models.FileField(upload_to=user_directory_path, null=True) inputfilename=models.CharField(max_length=300,blank=True) multiplefile=models.BooleanField(blank=True,default=False) date_uploaded = models.DateTimeField(auto_now=True) def __str__(self): return(self.process.process_name) def get_absolute_url(self): return reverse("tagging:tagginghome") class UploadMultiFile(models.Model): process=models.ForeignKey(Process,blank=False,on_delete=models.CASCADE,related_name="process") batch=models.ForeignKey(UploadInputFile,blank=False,on_delete=models.CASCADE,related_name="multiplefiles") inputfilepath=models.FileField(upload_to=user_directory_path, null=True) inputfilename=models.CharField(max_length=300,blank=True) date_uploaded = models.DateTimeField(auto_now=True) def __str__(self): return(self.batch_id.process_id.process_name) def get_absolute_url(self): return reverse("tagging:tagginghome") # VIEWS.PY # upload Multiple files def UploadMultipleFile(request,batchid): batchid=int(batchid) pk=batchid getProcessAndBatch=UploadInputFile.objects.all().values().get(id=batchid) MultiFileUploadFormSet = inlineformset_factory(UploadInputFile,UploadMultiFile,fk_name='batch',fields=('inputfilepath','inputfilename')) if request.method=="POST": formset= MultiFileUploadFormSet(request.POST,request.FILES,instance=getProcessAndBatch) if formset.is_valid(): formset.save() else: formset= MultiFileUploadFormSet(instance=getProcessAndBatch) return render(request,"tagging/UploadInputFile_Form.html",{'pk':pk,'formset':formset}) -
unable to install mysqlclient to connect django to mysql db on my mac
I'm new to mac, python and django. This will be my second project. I use to have a django environment working on my old windows pc but, that also came with many weeks of struggle to get it working. Now I've been struggling through article after article on the web but, with absolutely no progress for 2 weeks. I just keep getting this issue..... (klsapp) normancollett@Normans-MacBook-Air klsapp % pip3 install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.4.6.tar.gz (85 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/normancollett/Documents/GitHub/klsapp/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/gy/lrnz57_x27z52f77rgshj80w0000gn/T/pip-install-nkn6549a/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/gy/lrnz57_x27z52f77rgshj80w0000gn/T/pip-install-nkn6549a/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/gy/lrnz57_x27z52f77rgshj80w0000gn/T/pip-wheel-658q_j90 cwd: /private/var/folders/gy/lrnz57_x27z52f77rgshj80w0000gn/T/pip-install-nkn6549a/mysqlclient/ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.6 creating build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb creating build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension … -
How Do I Group a Model Class with More then Two Levels of Subcategories?
How do you define a organized choice of a model class that have more then two levels in the named groups. I want to create a class so when I add a meteorites it goes into the proper classification but also inherits the top levels. For example a shergottites meteorite is also a differentiated meteorites, martian meteorites. differentiated meteorites martian shergottites I am self taught through basic Django tutorials and basic google search troubleshooting which has worked so till this. I am open to any solution, but was wondering whats the best practice for adding something with multiple nesting inside. Later this grouping will be import for sorting, searching and most functionality. I found this on Django project which is close to what I need but there are a few extra levels of organization. MEDIA_CHOICES = [ ('Audio', ( ('vinyl', 'Vinyl'), ('cd', 'CD'), ) ), ('Video', ( ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ) ), ('unknown', 'Unknown'), ] Below is what I am trying to do which two broad categories with 3 and 4 sub categories in each with up to two more subcategories. Here is NASA chart I am using for classification as a picture NASA Meteorite Classification Chart In … -
Microsoft Azure - App Service for containers (Docker problem)
i am trying to upload django app at microsoft azure using their solution app services for containers. The APP without docker is working perfectly, after i added docker it's working locally but when i use microsoft container registry and upload it to and then try to use their app for containers solution it doesn't work. I need some help in here: I created basic django restapiframework. Didn't add anything in there. After that i checked if it's working locally and it's working perfectly. After that i uploaded it on microsoft azure web app (not for cointaners) and it worked perfectly. After that i tried to add docker to my project and use microsoft azure web services for containers. Below is my docker code and commands i try to use for locally: DockerCompose: version: '3.7' services: web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate --run-syncdb && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - ./django_dashboard:/usr/src/django_dashboard ports: - 8000:8000 env_file: - ./.env.dev DockerFile: FROM python:3.6 # set work directory WORKDIR /usr/src # install dependencies RUN pip install --upgrade pip COPY requirements.txt /usr/src/requirements.txt RUN pip install -r requirements.txt # set work directory WORKDIR /usr/src/django_dashboard # set … -
Django Return 1 If Course Is A Paid Course
I want to be able to determine if a course is a paid course. If it is, return 1. A course can be any combination of Free, Monthly, or Yearly. Monthly and Yearly are paid and cost money. I tried doing a couple of things (template for loops) and using a paid function in my model and have not had luck with either one. Desired Result: If a course allows Monthly or Yearly access then return 1 Template Loops: {% for object in object.course.allowed_memberships.all %}{{object}}{% endfor %} FreeMonthlyYearly {% for object in object.course.allowed_memberships.all %}{% if object|stringformat:"s" != 'Free' %}1{% else %}0{% endif %}{% endfor %} 011 Models.py: class Course(models.Model): SKILL_LEVEL_CHOICES = ( ('Beginner', 'Beginner'), ('Intermediate', 'Intermediate'), ('Advanced', 'Advanced'), ) slug = models.SlugField() title = models.CharField(max_length=120) description = models.TextField() search_page_description = models.TextField() allowed_memberships = models.ManyToManyField(Membership) created_at = models.DateTimeField(auto_now_add=True) subject = models.ManyToManyField(Subject) skill_level = models.CharField(max_length=20,choices=SKILL_LEVEL_CHOICES, null=True) visited_times = models.PositiveIntegerField(default=0) thumbnail = models.ImageField(blank=True, null=True, max_length=255) thumbnail_alt = models.CharField(blank=True, null=True, max_length=120) @property def paid(self): print(self.allowed_memberships.all().exclude(membership_type='Free')) for x in self.allowed_memberships.all().exclude(membership_type='Free'): print(x) if str(x) in ('Monthly', 'Yearly'): return '1' else: return '0' class Lesson(models.Model): slug = models.SlugField() title = models.CharField(max_length=120) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) description = models.TextField() transcript = models.TextField() … -
django Could not find a version that satisfies the requirement sweetalert2 (from versions: none)
I am using django 3.0.3, why i cant install sweetalert? does django supported sweetalert? ive tried also sweetalert and sweetalert2