Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Contact Us form
How to use django rest framework to make a contact us form. What exactly should I have in the serializers and views. -
Relation not being stored django
I wrote the following code: class Predictor: def __init__(self, sofascore_id): self.sofascore_id = sofascore_id self.fixture = Fixture.objects.get(sofascore_id=sofascore_id) def add_prediction(self, prediction): self.fixture.predictions.add(prediction) self.fixture.save() def run(self, maximum, factor_1, factor_2, name, minimum=1): market_name = name[0:1] + name[1:].title().replace("_", " ") market = Market.objects.get_or_create(name=market_name, defaults={'name': market_name})[0] prediction = Prediction.objects.get_or_create(market=market, fixture=self.fixture, defaults={'market': market, 'fixture': self.fixture})[0] self.add_prediction(prediction) When executing this it stores the 'predictions' in the database properly, but when I try to retrieve them using f = Fixture.objects.get(sofascore_id="8645471").predictions.all() the results are: <QuerySet []> My models are as follows: class Market(models.Model): name = models.CharField(max_length=200) class Fixture(models.Model): sofascore_id = models.CharField(max_length=200) home = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="home") away = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="away") league = models.ForeignKey(League, on_delete=models.CASCADE, blank=True) round = models.CharField(max_length=200, default=None, blank=True, null=True) date = models.DateTimeField() statistics = models.ForeignKey(Statistics, on_delete=models.CASCADE, default=None, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return u'{0} - {1}'.format(self.home.name, self.away.name) class Prediction(models.Model): market = models.ForeignKey(Market, on_delete=models.CASCADE, blank=True) fixture = models.ForeignKey(to=Fixture, on_delete=models.CASCADE, related_name="predictions", null=True, blank=True) What am I doing wrong here? -
FOREIGN KEY constraint failed in signals
I tried to insert data into the table Account, but I keep getting this error message. I delete all my migrations and make migrations again but I keep getting this error. Here is my models. class Student(models.Model): user = models.OneToOneField(Account, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=True, blank=True) phone = models.CharField(max_length=15, blank=True, null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True, null=True) section = models.ForeignKey(Section, on_delete=models.CASCADE, default=1) dept = models.ForeignKey(Dept, on_delete=models.CASCADE, blank=True, null=True) batch = models.CharField(max_length=15, null=True, blank=True) USN = models.CharField(primary_key='True', max_length=100) DOB = models.DateField(default='1998-01-01') profile_image = models.ImageField(upload_to='student/profile_images/%Y/%m/%d/', blank=True, null=True) address = models.CharField(max_length=300, null=True, blank=True) nationality = models.CharField(max_length=100, null=True, blank=True) guardian_name = models.CharField(max_length=200, null=True, blank=True) guardian_number = models.CharField(max_length=15, null=True, blank=True) guardian_address = models.CharField(max_length=300, null=True, blank=True) blood_group = models.CharField(max_length=3, null=True, blank=True) exam_name = models.CharField(max_length=300, null=True, blank=True) background = models.CharField(max_length=300, null=True, blank=True) passing_year = models.CharField(max_length=8, null=True, blank=True) score = models.CharField(max_length=10, null=True, blank=True) school_name = models.CharField(max_length=300, null=True, blank=True) country = models.CharField(max_length=100, null=True, blank=True) certificate = models.FileField(upload_to='certificates/%Y/%m/%d/', null=True, blank=True) Here is Account model. class Account(AbstractBaseUser, PermissionsMixin): unid = models.CharField(max_length=20, unique=True, null=True, blank=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True) user_permissions = models.ManyToManyField( Permission, … -
Django can't login the superuser in admin page
So , I am trying to make an register and login system . I want to customize it using the custom user model , where I can save my data and extend the model. I am using AbstractBaseUser and BaseUserManager to do that. The problem is I can't login in the django admin page. I created already a superuser so I can access admin section , I enter the Email and Password correct and then I have this error : "Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive." What my goal is , is that I want to be able to access the administration by login ( i mean fixing this red message and being able to use administration as an superuser ), and then add to the Userr model the specialkey field which will take place in the login view as the username in the built-in django authentication system. This is the message error : https://i.stack.imgur.com/TL1wT.png. I hope someone helps me with this , because I can't see the problem in the code , I've been trying to fix this for almost 3 days. The models.py: from django.db import … -
on_delete=models.PROTECT not working in Django
I'm trying to create a model, called contract, that will have a foreign key to the instance of the user. I don't want the contract to be deleted if the user gets deleted it keeps the contract because of on_delete=models.PROTECT. This is my entire model: class Contract(models.Model): # * added by photographer model_email = models.EmailField(max_length=240, blank=False) shoot_location = models.CharField(max_length=240, blank=False) shoot_date = models.DateField(default=date.today, blank=False) # todo: contract content # ? how to add photographer's fist and last name to contract? # * added by model model_name = models.CharField(max_length=120, blank=False) model_address = models.CharField(max_length=480, blank=False) # todo: signature # * added automatically photographer = models.ForeignKey( User=get_user_model(), verbose_name=_("photographer"), on_delete=models.PROTECT ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) signed = models.BooleanField(default=False, blank=False) # todo add PDF file get_url = models.URLField( default=secrets.token_urlsafe(64), editable=False, blank=False, help_text="The url emailed to the model to sign the contract." ) def __str__(self): return f"{self.model_full_name} - {self.date_created}" But when I run makemigrations I get the following error: File "/Users/mark/Documents/hannerly-b/hannerly/contract/models.py", line 8, in <module> class Contract(models.Model): File "/Users/mark/Documents/hannerly-b/hannerly/contract/models.py", line 25, in Contract on_delete=models.PROTECT TypeError: __init__() missing 1 required positional argument: 'to' -
django.db.utils.ProgrammingError: cannot cast type time without time zone to timestamp with time zone While migrating to postgresql on heroku
I don't know sql. I have a time_posted field in my models.py from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() date_posted = models.DateField(auto_now_add=True) time_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title This app is running on my local machine. But when i try to migrate my model schema in Postgresql on heroku, I am getting an error cmd image of error -
Models and ModelForms: needs to have a value for field "id" before this many-to-many relationship can be used
I'm using a Django Model with some many-to-many fields. I'm also using a ModelForm to generate the associated form. It is my understanding that, provided nothing else is overridden, Django should be able to handle many-to-many fields being saved in the ModelForm? For me, attempting to do this is causing this error: Internal Server Error: /cameramodel/create/ Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/edit.py", line 172, in post return super().post(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/edit.py", line 141, in post if form.is_valid(): File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 185, in is_valid return self.is_bound and not self.errors File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 180, in errors self.full_clean() File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 383, in full_clean self._post_clean() File "/usr/local/lib/python3.8/site-packages/django/forms/models.py", line 403, in _post_clean self.instance.full_clean(exclude=exclude, validate_unique=False) File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 1188, in full_clean self.clean() File "./schema/models.py", line 1439, in clean if self.metering_modes is True: File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 527, in __get__ return self.related_manager_cls(instance) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line … -
Django redirect direct to the same page
I have a render_bfi2() function that presents a test. I don't want users to wait seven days to retake the test. I'm using too_soon_test_request() function to check this. But return redirect('pages:home_page') line of the code isn't working. I end up seeing the message but no redirect. def too_soon_test_request(request, inv): '''Makes sure that there is a specified amount of days between two test sessions. ''' now = timezone.now() user_id = request.user.id response = ItemResponse.objects.filter(user=user_id, item__inventory__title=inv.title)[0] last_time = response.response_time time_diff = last_time - now if time_diff < datetime.timedelta(days=7): messages.warning(request, 'You have to wait to take this test again!') return redirect('pages:home_page') @login_required def render_bfi2(request): '''Renders Big Five Inventory-2 and save responses.''' inventory = Inventory.objects.get(code_name='bigfiveinventory2') items = Item.objects.filter(inventory=inventory).order_by('item_rank') user = request.user too_soon_test_request(request, inv=inventory) if request.method == 'POST': responses = [] for i in range(1, items.count()): item = 'item' + str(i) item_response = request.POST[item] responses.append(item_response) responses = [i.split('_') for i in responses] responses = [[int(i) for i in sub] for sub in responses] for i in responses: current_item = inventory.items.get(item_rank=i[0]) response = i[1] item_response = ItemResponse(item=current_item, user=user, response_time=timezone.now(), response=response) item_response.save() return redirect('pages:home_page') else: test_title = inventory return render(request, 'personality_tests/render_bfi-2.html', {'bfi2_items': items, 'test_title': test_title}) -
AttributeError: '…' object has no attribute '_set'
I wrote the following code: class Market(models.Model): name = models.CharField(max_length=200) class Fixture(models.Model): home = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="home") away = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="away") league = models.ForeignKey(League, on_delete=models.CASCADE, blank=True) round = models.CharField(max_length=200, default=None, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return u'{0} - {1}'.format(self.home.name, self.away.name) class Prediction(models.Model): market = models.ForeignKey(Market, on_delete=models.CASCADE, blank=True) fixture = models.ForeignKey(to=Fixture, on_delete=models.CASCADE, related_name="fixture", null=True, blank=True) I'm trying to get all the predictions attached to one fixture, using the following code: f = Fixture.objects.get(sofascore_id="8645471").prediction_set But this produces the following error: AttributeError: 'Fixture' object has no attribute 'prediction_set' What am I doing wrong here? -
Dockerizing DJango and Postgresql: django.db.utils.ProgrammingError after running manage.py migrate
I just dockerized my final django application according to this tutorial, creating one container for the postgre database and one for django. When trying to migrate the tables in the new database using docker-compose -f final.yml exec django python manage.py migrate --noinput the following error occurs: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "internal_app_account" does not exist LINE 1: ...", "internal_app_account"."is_registered" FROM "user_mana... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/checks.py", line 74, in check_user_model if isinstance(cls().is_anonymous, MethodType): File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 474, in __init__ val = field.get_default() File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 829, in get_default return self._get_default() File "/home/app/web/internal_app/models.py", line 8, in generate_dummy_email print(dummy_mail_accs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", … -
Django Application Run Script for Each Session Seperately
I've already achieved run django app , for example there are one button and user input item. When the user enter the IP address and push the button , in background paramiko ssh script works and connect to this device. After that user redirected confirmation page and next button is pushed and run "show hostname" command.(just for example). How can i make this process for multiple session separately?It works for one user,however when the second user push button at the same time, the process is being complicated and return error. I just read about threading but i am not sure how to apply to this application properly even if it resolve the issue. I am just network engineer and could not find right answer in my search. I just summarized my code as below: def create(request): if request.method=="POST": SSH_CONNECTION() return redirect("/sendpage") def submit(request): if request.method == "POST": SSH_SEND() return redirect("/") -
gaierror, [Errno 11001] getaddrinfo failed in django
I am trying to send mail from Django to Gmail but I am getting Gaierror in my browser when I run my server enter image description here Here is my views.py code from django.shortcuts import render from django.core.mail import send_mail def mail(request): subject = "Real programmer contact" msg = "Congratulations for your success" to = "amangupta.2003@rediffmail.com" res = send_mail(subject, msg, 'testgupta.555@gmail.com', [to]) if(res == 1): msg = "Mail Sent" else: msg = "Mail could not sent" return render(request, 'testapp/index.html',{'msg':msg}) Here is a settings.py code EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gamil.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'testgupta.555@gmail.com' EMAIL_HOST_PASSWORD = '555amangupta2' Here is HTML code <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>mail box</title> </head> <body> {{msg}} </body> </html> and last is urls.py path('mail/',views.mail), I am not able to resolve this problem. -
TypeError: blog() missing 1 required positional argument: 'todo_id'
Hi i am new in django and i try to do a todo app in my page.I have a list of items with radio buttons. I want to change the list element to True from false when click the submit button. Everytime when i want to come to page i see this error: TypeError at /home/blog/ blog() missing 1 required positional argument: 'todo_id'. How to repair that?? blog.html <form action='{% url 'home:acceptTodo' todo.id %}' method="post"> {% csrf_token %} <div class="kd"> {% for tu in todo_items %} <ul> <input type="radio" id="male" name="jimba" value="male"> <label for="male">{{ tu.todo_text }}</label><br> </li> </ul> {% endfor %} <button value='Vote' type="submit" name="button">Zakoncz zadanie</button> </div> </form> views.py def blog(request, todo_id): #notes new_note = NotesForm() latest_notes_list = Notes.objects.all() #to-do domb = TodoForm_Two lipa = TodoForm todo = ToDo.objects.get(pk='todo_id') todo_items = ToDo.objects.filter(todo_complete=False) return render(request, 'home/blog.html',{'latest_notes_list': latest_notes_list, 'form':new_note, 'todo_items':todo_items, 'tadla':lipa, 'domb':domb, 'todo':todo}) def acceptTodo(request, todo_id): todo= ToDo.objects.get(pk=todo_id) succes = todo.objects_set.all(pk=request.POST['jimba']) succes.todo_complete = True succes.save() return redirect('/home/blog') urls.py from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('', views.index, name='index'), path('blog/', views.blog, name='blog'), path('blog/add', views.addNote, name='add'), path('blog/<int:notes_id>', views.DetalicNote, name='detalicNote'), path('blog/addTodo', views.addTodo, name = 'addTodo'), path('blog/<int:todo_id>/', views.acceptTodo, name = 'acceptTodo'), ] models.py class ToDo(models.Model): todo_text = models.CharField(max_length=30) todo_complete … -
Getting 'ImportError: cannot import name ' when i run it using django
I am new to django and trying to execute a simple hello world program I created urls.py file and trying to import views. When run manage.py i get "ImportError: cannot import name 'views' from django.views (C:\Users\XYZ\Envs\test\lib\site-packages\django\views__init__.py) Can anyone please help me out here Thanks Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\XYZ\appdata\local\programs\python\python37-32\lib\threading.py", line 926, in _bootstrap_inner self.run() File "c:\users\XYZ\appdata\local\programs\python\python37-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\XYZ\Envs\test\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\XYZ\Envs\test\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\XYZ\Envs\test\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\Users\XYZ\Envs\test\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\XYZ\Envs\test\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\XYZ\Envs\test\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\XYZ\Envs\test\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\XYZ\Envs\test\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\XYZ\Envs\test\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\XYZ\Envs\test\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\XYZ\Envs\test\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\XYZ\Envs\test\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "c:\users\XYZ\appdata\local\programs\python\python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen … -
Scraped data is not getting displayed on the webpage
I am working with Beautiful Soup for web scraping. I want to display the data on the webpage but the code doesn't works. This is my views.py: def index(request): session=request.Session() session.headers={"User-Agent":"Googlebot/2.1 (+http://www.google.com/bot.html)"} url="https://weather.com/en-IN/weather/today/l/9d531fc505eb4a93a90a7e8303ccaa22a142c9370b68391129de5019ee7adf5b" content=session.get(url,verify=False).content soup=BeautifulSoup(content,"html.parser") for hit in soup.findAll(attrs={'class':'today_nowcard-temp'}): head=hit.text summ=(hit.next_sibling.text) weather=News() weather.head=head weather.summ=summ weather.save() return redirect("../") def news_list(request): weathers=News.objects.all() context={ 'object_list': weathers, } return render(request,'index.html',context) This is my index.html where I want the data to be displayed: <div class="trending-top mb-30"> <div class="trend-top-img"> <div class="trend-top-cap"> <span>{{head}}</span> <h2><a href="details.html">{{summ}}</a></h2> </div> </div> </div> Below is my models.py: from django.db import models class News(models.Model): head=models.CharField(max_length=100) summ=models.CharField(max_length=100) def __str__(self): return self.title -
How validate 2 model? class Defeito model numerodeserie and class fct model Numero_de_serie
def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super().get_search_results(request, queryset, search_term) try: from Smt.models import Defeito error = Defeito.objects.filter(Numerodeserie = 'search_term') except ValueError: pass else: queryset |= self.model.objects.filter(Numero_de_serie = error) return queryset, use_distinct -
How to map model data(query set) into dictionary and use it as ordered list
Mapping over values in a python dictionary -
unable to print multiple values in django
I have a code that tests if the different directories exist in the URL. Example - www.xyz.com/admin.php here admin.php is the directory or a different page I am checking these pages or directories through opening a text file. suppose the following is the file.txt index.php members.html login.php and this is the function in views.py def pagecheck(st): url = st print("Avaiable links :") module_dir = os.path.dirname(__file__) file_path = os.path.join(module_dir, 'file.txt') data_file = open(file_path,'r') while True: sub_link = data_file.readline() if not sub_link: break req_link = url + "/"+sub_link req = Request(req_link) try: response = urlopen(req) except HTTPError as e: continue except URLError as e: continue else: print (" "+req_link) the code is working fine and prints all the webpages that are actually there in the console. but when I try to return it at the last to print it in the Django page. return req_link print (" "+req_link) it only shows the first page that makes the connection from the file.text. Suppose, all the webpages in the file.txt are actually there on a website. it prints all the in the console but returns a single webpage in the django app I tried using a for loop but it didn't work -
Adding Keywords not showing up in Template
Hi I am adding keywords for meta tag in the templates, I don't know why they are not showing up when I inspect the page, noting that the other things in the models is showing such title, image and the rest. <meta name="keywords" content=" "> Here is the models.py : class Item(models.Model): title = models.CharField(max_length=100) keywords = models.CharField(max_length=100) def __str__(self): return self.title Here are the views: def products(request): context = { 'items': Item.objects.all() } return render(request, "products.html", context) here is the template: {% extends "base.html"%} {% block head_title %} Welcome to {% endblock %} {% block content %} {% for item in object_list %} {% block keywords %} {{item.keyword}}{% endblock %} {% endfor %} {% endblock content %} -
Django Nested Relationship
I'm trying to query a nested relationship with Django REST, but I can't seem to nest it properly. I want to query all users and model nested within the users. This is the model I want nested within the JSON output: class ChallengeInstance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) id = models.AutoField(primary_key=True) color_scheme = models.ForeignKey(ColorScheme, on_delete=models.CASCADE, null=True, blank=True) paint_technique = models.ForeignKey(PaintTechnique, on_delete=models.CASCADE, null=True, blank=True) theme = models.ForeignKey(Theme, on_delete=models.CASCADE, null=True, blank=True) Here is my serializers: class ChallengeInstanceSerializer(serializers.ModelSerializer): class Meta: model = ChallengeInstance fields = ['id', 'color_scheme', 'paint_technique', 'theme'] class UserSerializer(serializers.ModelSerializer): challengeinstance = ChallengeInstanceSerializer(many=True, read_only=True) class Meta: model = User fields = ['id', 'username', 'challengeinstance'] Any ideas why those serializers do not work? -
Docker,Django+uwsgi+nginx can't work coorrectly
This is my code.(django codes have not commit,not the problem) click here When I use "docker-compose",I visit "XXX.XXX.XXX.XXX:9001",it can be visited (surely can't load static files,it's normal),but when I visit "XXX.XXX.XXX.XXX:80",nginx 502 error,I read error.log and it shows "[error] 6#6: *1 connect() failed (111: Connection refused) while connecting to upstream, client: , server: , request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://127.0.0.1:9000"," -
Can Django handle large spikes in usage?
To make this question concrete, suppose you develop a web site in Django and deploy it on a small AWS or GCP (your choice) instance, which is more than sufficient for your current users. However, while you are asleep, Justin Bieber tweets a link to your site, temporarily spiking its users enormously. Is there anything you could have done to prepare for such a spike other than constantly paying for way more hardware than you normally need? -
Can not send password reset mail to user in django from local machine server
Here are my URL patterns path('password_reset/',auth_views.PasswordResetView.as_view(),name= 'password_reset'), path('password_reset_done/',auth_views.PasswordResetDoneView.as_view(),name= 'password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(),name= 'password_reset_confirm'), path('password_reset_complete/',auth_views.PasswordResetCompleteView.as_view(),name= 'password_reset_complete'), here is my smtp configuration: #smtp confuguration EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtp.gmail.com' EMAIL_PORT=578 EMAIL_USE_TLS=True EMAIL_HOST_USER='my mail' EMAIL_HOST_PASSWORD='password' I have turned on less secure apps and turned of 2 factor verification of my email. but when I submit the form the following error message shows up like TimeoutError at /password_reset/ [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. How can I fix this? I am using a custom user model. -
how to tell if a screen is add or change in django admin
I am trying to determine if the admin screen in Django is add or change in the save method. If I internet search on this, I cannot find any answer. What is the proper way to do this in Python? -
Get data from a view with AJAX Django
I don't know how to solve this problem The situation is this: I have an html file called detail.html, where I have the following code: {% for choice in question.choice_set.all %} <div class="input-group-text"> <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}"> {{ choice.choice_text }}</label> </div> {% endfor %} <br /> <button type="submit" class="btn btn-light mb-2">Vote</button> I want to send this form with "Vote" button and print another html called results.html with AJAX. I can't do {% extends "results.html" %} because the results.html also has a layout.html extension and must-have info form its view.py function. {% extends "app/layout.html" %} {% block content %} <h2>{{ title }}.</h2> <h3>{{ message }}</h3> <h1>{{ question.question_text }}</h1> {% if not request.user.is_authenticated %} {% if choice.correct %} <h3 style="color: green">¡ Respuesta Correcta !</h3> {% else %} <h3 style="color: red">¡ Respuesta Incorrecta !</h3> {% endif %} {% endif %} <table class="table"> <thead> <th scope="col">Choice text</th> <th scope="col">Votes</th> </thead> <tbody> {% for choice in question.choice_set.all %} <tr> <td>{{ choice.choice_text }}</td> <td>{{ choice.votes }}</td> </tr> {% endfor %} </tbody> </table> <a href="{% url 'chart' question.id %}"> Ver grafica</a><br /> <a href="{% url 'index' %}">Contestar otra pregunta?</a> {% endblock %} views.py def results(request, question_id): question …