Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to set non-model field in model form to some other field that exists in the model
I have a form that I need to add an extra field to - and it needs to have an initial value of the data model's time field (called seg_length_time). I didn't expect the code to work because I know I need to convert the time into a string from the model, but I can't seem to figure out how to set the field to begin with. See code below: class SegmentForm(forms.ModelForm): str_seg_length_time = forms.CharField(max_length=8) class Meta: model = Segment exclude = ('seg_length_time_delta', 'seg_length_time', 'seg_run_time', 'seg_run_time_delta' , 'seg_remaining_time', 'seg_remaining_time_delta', 'program_id', 'audit_user', ) def __init__(self, *args, **kwargs): obj = Segment.objects.get(id=self.pk) self.fields['str_seg_length_time'].initial = obj.seg_field_length super().__init__(*args, **kwargs) The snippet of the model is below: class Segment(models.Model): class Meta: ordering = ['sequence_number'] program_id = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='segments', # link to Program ) sequence_number = models.DecimalField(decimal_places=2,max_digits=6,default="0.00") title = models.CharField(max_length=190) bridge_flag = models.BooleanField(default=False) seg_length_time = models.TimeField(null=True,default=None, blank=True) . . (other code below this) I haven't included the whole thing, but you get the idea. The field shows up on the form as nothing (Blanks), if I don't do some sort of initial code to set it from the model. Can I get the object by id, or - dont I already have the object in the … -
Removing an apostrophe from a Django Jinja Template?
I would like to remove an apostrophe from a Django template variable in HTML using Jinja. The variable item.product is Paul's Phone which I am using to open a Boostrap Modal: id="move_{{ item.product|cut:' ' }}" This will remove the spaces, which is good. The outcome now is Paul'sPhone, but I can't remove the apostrophe by doing this: data-target="#move_{{ item.product|cut:' ', ''' }}" How do I get around these tags to remove the apostrophe from that variable? -
how to check the submit in django
I'm new to Django my problem is when the user refreshes the page the rate always increases even the user answer the question or not how to prevent rate increase if the user doesn't answer the question I don't know how to solve that any help <form id="resultform" action="/game1/" method="POST"> {% csrf_token %} <input type="hidden" name="std_email" id="std_email" value="{{std_email}}" /> <input type="hidden" name="std_quest" id="std_quest" value="" /> <input type="hidden" name="std_answer" id="std_answer" value="" /> </form> <button type="button" class="btn btn-primary btn-circle btn-xl" onclick="checkAnswer()" > Check </button> def game(request, std): qest = getQuestion() context = { 'question': qest, 'std_name': std[0].name, 'std_rate': std[0].rate, 'std_email': std[0].email, } return render(request, 'qgame.html', context) def getQuestion(): tmp = UserQuestion.objects.all() length = tmp.count() rand = random.randint(1, length) qest = UserQuestion.objects.get(pk=rand) return qest def checkAnswer(request): if(request.method == "POST"): std_quest = request.POST['std_quest'] std_ans = request.POST['std_answer'] std_Email = request.POST['std_email'] std = Student.objects.filter(email=std_Email) if(std_quest == std_ans): rate = std[0].rate rate += 1 Student.objects.filter(email=std_Email).update(rate=rate) return game(request, std) elif(std_quest != std_ans): rate = std[0].rate rate -= 1 Student.objects.filter(email=std_Email).update(rate=rate) return game(request, std) -
Allow only staff member to delete post don't allow any other user to delete
inside views.py can we overide some method inside Postdelete to achieve this i have tried using class PostDelete(DeleteView): model = Post def get_queryset(self): if self.request.user.is_staff: return super(PostDelete, self).get_queryset() def get_success_url(self): return reverse('dashboard') -
Wagtail form builder: How to preserve query string/url parameter from form page for corresponding landing page?
In a wagtail project with a wagtail form builder [1] the default implementation redirects the user after successful form submission to a landing page [2]. In my somewhat special implementation of my form page (AbstractEmailForm) I use a query string (here: ?embed=true) to adjust the rendered page/layout for being "embeddable" (via an iFrame). That works. But after submitting the form on such a page, the method render_landing_page[3] gets called and renders a landing page for that form. But my query string is lost. How do I preserve the query strings from the form page to the corresponding landing page? [1] https://docs.wagtail.io/en/stable/reference/contrib/forms/index.html [2] https://docs.wagtail.io/en/stable/reference/contrib/forms/customisation.html#custom-landing-page-redirect [3] https://github.com/wagtail/wagtail/blob/571b9e1918861bcbe64a9005a4dc65f3a1fe7a15/wagtail/contrib/forms/models.py#L270 -
Unable to save images to model after scraped with beautiful soup
I have tried to saving images to my database immediately I scraped it from a website using beautiful soup and it has refused to save I have tried rectifying this for more than three months now but it seems impossible. What do I do to resolve this. Am very very tired and frustrated with this. This images are urls containing url on database this will give me an error if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' this error is as a result of my attempts to save this scraped image with beautiful soup below are images list that refused to be saved on my models , this images are been scraped with beautiful soup something like this brought the images images = [i['data-src'] for i in soup.find_all('img', {'class','attachment-jnews-750x375 size-jnews-750x375 lazyload wp-post-image'})] https://people.net/wp-content/uploads/2021/03/ad1-746x375.jpg https://people.net/wp-content/uploads/2020/08/caroon-1-600x375.jpg why this code brought the above error Post.objects.create( title=title, content_1=paragraphs, image=images, sources=lnk, ) this is my model.py example code class Post(models.Model): title = models.CharField(max_length=250, blank = True, help_text='Maximum 160 Title characters.') image = models.FileField(upload_to='images', blank=True, null=True, help_text='You must upload original image before continuing.') but i get this error if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' but if … -
is it better to include token in the User model for Django+Jwt?
i'm looking at different ways of using django rest framework with jwt, and most cases would do it in a "normal" way (as the Getting started in the simple Jwt Documentation says), but i encoutred some ones that extends the User model and include the Token inside, something like : class User(AbstractBaseUser, PermissionsMixin): # .....(usual fields(username, password,...)) @property def token(self): return self._generate_jwt_token() def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token is this way better? or is it just a different way to handle it? what difference does it make? -
Ajax in django form
My Ajax request works correctly when I use change and the input is checkbox, but my Ajax request does not work when use input type submit !! I want my type in the input submit and when I do this the Ajax request will not work and the page will reload. $(document).on('change','.filter-form',function(event){ event.preventDefault(); $.ajax({ type:'GET', url:'filter/', data : $(this).serialize(), dataType: 'json', success: function (data) { $('#product-main').html(data['form']); }, error: function (data) { alert("error" + data); } }); }); my form : <form action="" class="filter-form"> <input type="submit" name="price" value="new"> <input type="submit" name="discount" value="discount"> <input type="submit" name="old" value="old"> </form> -
static file directory not found (heroku)
I am making a site with Django 2.2 . But when i try to run git push heroku master an error occours . I tried all the stackoverflow answers but nothing worked. here is my directory: ├───.idea │ └───inspectionProfiles ├───.vscode ├───CheemsCode_Site │ └───__pycache__ └───homepage ├───migrations │ └───__pycache__ ├───static │ ├───css │ ├───img │ │ ├───portfolio │ │ ├───team │ │ └───testimonials │ ├───js │ └───vendor │ ├───bootstrap │ │ ├───css │ │ └───js │ ├───bootstrap-icons │ │ └───fonts │ ├───boxicons │ │ ├───css │ │ └───fonts │ ├───glightbox │ │ ├───css │ │ └───js │ ├───isotope-layout │ ├───php-email-form │ ├───purecounter │ └───swiper ├───templates └───__pycache__ here is my settings.py: """ Django settings for CheemsCode_Site project. Generated by 'django-admin startproject' using Django 2.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'sq@0@!_3yqx%c=%vd_xe4h($n47066smhg3)u2+ro2+gfp8qxa' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application … -
Django BuiltinSignatureError when using DRF
I am not able to figure out the error. The API sometimes returns data and at times it does not. class CreateQuiz(generics.ListCreateAPIView): serializer_class = QuizSerializer def get_queryset(self): classId = self.kwargs.get('classId',None) subject = self.kwargs.get('subject',None) category = Category.objects.filter(class_id=classId,category=subject).values_list('id',flat=True)[0] # chapter = self.kwargs.get('chapter',None) subcategory=self.kwargs.get('chapter',None) subcat = SubCategory.objects.filter(id=subcategory).values_list('sub_category',flat=True)[0] total_marks = 30 questionIDs = Question.objects.raw('''somesql''',params=[category,subcategory,total_marks,category,subcategory,total_marks]) # # and qq.sub_category_id IN %s questions= MCQuestion.objects.filter(question_ptr_id__in=questionIDs).prefetch_related('answer_set__question') essayquestions= Essay_Question.objects.filter(question_ptr_id__in=questionIDs) user = User.objects.get(id=1) if MCQuestion.objects.filter(question_ptr_id__in=questionIDs).prefetch_related('answer_set__question').exists(): print("create quiz") quiz = Quiz() quiz.durationtest="10:00" quiz.random_order=True quiz.save() quizid = Quiz.objects.filter(id=quiz.id).values_list('id',flat=True)[0] quiz = Quiz.objects.get(id=quiz.id) quiz.title = "Practice Exam : "+ quiz.category.class_id.classVal +" "+quiz.category.category +" ("+subcat+") " quiz.save() with connection.cursor() as cursor: cursor.execute("INSERT INTO quiz_subcategory_quiz(subcategory_id,quiz_id) VALUES (%s,%s)",(subcategory,quiz.id,)) for obj in questionIDs: if Question.objects.filter(id=obj.id,quiz__id=quiz.id).exists(): print("Do nothing") else: question = Question(id=obj.id) question.quiz.add(quiz.id) question.save() obj, created = UserQuiz.objects.update_or_create( user_id = user.id,quiz_id=quiz.id ) return Quiz.objects.filter(id=quizid) else: response = JsonResponse({"error": "there was an error"}) response.status_code = 403 # To announce that the user isn't allowed to publish return response return Quiz.objects.filter(id=quizid) My Serializer Class class QuizSerializer(serializers.ModelSerializer): class Meta: model = Quiz fields=( 'id', 'title', 'description', 'url', 'category', 'random_order', 'pass_mark', 'draft', 'durationtest', ) I get the following error and its happening randomly. Any suggestions please. Field source for QuizSerializer.title maps to a built-in function type and is invalid. Define a property or … -
Python Django get textarea value without quotes
am using Django 3.2, i need to get the value of a textarea from template my template code is: <div class="form-group"> <label for="text_to_change">Text to replace</label> <textarea name="replace_text" class="form-control" rows="3"></textarea> </div> i need to pass a list e.x ['Old text', 'New Text'] but what is get is a string: "[Old text', 'New Text']" i tried to use unescape_string_literal without luck -
Do not change the language of CK Editor
I want to change the language of CK Editor to Persian in my Django project After inserting the following code, I receive an error in the console. And CK Editor is not displayed Other languages work properly. What is the problem? I am using the following Python package for CK Editor in my project https://pypi.org/project/django-ckeditor/ Error Image Code CKEDITOR.replace( 'id_html_content', { language: 'fa' } ); -
Django: urls.py giving No Reverse Match error
I installed django-axes which allows you to set a url to redirect to upon 5 login failures. I added this line to settings.py per the documentation: AXES_LOCKOUT_URL = 'account-locked' I then added this line to users/urls.py: path('account/locked/?username=<str>', user_views.account_locked, name='account-locked'), When i input 5 incorrect username/password combos in the login screen, it attempts to redirect me, but I get this error: NoReverseMatch at /login/ Reverse for 'account-locked?username=user2' not found. 'account-locked?username=user2' is not a valid view function or pattern name. -
save multiple hidden fields in django
I have two hidden that the user is not able to fill from form, but I want to provide values for these fields before I save the entry. I have the snippet below to achieve this if I have just one hidden field, but not sure how to make it work for more than one. if request.method == 'POST': var1 = AppName(col1=value1) # var2 = Notice(col2=value2) form = AppNameForm(request.POST, instance=var1) if form.is_valid(): form.save() return redirect("home") How can I bring var2 into the form values before saving? -
gunicorn failing when log configuration added to settings.py in Django
Basically as soon as I add logging configuration, gunicorn responds with this ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Fri 2021-04-23 19:05:44 UTC; 7s ago TriggeredBy: ● gunicorn.socket Process: 4154 ExecStart=/home/ubuntu/.local/share/virtualenvs/name-fma1nZHV/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock name.wsgi:application (code=exited, status=1/FAILURE) Main PID: 4154 (code=exited, status=1/FAILURE) Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: self.stop() Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: File "/home/ubuntu/.local/share/virtualenvs/nameapi-fma1nZHV/lib/python3.8/site-packages/gunicorn/arbiter.py", line 393, in stop Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: time.sleep(0.1) Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: File "/home/ubuntu/.local/share/virtualenvs/nameapi-fma1nZHV/lib/python3.8/site-packages/gunicorn/arbiter.py", line 242, in handle_chld Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: self.reap_workers() Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: File "/home/ubuntu/.local/share/virtualenvs/nameapi-fma1nZHV/lib/python3.8/site-packages/gunicorn/arbiter.py", line 525, in reap_workers Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Apr 23 19:05:44 ip-10-0-84-161 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Apr 23 19:05:44 ip-10-0-84-161 systemd[1]: gunicorn.service: Failed with result 'exit-code'. However, when there is no logging in my settings.py file for Django, gunicorn works fine. Below is my settings.py with and without logging (the settings.py works fine in dev environment on localhost, just breaks gunicorn in production) - also, for every part of the settings that I wanted to keep to myself such … -
Trouble connecting to AWS ElasticSearch from django-haystack using an SSH tunnel
I have a Django app running on EC2, and it can connect to my AWS ElasticSearch using the following django-haystack configuration: HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': os.environ.get('ELASTICSEARCH_URL', 'http://elasticsearch').strip(), 'INDEX_NAME': 'my_index' }, } if 'es.amazonaws.com' in HAYSTACK_CONNECTIONS['default']['URL']: HAYSTACK_CONNECTIONS['default']['KWARGS'] = { 'port': 443, 'http_auth': AWS4AuthEncodingFix( os.environ.get('AWS_ACCESS_KEY_ID').strip(), os.environ.get('AWS_SECRET_ACCESS_KEY').strip(), os.environ.get('ELASTIC_SEARCH_AWS_REGION', 'us-east-1').strip(), 'es'), 'use_ssl': True, 'verify_certs': True, 'connection_class': RequestsHttpConnection, } This works fine, but now for debugging purposes, I need to connect to the production ElasticSearch from my local development machine. To do this, I created an SSH tunnel: ssh -v -N -L localhost:9200:${ELASTICSEARCH_ENDOINT}:443 -i my_secret_pem_file.pem ${EC2_USERNAME}@${EC2_IP} From the SSH logs I can see that the connection is established, and this works fine: 10:26 $ curl -k -X GET 'https://localhost:9200/_cat/indices?v' health status index pri rep docs.count docs.deleted store.size pri.store.size yellow open .kibana-4 1 1 2 0 9.5kb 9.5kb yellow open my_index 5 1 1150327 547242 2.2gb 2.2gb (note that I had to use -k with curl to bypass SSL verification, as the certificate would not be valid for localhost. To connect from django-haystack, I added the following else branch to the configuration above: else: HAYSTACK_CONNECTIONS['default']['KWARGS'] = { 'port': 9200, 'use_ssl': False, 'verify_certs': False, } When I start my Django app and try … -
remove all record of a model in Django restfull
I try to remove all records of a model by using API but I get an error how can I do that View : @api_view(["DELETE"]) @csrf_exempt @permission_classes([IsAuthenticated]) def delete_site(request): try: Site.objects.all().delete() return Response(status=status.HTTP_204_NO_CONTENT) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) URL router.register('site-delete',views.delete_site) Error : assert queryset is not None, '`basename` argument not specified, and could ' \ AssertionError: `basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute. -
Django inline formset does not do this
I am creating a Calorie Log website using Django. One creates an account, and can start logging the amount of calories he consumed and burnt on a particular date, then it shows whether on that day he consumed or burnt more calories. The User can store frequently eaten food and frequent exercise that he does so that when he adds the data he can use that item Using the given midels user can add food-item and exercises. Food Model: class Food(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) food_name = models.CharField(max_length=50, null=True, blank=True) calories = models.IntegerField(null=True) food_pic = models.ImageField(default="default_food.jpg", null=True, blank=True) def __str__(self): return f"{self.food_name}" Exercise Model: class Exercise(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) exercise_name = models.CharField(max_length=100, null=True, blank=True) calories = models.IntegerField(null=True) exercise_pic = models.ImageField(default="default_exercise.png", null=True, blank=True) def __str__(self): return f"{self.exercise_name}" I use the following two models to store the information about a particular date: DailyFood Model: class DailyFood(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) food_name = models.ForeignKey(Food, on_delete=models.CASCADE, null=True) quantity = models.FloatField(null=True) date = models.DateField(auto_now_add=True, null=True) def __str__(self): return f"{self.customer}, {self.date}" DailyExercise Model: class DailyExercise(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) exercise_name = models.ForeignKey(Exercise, on_delete=models.CASCADE, null=True) quantity = models.FloatField(null=True) # number of hours done exercise date = models.DateField(auto_now_add=True, null=True) def __str__(self): return f"{self.customer}, … -
Django rest framework + cpanel's application manager(phusion passenger) = error 500
I'm able to run a local server with the quickstart example from https://www.django-rest-framework.org/tutorial/quickstart/, but after deploy with Application Manager (Phussion Passenger) the server only display the following page: no css, js And console: error When click /users : Server error I did run python manage.py collectstatic Setup: Centos 7.9 Cpanel Application Manager (Phusion Passenger) - Development = True Python 3.8 venv Django + Django Rest Framework - Debug = True Settings.py : from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secret' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ] 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', ] ROOT_URLCONF = 'tutorial.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'tutorial.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', … -
smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server - trying to send email via Django
I have a Docker container where I am trying to send an email via Django. I have a separate email server on another domain that I want to use for this purpose. I have other applications connect with it with no problem. My Django production email setup looks like this (I intend to replace username and password with Kubernetes secrets in the future, but for testing I am just putting them inside the file): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.mydomain.io' EMAIL_USE_TLS = False EMAIL_PORT = 587 EMAIL_HOST_USER = "<username>" EMAIL_HOST_PASSWORD = "<password>" In my module, I have the following code: from rest_framework.views import APIView from django.core.mail import send_mail class MailView(APIView): def post(self, request): subject = request.data.get("subject") message = request.data.get("message") sender = request.data.get("sender") receipients = request.data.get("receipients") send_mail(subject,message,sender,receipients,fail_silently=False,) ... more This works locally, however when I try to run it inside the container, I get the following error: smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server. Do I need to install some sort of SMTP relay or server to my Docker container? My Docker container is based on the python:3.7 container and I am not currently installing any SMTP extensions or anything to it. -
Django RESTApi Using ForeignKey as filter still produces error
I think I come closer to my problem with API, but I still get the following error: TypeError: Field 'id' expected a number but got <built-in function id>. Model: from django.contrib.auth.models import User class Todos(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=20, default="") text = models.TextField(max_length=450, default="") done = models.BooleanField(default=False) Serializer: class TodosSerializer(serializers.ModelSerializer): class Meta: model = Todos fields = ("id", "owner", "name", "text", "done") View: class TodosView(viewsets.ModelViewSet): queryset = Todos.objects.filter(owner__id=id) serializer_class = TodosSerializer urls: router = routers.DefaultRouter() router.register("todos/<int:id>", views.TodosView) urlpatterns = [path("", include(router.urls))] I want to get all todos for a single User. What am I doing wrong here? -
How do I register one to one users in django rest_framework?
I'm lost on how should I register and login a user which is extendable to many roles. I have different apps in my project: Admin Student Teacher And all these apps with their models are connect to my Custom User model with one to one relationship. Now what should I implement to make these endpoints: POST 'admin/register' - registers an admin POST 'student/register' - registers a student POST 'teacher/register' - registers a teacher POST 'admin/login' - login an admin POST 'student/login' - login a student POST 'teacher/login' - login a teacher What this will do is, whenever, someone registers as a admin it will first create a user and then register it as an admin. I tried using djoser but didn't find much on custom create methods. Little guidance will be appreciated! -
Mongodb connection error from digitalocean app platform
I am having an unusual problem: I successfully deployed a Django app on the digital ocean app platform but the problem is that whenever I am trying to reach any route that requires database app crashes because of MongoDB connection problem and after some time I see upstream connect error or disconnect/reset before headers. reset reason: connection termination When I check the logs I see the ServerSelectionTimeoutError from pymongo So the first thing I checked is the host URL which is correct because using the same credentials I am able to connect and query data from my local pc by a python program I followed the format: "mongodb:srv//myusername:mypassword@clustername.mongodb.net/mydbname my password doesn't contain any special characters In my Django app settings, I put all the required variables to get Django working with MongoDB -I used djongo as an engine DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'stocks', 'HOST': os.getenv("DB_HOST"), 'USER': os.getenv("DB_USERNAME"), 'PASSWORD': os.getenv("DB_PASSWORD") } } All the variables are set correctly I checked in an App platform console Another thing is that if I run python shell in apps console on digital ocean so directly on a server I get a different error immediately but when accessing from the deployed … -
ModuleNotFoundError, even thought it exist, and is installed
I tried makemigrations and i get: from SocialNetwork.Accounts.models import User ModuleNotFoundError: No module named 'SocialNetwork.Accounts''= I made a few applications, installed it in settings, and even pycharm sees it, but i get an error as above. My project structure: -SocialNetwork -Accounts -__init__.py -admin.py -apps.py -models.py -tests.py -urls.py -views.py -Chats -__init__.py -admin.py -apps.py -models.py -tests.py -urls.py -views.py -Other apps And tried install models from account in chats: from django.db import models from SocialNetwork.Accounts.models import User class Chat(models.Model): firstUser = models.ForeignKey(User, on_delete=models.CASCADE) secondUser = models.ForeignKey(User, on_delete=models.CASCADE) I doubt that it will be helpful but i can write models from user: class User(models.Model): name = models.CharField(max_length=50, null=True) phone = models.PhoneNumberField() dateBirth = models.DateField(blank=True, null=True) description = models.CharField(max_length=200, blank=True, null=True I have been sitting with this for 2 hours, what can i should do in this case? Maybe something more with settings or structure? But structure seems be as always in django projects. Any help will be approciated cos i am a little bit new in django. -
Bootstraps cards get encapsulated on Django Landing page
I have a myterious phenomenom and hopefully somebody has experienced this already as well. I want to put three cards in a row on my Django landing page. I fill these cards with dynamic content, means i populate three lines of text which get selected in a for loop in my template. With a dummy text everything looks fine. But as soon as the dynamic text lines gets populated, the third card gets encapsulated into the second card. I would have expected the third card to wrap into the new line but for some reason the layout reacts differently (strangely). Has anyone a clue how I can prevent this to happen? I assume it has sth. to do with the width... :( Thanks a lot in advance for any helpful tip! Best regards Rudy