Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
else block not executing in Django/python
query= request.GET.get("query") if query: story=Story.objects.filter(Q(title__icontains=query) | Q(body__icontains=query)| Q(des__icontains=query)) else: tag=get_object_or_404(Tag, slug=query) story=Story.objects.filter(tags__in=[tag]) I am implementing this search functionality in my django project. It is intended to allow me search database by title, body, description, and tags. While I can search the first three with strings, tags can only be searched by id, hence the need to seperate it into a seperate else block. But I don't understand why the else block isn't executing when I expect it to. -
how do i perform a math operation in django?
i am trying to calculate the new_balance when a user withdraw any amount from thier main balance. i am trying to perform this operation when the form is being submitted but i do not know if this is the perfect way to perform this operations. This is what i am trying to achive. @login_required def withdrawal_request(request): user = request.user profile = Profile.objects.get(user=user) total_investment = PurchasedPackage.objects.filter(paid=True, user=request.user).aggregate(Sum("investment_package__price"))['investment_package__price__sum'] bonus_earning = profile.earning_point total_ref_earning = profile.referral_point bonus_point = profile.bonus_point social_share_points = profile.social_share_points pending_payout = WithdrawalRequest.objects.filter(user=request.user, status="pending").aggregate(Sum("amount"))['amount__sum'] if pending_payout == None: pending_payout = 0 total_payout = WithdrawalRequest.objects.filter(user=request.user, status="settled").aggregate(Sum("amount"))['amount__sum'] try: all_earning = total_investment + bonus_earning + total_ref_earning + bonus_point + social_share_points except: all_earning = bonus_earning + total_ref_earning try: new_balance = total_investment + bonus_earning + total_ref_earning + bonus_point + social_share_points except: new_balance = bonus_earning + total_ref_earning if request.method == "POST": form = WithWithdrawalRequestForm(request.POST) if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user if new_form.amount > all_earning: messages.warning(request, "You cannot withdraw more than what is in your wallet balance.") return redirect("core:withdrawal-request") elif pending_payout > new_balance: messages.warning(request, "You have reached your wallet limit") return redirect("core:withdrawal-request") else: new_form.save() new_balance = new_balance - new_form.amount messages.success(request, f"Withdrawal Request Is Been Processed...") return redirect("core:withdrawal-request") else: form = WithWithdrawalRequestForm(request.POST) context = { "form":form, "new_balance":new_balance, } … -
Django Login suddenly stopped working - timing out
My Django project used to work perfectly fine for the last 90 days. There has been no new code deployment during this time. Running supervisor -> gunicorn to serve the application and to the front nginx. Unfortunately it just stopped serving the login page (standard framework login). I wrote a small view that checks if the DB connection is working and it comes up within seconds. def updown(request): from django.shortcuts import HttpResponse from django.db import connections from django.db.utils import OperationalError status = True # Check database connection if status is True: db_conn = connections['default'] try: c = db_conn.cursor() except OperationalError: status = False error = 'No connection to database' else: status = True if status is True: message = 'OK' elif status is False: message = 'NOK' + ' \n' + error return HttpResponse(message) This delivers back an OK. But the second I am trying to reach /admin or anything else requiring the login, it times out. wget http://127.0.0.1:8000 --2022-07-20 22:54:58-- http://127.0.0.1:8000/ Connecting to 127.0.0.1:8000... connected. HTTP request sent, awaiting response... 302 Found Location: /business/dashboard/ [following] --2022-07-20 22:54:58-- http://127.0.0.1:8000/business/dashboard/ Connecting to 127.0.0.1:8000... connected. HTTP request sent, awaiting response... 302 Found Location: /account/login/?next=/business/dashboard/ [following] --2022-07-20 22:54:58-- http://127.0.0.1:8000/account/login/? next=/business/dashboard/ Connecting to 127.0.0.1:8000... … -
Avoid Django form being resubmitted by using HttpResponseRedirect
My views.py runs code fine when I press a button on my HTML page, views.py: def start_or_end_fast(request): #If starting fast, add a row to the db: #fast_finished = False #start_date_time using = current time #end_date_time using = current time if request.method == 'POST' and 'start_fast' in request.POST: add_fast = logTimes(fast_finished=False,start_date_time=datetime.now(),end_date_time=datetime.now()) add_fast.save() print(add_fast.start_date_time,add_fast.end_date_time) print('Fast started') #return render(request,'startandstoptimes/index.html') return HttpResponseRedirect('startandstoptimes/index.html') You can see my commented return line, this works but when I refresh the page I can resubmit the data, I want to avoid this. In researching my solution, I saw this could be solved using HttpResponseRedirect but I am not able to get this to work with my code, the more I change the more broken things become. My application urls.py: from turtle import home from django.urls import path,include from . import views urlpatterns = [ path('', views.start_or_end_fast,name="start_or_end_fast") ] My project urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('startandstoptimes.urls')) ] I believe it is related to the URLs, due to the 404 message I see: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/startandstoptimes/index.html Using the URLconf defined in myfastingsite.urls, Django tried these URL patterns, in this order: admin/ [name='start_or_end_fast'] The current path, startandstoptimes/index.html, didn’t match any of these. Am … -
get values from html select in views with django
I would like to get the value and even the string if possible of the selected value in my HTML file. index.html <form action="#" method="post"> <select id="drop1"> <option disabled selected value> -- select value -- </option> {% for i in df %} <option value="{{ i }}">{{ i }}</option> {% endfor %} </select> </form> views.py def index(request): if request.method == 'POST': selected_value = request.POST.get('drop1') print(selected_value) else: return render(request, 'index.html', {'df': df.designation_list}) With this, nothing is returned. I saw that I have to use <form></form> to get an html value but I can't find what to put in the action= field. Can you see what is missing in my code? Thanks in advance -
How to prerender html/JS with django
I am currently using fancyTable.js https://github.com/myspace-nu/jquery.fancyTable to paginate results and allow a dynamic search. The pagnation and search works very well after the page loads, however, the initial page load is delayed (~2-3 seconds) due the large amount of data being paginated (with a smaller data set this delay is not noticeable) I tried to prerender the page using <link rel="prerender" href="{% url 'dashboard' %}"> in the header, but I'm assuming the prerender isn't working because the django url has not been called, meaning the data has not been passed to the web page. What is the best way to prerender this page? dashboard.html (companies is the issue, it contains 3000+ objects): <table id="mytableID" style="width:100%; " class="table table-striped sampleTable"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> {% for user in companies %} <tr class="tableHeaderData" style="display: none"> <td class=""> <input class="checkboxHeaderData" style=" " type="checkbox"> </td> <td class="headerNameMainData"> <div class="nameHeaderData"> <p class="textStyleData">{{ user.company }}</p> </div> </td> <td class="headerStageMainData"> <p class="textStyleData">{{ user.stage }}</p> </td> <td class="headerStatusMainData"> <p class="headerStatusData">In Progress</p> </td> <td class="headerSubmarketMainData"> <p class="headerSubmarketData">{{ user.submarket }}</p> </td> <td class="headerKeywordsMainData"> <p class="headerKeywordsData">Keyword</p> </td> </tr> {% endfor %} </table> The js script: <script type="text/javascript"> $(document).ready(function() { $(".sampleTable").fancyTable({ /* Column number for initial sorting*/ sortColumn:1, /* Setting pagination … -
Using Pillow in Django with pathlib instead of os
I'm doing a project in Django 4.0.6, which uses pathlib instead of os. I installed Pillow to include an image in the user's profile, but when I try to save the image I get the following error: TypeError at /admin/account/profile/2/change/ expected str, bytes or os.PathLike object, not tuple In settings.py this is the media setting: MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR, 'media' If I import os and set MEDIA_ROOT = os.path.join(BASE_DIR, 'media/'), then it works, but I would prefer using pathlib, and no mixing pathlib and os, this is just a personal preference, but I would like to understand why this error is happening. Below is the tracebak complete: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/account/profile/2/change/ Django Version: 4.0.6 Python Version: 3.10.4 Installed Applications: ['account.apps.AccountConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Traceback (most recent call last): File "/Users/ro/CS/rypptc/polmanv0.0.0.1/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/ro/CS/rypptc/polmanv0.0.0.1/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/ro/CS/rypptc/polmanv0.0.0.1/env/lib/python3.10/site-packages/django/contrib/admin/options.py", line 683, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/ro/CS/rypptc/polmanv0.0.0.1/env/lib/python3.10/site-packages/django/utils/decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/ro/CS/rypptc/polmanv0.0.0.1/env/lib/python3.10/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/ro/CS/rypptc/polmanv0.0.0.1/env/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 242, … -
type object 'Task' has no attribute '_meta'
Am starter in Django and tried CreateView class and got the following error: Am unable to find the issue. ListView and DetailView works fine. Trace Log : System check identified no issues (0 silenced). July 20, 2022 - 22:38:33 Django version 3.2.12, using settings 'configs.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /task/create/ Traceback (most recent call last): File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 168, in get return super().get(request, *args, **kwargs) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 133, in get return self.render_to_response(self.get_context_data()) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data kwargs['form'] = self.get_form() File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 32, in get_form form_class = self.get_form_class() File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 101, in get_form_class return model_forms.modelform_factory(model, fields=self.fields) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 563, in modelform_factory return type(form)(class_name, (form,), form_class_attrs) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 261, in new fields = fields_for_model( File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 150, in fields_for_model opts = model._meta AttributeError: type object 'Task' has no attribute '_meta model : class Task(models.Model): user =models.ForeignKey(User,on_delete=models.SET_NULL,null=True,blank=True,related_name='usertasks') title = models.CharField(max_length=200,blank=False, null=False) description = models.TextField(null=True, blank=True) complete … -
How to get the list item as url parameter in django
I'm trying to use a list item as a parameter in a URL tag in Django, but unable to use it. Everytime it gives django.urls.exceptions.NoReverseMatch: Reverse for 'film_details' with no arguments not found. 1 pattern(s) tried: ['refs/film_details/(?P<pk>[^/]+)/$'] Upon lots of searching, I found out that there is a problem with accessing the list item. My question is how do I use the list item as a parameter in the URL tag? View function def search_field(request): search_text = request.POST.get('search') refs = Ref.objects.filter(title__icontains=search_text).values('id','title') year = ImdbFilm.objects.filter(year__icontains=search_text).values('title') filmNames = ImdbFilm.objects.filter(title__icontains=search_text).values('year','crew__name') results = list(chain(refs,year,filmNames))[:10] context = {'results': results} return render(request,'refs/search-results.html', context) Url Tag {% for film in results %} <li> <a href="{% url 'refs:film_details' film.id %}"> </li> {% endfor %} urls.py file path("film_details/<str:pk>/", views.film_details, name="film_details") -
How is a template tested outside the request-response cycle?
How is a template and it's context tested for when testing it in isolation? To be specific, this template is being included into another with the {% include %} tag. I've used two different test assertions yet they raise these assertion errors: self.assertInHTML => AssertionError: False is not true : Couldn't find 'id=question_id_1' in response self.assertIn => AssertionError: 'id=question_id_1' not found in '\n<div id="question_id_1">\n\n</div>\n' class TestUserQuestionProfileTemplate(TestCase): @classmethod def setUpTestData(cls): tag1 = Tag.objects.create(name="Tag1") tag2 = Tag.objects.create(name="Tag2") user = get_user_model().objects.create_user("ItsNotYou") profile = Profile.objects.create(user=user) question = Question.objects.create( title="Test Question ZZZ", body="Post content detailing the problem about Test Question ZZZ", profile=profile ) question.tags.add(*[tag1, tag2]) cls.template = render_to_string( "authors/questions.html", {"question": question} ) def test_template_user_questions_listing(self): self.assertInHTML("id=question_id_1", self.template) self.assertIn("id=question_id_1", self.template) authors/questions.html <div id="question_id_{{ question.id }}"> </div> -
Acquiring a lock on a table to be reindexed?
first of all, I assure you, I have googled for hours now. My main problem is that I'm trying to fix a corrupted database of the tool paperless-ngx that I'm using. I am an IT admin but I have no experience with SQL whatsoever. I'm getting this error: ERROR: missing chunk number 0 for toast value 52399 in pg_toast_2619 Now every guide on the entire internet (I'm gonna post this one for reference) on how to fix this tells me to REINDEX the table. When I do this using reindex (verbose) table django_q_task; it keeps waiting indefinitely with this errormessage: WARNING: concurrent insert in progress within table "django_q_task" I am positive that there is no write happening from paperless side, all containers except for the database container have been stopped. I tried locking the table using lock table django_q_task in exclusive mode nowait; but the error persists. I'm at the end of my wits. I beg of you, can someone provide me with detailed instructions for someone with no postgresql experience at all? -
Django React Integration Error manifest.json not found 404
I integrated my react project successfully with Django. But every time I run the Django server, I get a manifest.json not found error. Also, when I ever I make any changes to the react app, it's not live to update when I run the Django server. I have to call npm run build every time to update the Django website. Is there a solution for this such that I do not get the manifest.json not found error and also the website server live updates as I update the front end react code. index.html <head> <meta charset="utf-8" /> <link rel="icon" href="/favicon.ico" /> <meta name="viewport" content="width=device-width,initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="/logo192.png" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" /> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <script src="https://unpkg.com/react/umd/react.production.min.js" crossorigin></script> <script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js" crossorigin></script> <script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js" crossorigin></script> <script>var Alert = ReactBootstrap.Alert</script> <title>React App</title> <link href="/static/css/2.e58a5209.chunk.css" rel="stylesheet"> <link href="/static/css/main.f38b3f41.chunk.css" rel="stylesheet"> </head> urls.py path('', TemplateView.as_view(template_name='index.html')), Directory Structure: enter image description here -
Unable to print JWT token in Django backend API
When I send a request from my React frontend to my backend api views, I can print the token, but it won't work for one specific view endpoint. There is nothing different in that code from the other view endpoints. This is the code I use to authenticate users, decode the JWT token, and print it to the terminal: def get(self, request): # print(request.headers) auth = get_authorization_header(request).split() print(auth) if auth and len(auth) == 2: token = auth[1].decode('utf-8') id = decode_access_token(token) I know it's not the frontend because it will print the token if I try to hit another endpoint from that same component. I'm completely stumped, and I don't know what to try. Any help is appreciated; thanks! -
installing python packegs problem on my machine
I have 3.10m python on my Machine but i was trying to run some commend through the command line and I keep getting the same error over and over even i have the python path in my environment paths SyntaxError: invalid syntax py -m pip install Django File "", line 1 py -m pip install Django ^^^ also pip install django file "", line 1 pip install django ^^^^^^^ syntaxerror: -
OperationalError at /profile/ no such table: users_profile even after I made migrations
I have the problem. When I'm trying to open a profile page to see the user's photo, but I can't, when I delete the line with user.register.photo, It works. I created a model, where there is a field that allows to users appload a photo, but when I'm trying to open "profile/" it shows this mistake. Seems like the problem is in migrations. I tried to delete migration folder, sqlite3 base and make migrations again, but it showed that "there are no changes" after I used makemigrations. It did not work for me, how can I fix this problem? users/models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' users/views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm from django.contrib.auth.decorators import login_required def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Создан аккаунт {username}!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): return render(request, 'users/profile.html') users/forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User … -
Django: show all related many-to-many items for a queryset
I have the following models: class NoteModel(models.Model): note = models.CharField( max_length = 5000, ) note_title = models.CharField( max_length = 500, blank = False, null = True, ) project = models.ForeignKey( IndividualProject, on_delete=models.CASCADE, related_name = "note_projects", blank = False, null = True, ) tags = models.ManyToManyField( NoteTagModel, related_name="tags", blank= False, ) def __str__(self): return f"{self.note_title}" class IndividualProject(models.Model): project = models.CharField( max_length = 64 ) def __str__(self): return f"Project {self.project}" I want to be able to find the tags for each project. So far I have the following: proj = IndividualProject.objects.get(id=2) notes = NoteModel.objects.filter(project = proj) notes is a QuerySet, how do I find all of the tags related to each item of the QuerySet? Ideally I would look to sort this in my views.py so that I could cleanly loop through in my template. Any help is greatly appreciated. -
Django ORM get all fields value. (foreign keys)
class MyUser(models.Model): name = models.CharField(max_length=10) class Foo(models.Model): my_user = models.ForeignKey(MyUser,on_delete=models.CASCADE) text = models.CharField(max_length=25) Let's say we have two models like this. I want to get all fields with an ORM query from the MyUser model. Like this: { "name":"example" "Foo":{ "text":"example-text", "text":"example_text2" } } How should I write a query to do this? MyUser.objects.all() # But give it ALL FIELDS + RELEATED FIELDS -
Best way to mock an RSS news feed endpoint in python?
I am currently implementing a feature which pulls the data from an RSS feed, parses it, does some modifications to it and saves it to our db. I have to specify that this all happens in a Django project. I pull the data from the RSS feed by using the feedparser library. I've also decided to write some tests, to make sure that the news feed is parsed well and that the whole process (from pulling and parsing the data to modifying it to saving it in our db) goes well. In those tests I've even managed to generate a dummy RSS feed using Django's feedgenerator util. However, I do not know how to effectively mock the RSS feed endpoint. I've tried using requests-mock but to no avail. I know for a fact that feedparser uses urllib. Should I mock something from urllib to make it work? Or should I start a server in another process that accepts connections and responds to everything with the mock RSS data? (something made with make_server from this example). The end goal for me would be to have something like this: request_mocker.get(RSS_NEWS_FEED_URL, data=dummy_rss_data, status_code=200) So when feedparser calls that RSS_NEWS_FEED_URL, it gets the dummy_rss_data. -
I am having trouble with logging users in and out of my blog
I am makeing a blog with Django and there is one admin account associated with the program. However, whenever I log in to the admin account and when I open a new window and go to my site, the new instance of my site is logged into my admin account. Does dose anyone know how I can fix this? -
django.db.utils.OperationalError: FATAL: role "user" does not exist
I am trying to authenticate users with django and postgresql. My project is dockerized. When I run docker-compose up --build I get an error saying: django.db.utils.OperationalError: FATAL: role "django2" does not exist I know error says role django2 doesn't exists but it does. If I run CREATE ROLE django2; I get an error saying ERROR: role "django2" already exists. My DATABASE section of settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'zane_db', 'USER': 'django2', 'PASSWORD': 'django2', 'HOST': 'db', 'PORT': 5432 } } My registration view: letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9",] characters = letters + numbers length = 5 token = "".join(random.sample(characters, length)) def signup(request): if request.method == "POST": context = {'has_error': False, 'data': request.POST} global password global password2 global email global username email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') password2 = request.POST.get('password2') body = render_to_string('authentication/email/email_body.html', { 'username': username, 'token': token, }) send_mail( "Email Confirmation", body, 'tadejtilinger@gmail.com', [email] ) return redirect('email-confirmation') return render(request, 'authentication/signup.html') def email_confirmation(request): if request.method == "POST": context = {'has_error': False, … -
Django model data query Exclude objects which are connected to another model by ForeignKey
I have two django models named Quiz and Result class Quiz(models.Model): name = models.CharField(max_length=250) another model class Result(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='results') Now i want to query data from this in two ways I want all the Quiz objects which do not have a Result I want all the Quiz objects which have a Result How can I do this? -
DoesNotExist error when using custom User model
I have a Group model in my group/models.py file: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) and an Account model, which is an extension of django's standard User, in users/models.py: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) joined_groups = models.ManyToManyField(Group, related_name='joined_group') created_groups = models.ManyToManyField(Group) in users/admin.py: class AccountInline(admin.StackedInline): model = Account can_delete = False verbose_name_plural = 'Accounts' class CustomUserAdmin(UserAdmin): inlines = (AccountInline,) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) The issue I'm having trouble understanding is when I create a new User, the Account for that User doesn't seem to really be registering. At the bottom of the new User's page (via django admin site) the new Account looks like this: Now, this new User seems to have an account which contains joined_groups and created_groups but when I try to join or create a Group with that new User, I get an error DoesNotExist - Account matching query does not exist I'm not sure why the new User/Account isn't really registering its Account. In comparison, inside my AdminUser page its Account info looks like this: Account: #1 for the new User vs. Account: Acount object (6) for Admin User. Finally, when I go onto the django … -
What makes my Django/Heroku app allow mobile version of a site?
I am new to web development. I just got my first project online, wich is Django app deployed in Heroku. App uses Bootstrap. When I use any size desktop browser window the app scales as I excpect it to. When I access it from my android phone it uses "mobile site" (if that's what it's called). The mobile site looks like a mess. If I use the "desktop site mode" on mobile it looks what I excpected it to look. I am trying to figure witch part of the stack is responsible for this happening. Is it possibly some of these? Django Bootstrap Heroku Browser I have not made any setting to use mobile site (at least not intentionally) so I am to assume this is the default for the tech responsible for this. Also in general; if I want my app to be usable both in desktop and mobile enviroments is it usually enough just to make site responsive and not bother with the "mobile site"? -
django static file not loading after updating it on production
i just deployed a django web app on azure i have a script which runs when i goes to myapp.com/update url it basically fetches data using bs4 library and convert the data into a pandas df then to show that data i used pd.to_html to convert it in html table format and stores that html file in static folder and then load it in my index.html (which present in templates folder using jquery) and mind you the html loads fine but after the i visit the update url it stops showing the updated html file (panada df one). i even goes to azure panel to see the updated html file (pandas df one) and it was there it got updated but cuz of the update, the site is not loading it anymore but before update it was loading perfectly --script in my views.py (for myapp.com/update url)-- text_file2 = open("staticfiles/album.html", "w") text_file2.write(updatedData) text_file2.close() this is how i'm adding that html file to my main index.html file (this loads the file perfectly but after update url it stops loading it) <script> $(function () { $("#includedAlbums").load("../static/album.html"); }); </script> Help me asap please. Thanks in advance <3 -
Django popup forms - CRUD
Could someone explain from the video below how the user call the "Edit" function? https://www.youtube.com/watch?v=P78-ltyeuVg&t=646s (19:18) Thank you!