Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.core.exceptions.FieldError: Unknown field(s) in ModelForm
After adding a ModelForm and specifying the fields, I get this error when I try to makemigrations. New to django and programming in general, so probably something dumb. django.core.exceptions.FieldError: Unknown field(s) (handling_time, holding_time, encounter_date, crate_time) specified for Encounter Models.py: from django.db import models from django.conf import settings import datetime class Animal(models.Model): Name = models.CharField(max_length=64, unique=True) Inactive_Date = models.DateField(null=True, default=None, blank=True) ANIMAL_TYPE_CHOICES = [ ('Alligator', 'Alligator'), ('Alpaca', 'Alpaca'), ('Anteater', 'Anteater'), ('Armadillo', 'Armadillo'), ('Cat', 'Cat'), ('Chicken', 'Chicken'), ('Chinchilla', 'Chinchilla'), ('Donkey', 'Donkey'), ('Frog', 'Frog'), ('Goat', 'Goat'), ('Horse', 'Horse'), ('Insect', 'Insect'), ('Lizard', 'Lizard'), ('Millipede', 'Millipede'), ('Owl', 'Owl'), ('Penguin', 'Penguin'), ('Pig', 'Pig'), ('Snake', 'Snake'), ('Spider', 'Spider'), ('Tenrec', 'Tenrec'), ('Turtle', 'Turtle'), ] Animal_Type = models.CharField( max_length=32, choices=ANIMAL_TYPE_CHOICES, default='Cassowary') Comments = models.CharField(max_length=255) def __str__(self) -> str: return ('Animal: ' + self.Name) def delete(self): self.Inactive_Date = datetime.datetime.today() self.save() class Encounter(models.Model): encounter_date = models.DateField animal = models.ForeignKey(Animal,null = True, on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL,null = True, on_delete=models.SET_NULL) handling_time = models.BigIntegerField crate_time = models.BigIntegerField holding_time = models.BigIntegerField comments = models.CharField(max_length=255) def __str__(self) -> str: return ('Encounter: ' + self.User.username + '/' + self.Animal.Name) Forms.py: from django.forms import ModelForm from encounters.models import Animal, Encounter import datetime class Open_Encounter_Form(ModelForm): class Meta: model = Encounter fields = ['encounter_date', 'user','animal','handling_time','crate_time','holding_time','comments'] Views.py: from encounters.models import Animal, … -
Configure Nginx with Vue.js, Django Rest Framework as backend and /api/ on same server?
I am in a process of deploying my newly developed e-commerce to a Ubuntu server that I have. I have already set up Nginx for Frontend and for Backend. The whole application is working fine. The only problem is DRF API that doesn't get anything from the backend (it doesn't send emails, users can't register). All of that gets error 500. It seems to me that I still need to add /api/ to my Nginx configuration, but when I do that the whole app goes down. Could someone explain the best way to set this up in "sites-available"? Thank you! Here is my Sites-Available for Backend: upstream perulab_app_server { server unix:/webapps/perulab/venv/run/gunicorn.sock fail_timeout=0; } server { listen 8000; server_name 172.16.7.52; client_max_body_size 4G; location /static/ { root /webapps/perulab/web-backend; } location /media/ { root /webapps/perulab/web-backend; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://perulab_app_server; } } } And this is my Sites-Available for Backend: server { listen 8010; listen [::]:8010; server_name _; charset utf-8; root /webapps/perulab/web-frontend/dist; index index.html index.htm; location / { try_files $uri /index.html; } } When I use it the way it is right now, console prints this error: GET http://172.16.7.52:8000/api/v1/get-user-details/ 500 … -
Can't deploy Python Django Flask app to Heroku?
I keep trying to deploy my app and keep getting the following error: at=error code=H10 desc="App crashed" method=GET path="/" host=binary-background-generator.herokuapp.com request_id=9b6e3182-d90a-41ca-9a11-01da97047792 fwd="66.181.213.97" dyno= connect= service= status=503 bytes= protocol=https Procfile: web: gunicorn binary-background-generator.wsgi requirements.txt: aiohttp==3.7.4.post0 async-timeout==3.0.1 attrs==21.2.0 blinker==1.4 chardet==4.0.0 click==8.0.1 colorama==0.4.4 Cython==0.29.24 Flask==2.0.1 idna==3.2 itsdangerous==2.0.1 Jinja2==3.0.1 MarkupSafe==2.0.1 multidict==5.1.0 Pillow==8.3.2 pyudorandom==1.0.0 Send2Trash==1.8.0 typing-extensions==3.10.0.2 Werkzeug==2.0.1 yarl==1.6.3 settings.py: # Configure Django App for Heroku. import django_heroku django_heroku.settings(locals()) Folder and file structure: Screenshot from VS Code -
Filter django query set based on whether a foreign key relationship exists
So I have two models. class Post(models.Model): id = models.OidField('object id', unique=True) class ArchivedFlag(models.Model): commit = models.ForeignKey(Commit, on_delete=models.CASCADE, related_name='archived_flag') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='archives') In views.py I have generated a list of all posts by some criteria, 'plist'. I want to filter the list based on posts that DO NOT have an ArchivedFlag object relationship. Basically the ArchivedFlag model is a tool hide certain posts. How can I do this? I'm trying to do something along the lines of plist = plist.exclude(models.ForeignKey.commit exists) but I'm unsure of the exact syntax. -
Firebase admin FCM error: Exactly one of topic, token or condition is required
I have integrated fcm-django==1.0.5 in my project, with firebase-admin==5.0.2 sending push notifications by user_id is working perfectly, on the other hand sending messages to the topic is giving this error: File "project_name/.venv/lib/python3.8/site-packages/firebase_admin/_messaging_encoder.py", line 681, in default raise ValueError('Exactly one of token, topic or condition must be specified.') ValueError: Exactly one of token, topic or condition must be specified. I tried to resolve it and came to this answer, which says "Avoid sending empty fcm token to Firebase. When we send an empty fcm token, Firebase gives us the below error" for that I even listed by registrations token, they are not empty. from fcm_django.models import FCMDevice >>> list(FCMDevice.objects.all().values('registration_id')) [{'registration_id': 'dVA1234XtoEdxk0i9J6srWM:APA91bHM3EBHkLYTIR2wAkop28Kn4RmI0HouifDazT7zCU5MXDIvrbVvzpZC3YiKDoDR9Wj-2DJ-d4_yPIhSfe_XU7Ac8QB2PXcOFOxwLRp3AGCLM18NVQz_N5NLQqFmIaArB'}, {'registration_id': 'ekpeG8fKTzWKANLA4UtIDV:APA91bFKkc32o4ke85iMfMqOIylY9zo599eTBHJNlWFxUA52PtAFBC3RlAIPTZ5P4578-OY6Iy1jGjGh3irgcGnXC3f6YHN3nrsrvU7N7A2VVssN9uPLWM55N7Kn5EVk8oyz'}] I have put up a print statement in the virtual environment to debug this issue, and in the output, I can see that both token, and title is getting passed, even though I am not sending the token, but it is taking it automatically. My code to send user messages to topic: def send_user_messages_to_topic(topic_name,title=None,body=None,image=None,data=None, extra_notification_kwargs=None,api_key=None,**kwargs): # print(topic_name, title, body, data, image) # Subscribing # FCMDevice.objects.all().handle_topic_subscription(True, topic=topic_name) # Sending messages to topic result = FCMDevice.objects.all().send_message( Message( notification=Notification(title=title,body=body,image=image), topic=topic_name, data=data, ) ) I have recently upgraded to fcm-django--1.0.5, is this … -
django is not reading javascript form-data files
so when I try to send files to Django server it raises ton of errors: Traceback (most recent call last): File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\Image.py", line 2972, in open fp.seek(0) AttributeError: 'NoneType' object has no attribute 'seek' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\asgiref\sync.py", line 482, in thread_handler raise exc_info[1] File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 38, in inner response = await get_response(request) File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\asgiref\sync.py", line 444, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\asyncio\tasks.py", line 442, in wait_for return await fut File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\concurrent\futures\thread.py", line 52, in run result = self.fn(*self.args, **self.kwargs) File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\asgiref\sync.py", line 486, in thread_handler return func(*args, **kwargs) File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\TM\سطح المكتب\New folder\web\views.py", line 86, in makeAccountApi IMG=RESIZE(Image) File "C:\Users\TM\سطح المكتب\New folder\web\helpers.py", line 110, in RESIZE im = Image.open(Img) File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\Image.py", line 2974, in open fp = io.BytesIO(fp.read()) AttributeError: 'NoneType' object has no attribute 'read' when I print request.body and request files and request POST it prints: b'[object FormData]' <MultiValueDict: {}> <QueryDict: {}> when I print file it console.log: C:\fakepath\download.jpg and after it it console.log: request.js:62 [Deprecation] Synchronous XMLHttpRequest on the main thread … -
Django Customize PasswordResetView: __init__() missing 1 required positional argument: 'user'
I try to customize Django PasswordResetView in order to validate the length of the password but I get this error: TypeError at /accounts/password_reset/ __init__() missing 1 required positional argument: 'user' views.py from django.contrib.auth import views as auth_views class PasswordResetView(auth_views.PasswordResetView): form_class = PasswordResetForm template_name = "accounts/users/password_reset.html" email_template_name = "accounts/users/password_reset_email.html" subject_template_name = "accounts/users/password_reset_subject.txt" from_email = settings.EMAIL_HOST_USER success_url = reverse_lazy("accounts_password_reset_done") forms.py class PasswordResetForm(SetPasswordForm): def clean_new_password1(self): password = self.cleaned_data.get("new_password1") if len(password) < 12: raise forms.ValidationError("Password must be at least 12 characters.") return password It is obvious that SetPasswordForm class needs to be taken user upon initialization: class SetPasswordForm(forms.Form): . . . def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) I do not find a clear solution to how to pass user data to PasswordResetView and PasswordResetForm because user data is used upon PasswordResetForm instance creation. -
How To Fix Django ValueError: Field 'persons' expected a number but got ''
I Don't Know How To Fix This Error I Run The Command python manange.py makemigrations, python manage.py migrate But it's is not fixing. i am creating ordering form I added a IntField it's called person it's means how many number of persons you need? There is my forms.py: class LeadModelForm(forms.ModelForm): class Meta: model = Lead fields = ( "first_name", "last_name", "email", "phone_number", "foodlancer", "location", "persons", ) This my models.py: class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) organisation = models.ForeignKey(UserProfile,null=True, blank=True, on_delete=models.SET_NULL) location = models.CharField(max_length=250) foodlancer = models.ForeignKey("Agent",null=True, blank=True, on_delete=models.SET_NULL) catagory = models.ForeignKey("Catagory", related_name="leads" ,null=True, blank=True, on_delete=models.SET_NULL) date_added = models.DateTimeField(auto_now_add=True) phone_number = models.CharField(max_length=20) email = models.EmailField() persons = models.IntegerField(max_length=30) def __str__(self): return f"{self.first_name} {self.last_name}" class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.user.email If I Even Remove Persons Var I Get Same Error I Hope You Can Help Me Thanks <3 -
Django - How can add multiple forms according to input enter number or with click add more button
I have an input field where the will customer add a number for buy membership then will get forms according to numbers 1,2, or 5 then will show 1,2, or 5 forms with input fields in which will add data. How can add this type of functionality? Because I'm a beginner in python Django. Thanks For example: customer will come to the site and click on buy membership the first page will How many Memberships do you want to buy? ==> input Field in which add 1,2, or 5 based on how many members enter a show a page to collect information of members 3rd step collect customer/parent information -
Can I use a keyword argument from another app to connect the URLs of two different aps together?
I'm currently developing an application using the Django REST Framework and Vue in which people can monitor a device's signal outputs. For some context, I created a custom user model with a unique UUID4 user ID that would be assigned to each user. This model is in a Django app that I called accounts. Similarly, I have the user's data recording sessions and associated data in separate models in an app that I call studio. My problem is this: I realized I would like to associate the data collected to the user's account and whatever session they wish to tie this data to. However, since these models are in different Django apps, I am getting the error get() got an unexpected keyword argument 'user_id' when I try to tie the URLs of the account and studio apps together. Relevant code snippets are below: models.py (in studio) from django.db import models class Session(models.Model): user_id = models.ForeignKey( 'accounts.CustomUser', on_delete=models.CASCADE) session_id = models.CharField(max_length=100, unique=True, blank=False) def get_associated_user_id(self): return (f'{self.user_id}') def __str__(self): return (f"Session ID: {self.session_id}") class LaserData(models.Model): user_id = models.ForeignKey( 'accounts.CustomUser', on_delete=models.CASCADE) session_id = models.ForeignKey('Session', on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) laser_current = models.DecimalField(max_digits=8, decimal_places=3) laser_temperature = models.DecimalField(max_digits=8, decimal_places=3) laser_temperature_set = models.DecimalField(max_digits=8, decimal_places=3) tec_voltage_positive = … -
I can't filter get data from my url to save into
I want to save transaction and increase the number of votes base on the status which i get from a response url nd redirect user to success page. But all transactions goes to error page rather even if they are successful. I want to check from the URL if the status== 'Approved' then i save the model and update the the model with new votes and redirect user to success page. this is the url response i get http://127.0.0.1:8000/process-payment/robert-yenji/000000000050/?votes=1?status=Approved&code=000&reason=Approved%3A%20Transaction%20successful!&transaction_id=314304818998 this is my views.py def process_payment(request, slug, amount): trans_id = request.GET.get('transaction_id') status = request.GET.get('status') reason = request.GET.get('reason') transaction_id = request.GET.get('transaction_id') if status == 'Approved': transaction = SuccessfulTransactionHistory( nominee_name=slug, transaction_id=transaction_id, amount=amount ) transaction.save() nomination = Nomination.objects.filter(slug=slug).values('votes') Nomination.objects.filter(slug=slug).update(votes=F('votes') + int(request.GET['votes'])) return redirect('/success') else: context = { 'error': reason } transaction = FailedTransactionHistory( nominee_name=slug, transaction_id=transaction_id, amount=amount ) transaction.save() return render(request, 'payment_error.html', context=context) -
Coding in UpdateVIEW of django
I have a edit button on my webapp, that reference a UpdateView with Django. The problem is that i don't know a way to execute calculations before they save the change on the database on the UpdateView. When i create a register, he get save after pass trought some calculations, functions, etc, and to create he call this function: def post_create(request): form = InsereCursosForm() if(request.method == 'POST'): form = InsereCursosForm(request.POST) print(form) if(form.is_valid()): def calculos(): post_nmCurso = form.cleaned_data['nmCurso'] post_acFaculdade = form.cleaned_data['acFaculdade'] post_nuMaterias = form.cleaned_data['nuMaterias'] post_nmInstituicao = form.cleaned_data['nmInstituicao'] post_nmPlayer = form.cleaned_data['nmPlayer'] post_nuHoras = form.cleaned_data['nuHoras'] post_acWorkshop = form.cleaned_data['acWorkshop'] post_acImplementacao = form.cleaned_data['acImplementacao'] post_acComunik = form.cleaned_data['acComunik'] def seFaculdade(post_acFaculdade, post_nuMaterias, post_nuHoras): if post_acFaculdade == True: post_nuHoras = post_nuMaterias * 4 return post_nuHoras else: return post_nuHoras post_nuHoras = seFaculdade(post_acFaculdade, post_nuMaterias, post_nuHoras) def ptWorkshopsF(post_nuHoras, post_acWorkshop): if post_acWorkshop == True: v = post_nuHoras * Decimal('0.2') return v else: return 0 def ptImplementacaoF(post_nuHoras, post_acImplementacao): if post_acImplementacao == True: return post_nuHoras * Decimal('0.45') else: return 0 def ptComunikF(post_nuHoras, post_acComunik): if post_acComunik == True: return post_nuHoras * Decimal('0.1') else: return 0 getcontext().prec=2 post_ptHoras = float((Decimal(post_nuHoras * 0.45))/Decimal('1')) post_ptWorkshop = float(Decimal(ptWorkshopsF(post_nuHoras, post_acWorkshop))/Decimal('1')) post_ptImplementacao = float(Decimal(ptImplementacaoF(post_nuHoras, post_acImplementacao))/Decimal('1')) post_ptComunik = float(Decimal(ptComunikF(post_nuHoras, post_acComunik))/Decimal('1')) new_post = Cursos(nmCurso=post_nmCurso, acFaculdade=post_acFaculdade, nuMaterias=post_nuMaterias,nmInstituicao=post_nmInstituicao, nmPlayer=post_nmPlayer,nuHoras=post_nuHoras, ptHoras=post_ptHoras,acWorkshop = post_acWorkshop, ptWorkshop=post_ptWorkshop ,acImplementacao= post_acImplementacao, ptImplementacao=post_ptImplementacao,acComunik … -
Issue sending keys, values to django Q()
I am trying to filter some IDs using a django query and trying to do it efficiently, I want to get the same result I got from a less efficient function I created before, but I am getting an issue with the dictionary key using Q from tmd import models from django.db.models import Q category = { "utility": models.Account.UTILITY, "system": models.Account.SYSTEM } country = { "Guatemala": models.Country.objects.get(name='USA'), "Honduras": models.Country.objects.get(name='CA'), } def get_a(stage=None, **kwargs): base_args =[] base_args.append(Q(stage__in=stage)) for key, value in kwargs.items(): base_args.append(Q(key= value)) a_ids = models.Account.objects.filter(*base_args).values_list('id', flat=True) print("Number of a_ids: {}".format(a_ids.count())) return a_ids input: a_ids = get_a(country=country["USA"], category=category["utility"]) The issue is located exactly in this line: base_args.append(Q(key= value)) If I can make an input that changes the key for every iteration, this will be solved -
Automatically increasing the value of a variable in generate_series
I ran into the need to automatically increment the value of a variable in generate_series. By the condition of the business logic, the field identifier in the model does not increase automatically. I decided to try to find the maximum id value in advance and, within the of the generation, try to simply increase it by 1. But I don't understand how to do this correct. max_id = Companies.objects.aggregate(Max('id')) # {'id__max': 1529367} value = max_id['id__max'] cursor.execute(f''' INSERT INTO test.companies( id, name, city_id, revenue, labors ) SELECT {value} = {value}+1, # This is what I want, but I don't know how to do it ( SELECT x[1 + ((random() * 25)::INT) % 3] FROM ( SELECT '{{Google,Yandex,Amazon}}'::text[] ) AS z2(x) WHERE SEQ = SEQ ), (random() * 3000)::INT, (random() * 3000)::INT, (random() * 3000)::INT FROM generate_series(1,10) SEQ; ''') All this I do as part of my work for Python Django. -
I'm learning django, so i need a front end sites to create the back end of it, so how can i get a free one?
I'm learning Django, so I need a front end sites to create the back end of it, so how can I get a free one ? -
django - disable Invitation object creation if User object with the email exists
I'd like to make sure that nobody can't create an Invitation object with an email that is already in a database either as Invitation.email or as User.email. To disallow creating Invitation with existing Invitation.email is easy: class Invitation(..): email = ...unique=True) Is it also possible to check for the email in User table? I want to do this on a database or model level instead of checking it in serializer, forms etc.. I was thinking about UniqueConstraint but I don't know how to make the User.objects.filter(email=email).exists() lookup there. -
HTTPSConnectionPool(host='api.razorpay.com', port=443): Max retries exceeded with url: /v1/orders
I was developing a social-media/eCommerce web app with Django. I want to add a payment gateway for purchasing products on the website for that I am using 'Razorpay'. I integrated it which worked fine with my app. But I wanted to store the transaction-related details in a model called 'TransactionDetails'. For that, I call a new function within the view that handles the Razorpay gateway. which creates the instance of the model and saves it. But for some reason when I call that function I am getting this error, please help me to understand what is happening. here's my view : from django.shortcuts import render, redirect import razorpay from django.views.decorators.csrf import csrf_exempt from weShare.settings import razorpay_id, razorpay_secret_key from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin from django.urls import reverse_lazy from social.models import * from social.forms import * from .models import TransactionDetails from social.models import UserProfile client = razorpay.Client(auth=(razorpay_id, razorpay_secret_key)) def home(request, pk): rentee = UserProfile.objects.get(user=request.user) renteeName = rentee.user renteeLocation = rentee.location post = Post.objects.get(pk=pk) renter = post.author product = post.productName subPeriod = post.subscriptionPeriod montlycharge = post.productMonthlyCharge loc = rentee.location order_amount = post.deposite*100 order_currency = 'INR' order_receipt = 'order_rcptid_11' notes = {'Shipping address': 'Bommanahalli, Bangalore'} # OPTIONAL payment_order = client.order.create(dict(amount=order_amount, currency=order_currency, payment_capture=1)) payment_order_id = … -
python Django Postgres Setup (with docker) .. Trying to make migrations for postgres but make file is failing
so its my first time building a stack from scratch i am trying to connect to postgres for better management but i am sure i have an error in my docker file or make file can any body shed some light on this for me ? code below make file build: docker build --force-rm $(options) -t bonkit_websites:latest . build-dev: $(MAKE) build options="--target development" compose-start: docker-compose up --remove-orphans $(options) compose-stop: docker-compose down --remove-orphans $(options) compose-manage-py: docker-compose run --rm $(options) website python manage.py $(cmd) docker.yml version: "3.8" x-service-volumes: &service-volumes - ./:/app/:rw,cached x-database-variables: &database-variables POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_USER: postgres x-app-variables: &app-variables <<: *database-variables POSTGRES_HOST: postgres services: website: tty: true image: bonkit_websites:latest command: python manage.py runserver 0.0.0.0:8000 volumes: *service-volumes enviroment: *app-variables depends_on: - db_migrate ports: - "8000:8000" db_migrate: image: bonkit_websites:latest command: python manage.py migrate volumes: *service-volumes enviroment: *app-variables depends_on: - postgres postgres: image: postgres ports: - "5432:5432" enviroment: - db-data:/var/lib/postgresql/data Docker File FROM python:3.9.7-slim as production ENV PYTHONBUFFERED=1 WORKDIR /app/ RUN apt-get update && \ apt-get install -y \ bash \ build-essential \ gcc \ libffi-dev \ musl-dev \ openssl \ postgresql \ libpq-dev COPY requirements/prod.txt ./requirements/prod.txt RUN pip install --user -r ./requirements/prod.txt COPY manage.py .manage.py #COPY setup.cfg ./setup.cfg COPY bonkit_website ./bonkit_website EXPOSE … -
How to render reverse fields using related name between foreign key models
I have two models if a foreign key relationship and a related name. I return a queryset of Foo and want to render fields of the related object Bar. However, item.link.value doesn't render anything. # Models class Foo(models.Model): item class Bar(models.Model: foo = models.Foreignkey(Foo, on_delete=models.CASCADE, related_name='link') value = models.Charfield(max_length=20) # View def test(request): qs = Foo.objects.all() context = { 'qs': qs } return render (request, 'somepage.html', context) # Template {% for item in qs %} <div> {{ item.link.value }} </div> -
Need help writing tests - Django framework
I am relatively new to Python with Django, and very new to writing tests. The app I'm working with allows a teacher to assign multiple assignments to a student. On the student dashboard, an assignment should only be available if the start date <= today's date. The student should only see the first assignment in the list. I need to compose tests to cover the following: create a few new assignments with different start dates and assign them to the currently logged in student use the same query that is used for the student dashboard to make sure that the only assignments returned are the ones with a start date <= today's date make sure that the only assignment the student sees on the dashboard is the one with the earliest start date Below I have posted the assignment code from models.py, as well as views.py code that shows what displays on the student dashboard. Please let me know if additional code is needed to help me get started with this. I would like to only use the built in django.test features to write my tests for now, if possible. Thanks very much for any help you can offer! models.py … -
Reload Form when select change
Is there a way to reload a form data in django when I change a select? I am trying to filter a select depending on the option selected in another without using ajax. What comes to mind is to use the __init__ of the form but I need to reload the form with the option selected in the first select and filtered the second. -
Gitlab returns Permission denied (publickey,password) for digitalocean server
I'm trying to implement CD for my dockerized Django application on the DigitalOcean droplet. Here's my .gitlab-ci.yml: image: name: docker/compose:1.29.1 entrypoint: [""] services: - docker:dind stages: - build - deploy variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 before_script: - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME - export WEB_IMAGE=$IMAGE/web:web - export NGINX_IMAGE=$IMAGE/nginx:nginx - apk add --no-cache openssh-client bash - chmod +x ./setup_env.sh - bash ./setup_env.sh - docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY build: stage: build script: - docker pull $IMAGE/web:web || true - docker pull $IMAGE/web:nginx || true - docker-compose -f docker-compose.prod.yml build - docker push $IMAGE/web:web - docker push $IMAGE/nginx:nginx deploy: stage: deploy script: - mkdir -p ~/.ssh - echo "$PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa - cat ~/.ssh/id_rsa - chmod 700 ~/.ssh/id_rsa - eval "$(ssh-agent -s)" - ssh-add ~/.ssh/id_rsa - ssh-keyscan -H 'gitlab.com' >> ~/.ssh/known_hosts - chmod +x ./deploy.sh - scp -o StrictHostKeyChecking=no -r ./.env ./docker-compose.prod.yml root@$DO_PUBLIC_IP_ADDRESS:/Pythonist.org - bash ./deploy.sh only: - master I have copied my Publick key to the production server (DO droplet). The build job is successful but the deploy stage failed with the following error: $ chmod 700 ~/.ssh/id_rsa $ eval "$(ssh-agent -s)" Agent pid 26 $ ssh-add ~/.ssh/id_rsa Identity added: /root/.ssh/id_rsa (abdul12391@gmail.com) $ ssh-keyscan -H 'gitlab.com' >> ~/.ssh/known_hosts … -
Django mod_wsgi Apache Server, ModuleNotFoundError: No Module Named Django
I read ton of articles, but still can't figure out what I'm missing. I'm running a django website from virtualenv. Here's my config file. The website address is replaced by <domain.com>, can't use that here. Config <VirtualHost *:80> ServerAdmin sidharth@collaboration-management ServerName <domain.com> ServerAlias <domain.com> DocumentRoot /home/sidharth/Downloads/gmcweb ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/sidharth/Downloads/gmcweb/static <Directory /home/sidharth/Downloads/gmcweb/static> Require all granted </Directory> <Directory /home/sidharth/Downloads/gmcweb/gmcweb> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess gmcweb python-home=/home/sidharth/Downloads/gmcwebenvlin python-path=/home/sidharth/Downloads/gmcweb WSGIProcessGroup gmcweb WSGIScriptAlias / /home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py </VirtualHost> Here's my WSGI.py file, didn't change anything never had to earlier import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gmcweb.settings') application = get_wsgi_application() Python Versions My virtualenv python version is 3.9.5 Default Google VM python version is 3.6.9 I installed apache modwsgi as well sudo apt-get install python3-pip apache2 libapache2-mod-wsgi-py3 Error Log File [Thu Sep 23 15:05:06.554545 2021] [mpm_event:notice] [pid 32077:tid 140392561593280] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Thu Sep 23 15:05:06.554594 2021] [core:notice] [pid 32077:tid 140392561593280] AH00094: Command line: '/usr/sbin/apache2' [Thu Sep 23 15:05:19.081581 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604] mod_wsgi (pid=32617): Target WSGI script '/home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py' c$ [Thu Sep 23 15:05:19.081638 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604] mod_wsgi (pid=32617): Exception occurred processing WSGI script '/home/sidharth/Downloads/g$ … -
How to run django-appointment project which is available in this site's github?https://pypi.org/project/django-appointments/ please help me
How to run django-appointment project which is available in this site's github?https://pypi.org/project/django-appointments/ -
How to add values for checked rows using javascript
I've uploaded a similar question in a previous post, but I'm re-posting because what I'm trying to achieve is a little clearer. We are outputting the list of students as a table. If we check the checkbox and click the Add Teacher button, we want the name of the currently logged in teacher to be added to the teacher field of the selected row. You can get the name of the currently logged in account with {{request.user.name}} . And I want it to be saved in DB by sending it to the server. <table class="maintable"> <thead> <tr> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Name</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Age</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Register Date</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Teacher</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Select</th> </tr> </thead> <tbody> {% for student in students %} <tr student-id="{{ student.id }}"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.register_date }}</td> <td>{{ student.techer }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <input type="button" value="Add Techer" class="addtecher"> Current student information is modified as follows. urls.py path('student/<int:id>/edit/', views.edit_student, name='edit_student') views.py def edit_student(request, id): student = get_object_or_404(Student, pk=id) edited_student, errors = Student.student_form_validation(request) if errors: return JsonResponse({'code': 'error', 'error': …