Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django get all values in many instances?
I have a problem. products = Producto.objects.all() data = products[per_page * page: per_page * (page + 1)] And I want to get all the data from the instance, con ForeignKey and "normal" values. Example: product = <Queryset[[prod_id: 1, name: "Ferrari 1"]. [prod_id: 12, name: "Playstation 5"] [prod_id: 5, name: "Soap"]]> and in the end, what I need is something like this to be parsed to JSON and send it: [[prod_id: "Car", name: "Ferrari 1"]. [prod_id: "Console", name: "Playstation 5"] [prod_id: "Clean Acc", name: "Soap"]] -
Error while using django_countries module
I have a model as below class Person1(models.Model): name = models.CharField(max_length = 20,null = True) country = CountryField() def __str__(self): return self.name while I'm trying to add value to the model fields it is showing the error AttributeError: 'BlankChoiceIterator' object has no attribute '__len__' Is there any issue with new version of django Here the problem is with the country field -
CSRF verification failed. Request aborted . im trying to send data from AJAX to views.py but it's showing this error
registration.html <form method="POST" id="someForm"> {% csrf_token %} <label for="name">Name:</label> <input type="text" id="name" name="name" required /> <label for="email">Email:</label> <input type="email" id="email" name="email" required /> <label for="password">Password:</label> <input type="password" id="password" name="password" required /> <input type="submit" value="Register" name="createuser" /> </form> </div> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> let URLd = "{% url 'defaultpg' %}"; let nameInput = document.getElementById("name"); let emailInput = document.getElementById("email"); let passwordInput = document.getElementById("password"); const someForm = document.getElementById("someForm"); someForm.addEventListener("submit", (e) => { e.preventDefault(); // prevent default behavior of the form var csrfToken = $("input[name='csrfmiddlewaretoken']").val(); let nameValue = nameInput.value; let emailValue = emailInput.value; let passwordValue = passwordInput.value; let isNameValid = /^[a-zA-Z]+$/.test(nameValue); let isEmailValid = /^\S+@\S+\.\S+$/.test(emailValue); let isPasswordValid = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test( passwordValue ); if (isNameValid && isEmailValid && isPasswordValid) { alert("Successful"); $.ajax({ type: "POST", url: /defaultpg/, headers: { "X-CSRFToken": csrfToken }, data: { name: nameValue, email: emailValue, password: passwordValue, csrfmiddlewaretoken: csrfToken, }, dataType: "json", success: function (data) { // Handle success response alert("Successful msg"); }, error: function () { // Handle error response alert("Failure"); }, }); } else { // Handle validation errors if (!isNameValid) { alert("Please enter a valid Name"); } else if (!isEmailValid) { alert("Please enter a valid Email Address"); } else { alert( "Password must contain letters, capital letter, small letter, special character, … -
Add users to group based on OAuth2 Role - Microsoft Azure AD - social-auth-app-django
I'm trying to use Django-Social-Auth to login to Django. I have the OAuth workflow working and I can login, but I am not part of any groups and have no permissions.. My Azure AD app has various roles configured that are mapped to AD groups.. How can I map the users role to a Django group and in turn give permissions? If I need to create a custom pipeline function, thats fine, but I cant find any reference to access the roles. Thanks. -
Is there a production ready code template to deploy a django app to aws?
I'm looking for a production-ready approach to deploy django apps to aws. The approach must be in a automated fashion and needs minimal changes when deploying for a new app. For example, let's say I have a todo list app. Now I want to deploy it to aws. I will need terraform to create the required infrastructures, and then some way to configure these infrastructure and deploy the django app there. What I want is next time when I have another app - say a blog app, I just need to change a couple of things and use the same approach I used last time to have it deployed. I have checked out a few tutorial online but none of them quite captured what I'm looking for. Using terraform for infrastructure provisioning is the norm, however for deploying django on AWS I see there are a couple of approaches. I'm not an expert in AWS so I just want something with minimal overhead and maximum reproducibility Please help me find such a template. This would help me tremendously in deploying django apps. -
Docker image not working after rebuild with same dependencies
Docker image not working after rebuild with same dependencies. probably related to xmlsec. Same versions for python, nginx, gunicorn, python3saml, xmlsec etc. rebuild and checked that all dependencies are the same. they are the same. Container is running in azure, but problem is reproduced locally. -
Site Can't be reached while creating server on Flask
The VSC terminal says that the server is running on 127.0.0.1:5000 But when I Go there.. It says site couldn't be reached.. Please solve this problem.. Same problem persists while creating a server from Django I asked chatgpt but couldn't find any good solutions . -
Django multiple annotation for one Case-When
I'm currently trying to annotate multiple value with the same When in a Case for a Django QuerySet. Currently I have something like this: my_qs.annotate( dynamic_status_deadfish=Case( when_inactive, when_only_recently_published, when_no_published_ad, when_not_enough_booking, when_low_booking_cnt, default=default, output_field=HStoreField(), ) ) with one of those when looking like this: when_inactive = When( is_active=False, then={"status": stats_cts.INACTIVE, "reason": None}, ) when_only_recently_published = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=True), then={ "status": stats_cts.PENDING, "reason": OwnerStatsStatusReason.RECENTLY_SUSPENDED, }, ) when_no_published_ad = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=False), then={ "status": stats_cts.PENDING, "reason": OwnerStatsStatusReason.NO_BOOKABLE_TO_MODERATE, }, ) As you can see my output is a dict, or more exactly an Hstore. Ideally, I'd like one distinct annotation for status and for reason so that I don't have to deal with serialization and have an easier access to the annotation than with this HSTore One way would be to duplicate the when for status and reason as the condition are the same, but I don't like it. Something like this: when_only_recently_published = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=True), then=Value(stats_cts.PENDING), ) when_only_recently_published_reason = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=True), then=Value(OwnerStatsStatusReason.RECENTLY_SUSPENDED), ) ... my_qs.annotate( dynamic_status_deadfish=Case( when_inactive, when_only_recently_published, when_no_published_ad, when_not_enough_booking, when_low_booking_cnt, default=default, ), dynamic_status_deadfish_reason=Case( when_inactive_reason, when_only_recently_published_reason, when_no_published_ad_reason, when_not_enough_booking_reason, when_low_booking_cnt_reason, default=default_reason, ) ) Any way to somehow set two annotations in a Case or something similar ? -
django search a value in multiple fields
There is a way to search a determinated value inside of N fields? (Without have to get all the db to filter it with for in) Something like this: db = id name age 1 Juan 10 2 Pedro 31 3 Laura 55 4 3_Manuel 11 search(3) => OUTPUT [[2 Pedro 31] , [4 3_Manuel 11]] search("au") => OUTPUT [[1 Juan 10]] -
How to manage azure blob storage with django in production?
I have a django app and I am using the library django-storages[azure]. When I run the django app local I can upload images via django admin to my storage container on azure. But I also have an web app with url: https://example.azurewebsites.net and I try to upload images from the mentioned url. But that doesn't work - the images are not uloaded to the storage container. So this are my azure settings in the settings.py file: DEFAULT_FILE_STORAGE = 'dierenwelzijn.custom_azure.AzureMediaStorage' STATICFILES_STORAGE = 'DierenWelzijn.custom_azure.AzureStaticStorage' STATIC_LOCATION = "static" MEDIA_LOCATION = "media" AZURE_ACCOUNT_NAME = "dier" AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' Question: what I have to change so that I can upload images from the hostmachine with url: https://example.azurewebsites.net ? -
How to store the data of two different django models which share one to many relationship via a single HTML form?
I have a single HTML form to fill up the details of both patient and his/her doctor. I have created a One to many relationship between Doctor and Patient models using ForeignKey. The form(docpatient.html) goes like this: <form action="{% url 'requestlanding' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <h2> Patient Details </h2> <label for="patientName"> Patient's Name: </label> <input type="text" id="patientName" name="patientName" required> <label for="age"> Age: </label> <input type="number" id="age" name="age" required> <label for="gender"> Gender: </label> <select id="gender" name="gender" required> <option value="male"> Male </option> <option value="female"> Female </option> <option value="other"> Other </option> </select> <label for="contactNumber"> Contact Number: </label> <input type="tel" id="contactNumber" name="contactPatient" required> <label for="email"> Email: </label> <input type="email" id="email" name="emailPatient" required> <label for="media"> Upload patient's picture: </label> <input type="file" id="media" name="wrecommend" accept="image/*,video/*,pdf/*"> <h2> Doctor Details </h2> <label for="doctorName"> Doctor's Name: </label> <input type="text" id="doctorName" name="doctorName" required> <label for="specialization"> Specialization: </label> <input type="text" name="specialization" id="specialization" required> <label for="contactNumber"> Contact Number: </label> <input type="tel" id="contactNumber" name="contactDoctor" required> <p> (All the information must be correct and proper) </p> <button type="submit"> Submit </button> </form> I have created Patient and Doctor models as following: from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Doctor(models.Model): name = models.CharField(max_length=50, blank=False) phone = models.IntegerField( validators=[MinValueValidator(1000000000), MaxValueValidator(9999999999)], blank=False, ) … -
Are multiple Django indices necessary?
I've a Django model that, among other fields, has time, station and variable. Nearly always, queries will be done providing the three fields - occasionally and very rarely, I might want to query using only one of them. In this case, does it matter if the index is set to models.Index(fields=["station", "time", "variable"]) or models.Index(fields=["time", "station", "variable"]) or other permutation of the three? Would it be useful to add all possible permutation or is it irrelevant? If there any performance penalty or benefit in adding all permutations? Many thanks! -
How to show the results of a many-to-many relationship backward direction via Django admin?
I have two models defined, groups and group_members, with the latter defining a many-to-many relationship to the former: class Group(models.Model): group_name = models.CharField(max_length=100, default="New Group") group_created_date = models.DateField(default=date.today) class GroupMember(models.Model): groups_joined = models.ManyToManyField(Group) email = models.EmailField(max_length=100) name = models.CharField(max_length=100) And then for my admin.py I simply have: admin.site.register(Group) admin.site.register(GroupMember) This works rather well from one side, when viewing GroupMember objects I can see and edit all the groups they belong to. However when viewing Group objects, I can not see the relationship from that side - I cannot see any members who belong to that group. What would I need to add to my admin.py to make this happen? I've been searching on how to do this but the answers either seem to convoluted and/or out of date. -
how to fix the following error? Error connecting Django to MSSQL
File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\db\backends\base\base.py", line 292, in _cursor self.ensure_connection() File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\db\backends\base\base.py", line 274, in ensure_connection with self.wrap_database_errors: File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\db\utils.py", line 91, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\ProgramData\Anaconda3\envs\Lib\site-packages\django\db\backends\base\base.py", line 275, in ensure_connection self.connect() File "C:\ProgramData\Anaconda3\envstest\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\db\backends\base\base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\mssql\base.py", line 366, in get_new_connection conn = Database.connect(connstr, **args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'user'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'user'. (18456); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)") DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': 'Test', 'USER': 'user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } mssql and pyodbc were installed -
Weird bug when looking at a user profile in django
So I have 2 user types: a company and a job seeker. The problem is when I go to the seeker's profile from a job application, or directly go to a seekers profile, it returns the data of the current logged in company. Like this: Here's the view for the JobApplication: class JobApplicationsView(CompanyRequiredMixin, LoginRequiredMixin, DetailView): model = Job template_name = "applications/job_applications.html" context_object_name = "job" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) job = self.get_object() # Get all job applications for the current job job_applications = JobApplication.objects.filter(job=job) context["job_applications"] = job_applications return context Here's the template job_applications.html {% extends "base.html" %} {% block content %} <div class="container mt-5"> <h1 class="mb-4">{{ job.title }} - Job Applications</h1> {% if job_applications %} <ul class="list-group"> {% for application in job_applications %} <li class="list-group-item"> <strong>Applicant:</strong> {{ application.applicant.username }}<br> <strong>Cover Letter:</strong> {{ application.cover_letter }}<br> {% if application.resume %} <a href="{{ application.resume.url }}" download class="btn btn-primary">Download Resume</a> {% else %} <span class="text-muted">No resume attached</span> {% endif %} </li> {% endfor %} </ul> {% else %} <p>No applications for this job yet.</p> {% endif %} </div> {% endblock %} To get it right, the localhost:8000/job-seeker/seeker1 should show the data of the job seeker. This happens to all profiles, when I use … -
Apple Store Server Notification: Python OpenSSL certificate loading fails in "header too long"
On my django server, I'm trying to decode the JWT content sent by the Apple Store Server Notification using Apple's package app-store-server-library-python. Under the official documentation, when starting to do the verification and decoding, we find this line: root_certificates = load_root_certificates() The implementation is not provided unfortunately. By looking here and there, I've tried several implementations that always fail in : OpenSSL.crypto.Error: [('asn1 encoding routines', '', 'header too long')] Here is my implementation: def load_root_certificates(): in_file = open("AppleRootCA-G3.cer", "rb") data = in_file.read() in_file.close() return load_certificate(FILETYPE_ASN1, data) Thanks for the help! -
Why do we return only a limited amount of information from a websocket event?
I'm working on implementing a real-time chat application that uses web sockets and a 3rd party application. This 3rd party application has various events that does not transmit the full message object, but rather a limited set of data. Wouldn't it be better to return the full message object, because it would greatly simplify the process of updating the client? What's happening right now is that I have to engage in complex search and update operations. I guess I am having trouble understanding this design choice because, at least in my eyes, returning the full message object shouldn't take up that much additional bandwidth. Here are some examples. API Responses Dialog (Represents chat between two people) [ { "id": 2, "created": 1704771541, "modified": 1704771541, "other_user_id": "1", "unread_count": 12, "username": "admin", "last_message": { "id": 36, "text": "f", "sent": 1704847056, "edited": 1704847056, "read": false, "sender": "1", "recipient": "2", "out": false, "sender_username": "admin" } } ] Message { "id": 36, "text": "f", "sent": 1704847056, "edited": 1704847056, "read": false, "sender": "1", "recipient": "2", "out": true, "sender_username": "admin" } Web Socket Events New Message {"msg_type": 3, "random_id": -999999, "text": "Hi …", "receiver": "2", "sender_username": "johntaylor"} Message Added {"msg_type": 8, "random_id": -999999, "db_id": 46} Unread count … -
Update OneToOneField Relationship in Django
I want to update to exera field of User models in Django programmatically in my program. how can i update the extra field of User model in Django? def user_profile(request): query_set = str(Group.objects.filter(user=request.user)[0]) if query_set == 'user': user = request.user name = user.first_name family = user.last_name extrainfo = ExtraInfo.objects.get(User=user) extrainfo.title = 'business' extrainfo.save() return render(request, 'user-profile.html', {'name': name, 'family': family, 'title': user.extrainfo.title}) else: messages.warning(request, 'Unauthorized Access!') return render(request, 'warnings.html') from django.db import models from django.contrib.auth.models import User class ExtraInfo(models.Model): User = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) title = models.CharField(max_length=25, blank=True) -
Integrate sslcommerz payment gateway in my Django project
I have alreadt integrated Paypal payment gateway in my django project fllowing this tutorial. Now, I want to integrate sslcommerz for users to give more option to pay. Here are some codes of my project. config/settings.py """ Django settings for config project. Generated by 'django-admin startproject' using Django 5.0. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-f=f@1a*+svrxj#j8_4ik%c@gd16_s6@c$(n%4p$(66*6g7we6)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'product', 'user_account', 'cart', 'order', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'product.context_processors.categories', 'cart.context_processors.cart' ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
Wrong credentials cause sign in alert box
I have react frontend and django backend. I am seeing an alert box when I enter incorrect credentials on my login screen. On Google Chrome I see the network call in pending state When I click on 'Cancel' button on the dialog, I see 401 error (as expected since invalid credentials were entered). Am I missing anything? Why am I seeing this dialog? -
Creating a PDF with PDFkit and Wkhtmltopdf, but encountering an issue where the entire table is being pushed to the next page. How can I resolve this
I'm facing an issue while generating PDFs in Python Django using PdKit and Wkhtmltopdf. Specifically, when the table has more than 10 items, it gets pushed to the next page. I've attempted the following solutions: Added the following CSS styles: page-break-inside: avoid !important; } table { page-break-inside:auto } tr { page-break-inside:avoid !important; page-break-after:auto !important } thead { display:table-header-group !important} tfoot { display:table-footer-group !important} ``` 2. Tried using the JavaScript solution provided - https://github.com/AAverin/JSUtils/blob/master/wkhtmltopdfTableSplitHack/wkhtmltopdf_tableSplitHack.js [![Image 1 ][1]][1] [![Image 2][2]][2] [1]: https://i.stack.imgur.com/TO2Hb.png [2]: https://i.stack.imgur.com/Dt3Wl.png -
Content-Security-Policy: The page’s settings blocked the loading of a resource at inline (“script-src”)
This is the code I copied from some blogs for google authentication OAUTH 2.0. The code was based on django backend and react.js frontend. In my project I am using django as backend but next.js 14 using typescript as frontend. When openGoogleLoginPage function is called after clicking a button google login page gets opened but in console Content-Security-Policy: The page’s settings blocked the loading of a resource at inline (“script-src”) error is shown. And After clicking on any account it sends get request to server but in django server "GET /api/v1/auth/login/google/?code=4%2F0AfJohXm69xHTNpnP3QX8CbhwTO18s4XZIFERfUDq_pfhaOgCYPm6jpf3XRyxTg_ziIB8Lw&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&authuser=2&prompt=consent HTTP/1.1" 500 103892 is shown const Home = () => { const [username, setUsername] = useState(localStorage.getItem('goggleFirstName')) useEffect(() => { const storedUsername = localStorage.getItem("user_goggle"); if (storedUsername) { setUsername(storedUsername); } }, []); const openGoogleLoginPage = useCallback(() => { const googleAuthUrl = "https://accounts.google.com/o/oauth2/v2/auth"; const scope = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", ].join(" "); const params = new URLSearchParams({ response_type: "code", client_id: REACT_APP_GOOGLE_CLIENT_ID, redirect_uri: `${REACT_APP_GOGGLE_REDIRECT_URL_ENDPOINT}/google`, prompt: "select_account", access_type: "offline", scope, }); const url = `${googleAuthUrl}?${params}`; window.location.href = url; }, []); const handleLogout = () => { localStorage.clear(); // Clear localStorage when the button is clicked setUsername("") }; The tutorial which I was following is this. I have been stuck with this problem for a couple … -
ORA-02019 Error When Executing Queries on Remote Oracle DB in Django Application
I'm currently working on a Django application that interacts with an Oracle database. My application needs to execute SQL queries on a remote Oracle database, which is configured in the settings.py file. The SQL queries I'm trying to execute have a syntax similar to: SELECT * FROM table@source Here, source is a different database than the one currently executing the query. Both the source and target databases are Oracle databases. Despite the remote database being configured in settings.py, I encounter the following error when executing the first query: ORA-02019: connection description for remote database not found I'm looking for guidance on how to resolve this error. Here's some additional information that might be helpful: I've confirmed that the remote database is accessible outside of the Django environment. The user credentials used in settings.py have the necessary privileges. The application works fine with local database queries. Has anyone encountered a similar issue or can provide insights into what might be going wrong? Any advice on configuring Django to work seamlessly with remote Oracle databases using database links would be greatly appreciated. Thank you in advance for your help! -
In Django how to compare two texts and print a message about correctness?
I'm new to Django. In Django i would like to compare two texts and receive a message if they are the same or different. In reality these two texts are two short HTML codes. The page can reload easily, I'm only interested in the logic behind comparing the two texts (and not the use of Ajax, jQuery, JS). A text will be inserted in the front-end by the user, who will write in a div (no textarea) with contenteditable="true" which is already present in my code. I have already prepared an example text in the black panel, so I would like to compare the entire block of text (from up to ). While the other text will be contained in the backend (in a variable or something similar). Then I will click on the button and in the gray rectangle i would like to print CORRECT: the two texts are the same or ERROR: the two texts are different. Important is that i don't want to use textarea, but as already said I want to use the div with contenteditable="true" that I already have in my code. HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta … -
DoesNotExist at /.../pk/
So I created a simple CRUD simple, like a tweet, where you have Username, Title and Message/Description It was working well and I was following a tutorial, then it happened I don't know what going on because my models seems to be ok class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) #participants = updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] It also doesn't seem to be an error in my views def room(requests,pk): room = Room.objects.get(id=pk) message = Message.objects.get(id=pk) context = {'room':room, 'message':message} return render(requests,'base/buy.html',context) def createRoom(request): form = RoomForm() if request.method == 'POST': form = RoomForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form':form} return render(request, 'base/room_form.html', context) But then I noticed this error in my shell Traceback (most recent call last): File "c:\Users\adrya\thegreatsite\base\views.py", line 2, in <module> from .models import Room, Message ImportError: attempted relative import with no known parent package these are the models I imported from django.shortcuts import render, …