Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I made a form and doesn't save to my database in django
Hey I just started learning django , and i had a problem in registration form , it doesn't save to my database , i've tried a lot of things and none if works for me i don't know where the problem is , and when i try to add it from python shell it worked but not from html i would love to if someone figure it out : models.py: class Register(models.Model): Username = models.CharField(max_length=255) email = models.EmailField(max_length=255) password = models.CharField(max_length=255) con_password = models.CharField(max_length=255) def __str__(self): return ( f"{self.Username}" f"{self.email}" ) views.py : def register(request): if request.method == "POST": form = Register(request.POST) if form.is_valid(): form.save(commit=False) form.save() return redirect('/') #redirect after saving form = Register() return render(request, "register.html", {'form': form}) register.html : {% block content %} <section id="hero" class="login"> <div class="container"> <div class="row justify-content-center"> <div class="col-xl-4 col-lg-5 col-md-6 col-sm-8"> <div id="login"> <div class="text-center"><img src="{% static 'touriste/img/logo_sticky.png' %}" alt="Image" data-retina="true"></div> <form method="post"> {% csrf_token %} {{ form.as_p }} <div class="form-group"> <label for="Username">Username</label> <input type="text" name="Username" class=" form-control" required placeholder="Username"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" name="email" class=" form-control" required placeholder="Email"> </div> <div class="form-group"> <label>Password</label> <input type="password" name="password" class=" form-control" required id="password" placeholder="Password"> </div> <div class="form-group"> <label>Confirm password</label> <input type="password" name="con_password" class=" … -
Django + Apache2 behind NGINX reverse proxy - redirections going wrong
I have a Django project running on Apache2 with mod_wsgi in a VM - https://systems3.slt.local/ Accessing the VM directly, via https://systems3.slt.local/ works perfectly. However, I need it to work behind an NGINX reverse proxy, and I'm having problems with login redirection. My proxy is configured like this: location /systems3 { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; proxy_pass https://systems3.slt.local/; } When I try to access the project through the proxy, https://example.org/systems3 , Django checks that there is no user logged in, and then redirects to https://example.org/**accounts/login**. The correct would be to redirect to https://example.org/**systems3/accounts/login**. Even if I try to directly access this address, I am redirected to https://example.org/accounts/login. It seems that some configuration is missing so that the address https://example.org/systems3 is the root of the project, it shouldn't be redirecting me outside of systems3. It's also giving problem with my static folder, it also looks for the folder at https://example.org/static, ignoring that it was supposed to look inside systems3. -
Convert a basic sql query to django query
I want to display the course name along with the question count in a table. Need help to convert below query to a django query: SELECT DISTINCT exam_course.course_name, COUNT(exam_question.question) FROM exam_course INNER JOIN exam_question ON exam_question.course_id = exam_course.id GROUP BY exam_question.course_id -
How to Properly Display RenderedMarkdownField() on Template when "safe" Isn't "Working"?
On my django website, I'm using a RenderedMarkdownField() to make some fancy looking description text on my posts. My model looks like this: # Portfolio project overview model class Work(models.Model): title = models.CharField(max_length=100) # description = models.TextField() description = MarkdownField(rendered_field='description_rendered', validator=VALIDATOR_STANDARD) description_rendered = RenderedMarkdownField() image = models.ImageField(upload_to="work_app/media/images/", null=True, blank=True) video = models.FileField(upload_to="work_app/media/videos/", null=True, blank=True) pdf = models.FileField(upload_to="work_app/media/documents/", null=True, blank=True) # To show the title in the Admin page def __str__(self): return self.title Then my work_index.html page looks like this when rendering each project from my database (personally identifying/crucial info scratched out): As you can see, the Markdown characters in the description text (the *'s) are visible in this description. To fix this, we use Django's safe tag and render the work.description_rendered field instead, so my code when iterating through each post looks like this: <div class="row"> {% for work in works %} <div class="col-md-4"> <div class="card mb-2"> <a href="{% url 'work_detail' work.pk %}"> <img class="card-img-top" src="{{ work.image.url }}"> </a> <div class="card-body"> <a href="{% url 'work_detail' work.pk %}"> <h5 class="card-title project-title-link">{{ work.title }}</h5> </a> <p class="card-text">{{ work.description_rendered | safe | truncatechars:200 }}</p> <a href="{% url 'work_detail' work.pk %}" class="btn btn-primary"> Read More </a> </div> </div> </div> {% endfor %} </div> ...HOWEVER, … -
Django: Accessing reusable app in settings.py
I have a reusable django app installed in my project, and the desired outcome is to import it into the main project's settings.py. The project runs well with the reusable app installed and added into INSTALLED APPS in settings.py. However, when I try to import it in settings.py, django throws an error. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I think it has something to do with Django not loading the reusable app in time before the imports, but I'm not sure how to solve this. Any suggestions are much appreciated! -
part a custom user model into two apps, but custom user model app override the 2nd app
I have searched a lot to any related to my problem but never found what i need I am trying to create a simple Django blog that has a custom user model inherit the core authentication AbstractUser class in app named user user.models.py class User(AbstractUser): email = models.EmailField('email_address', unique=True) USERNAME_FIELD = 'email' and another account app that has been parted the login and profiles of authenticated users account.models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile_user', on_delete=models.CASCADE) the settings.AUTH_USER_MODEL above is the same User that already been imported from user app user.models import User and already been identified in settings.py When i started to makemigrations and migrate i found no problems, but when i went to my PostgreSQL pgAdmin to see database tables i fount all tables except the account_profile table although there are another class in account i found it's table but no Profile as it never been created Also when i tried to create superuser, i got the same notation that : psycopg2.errors.UndefinedTable: relation "account_profile" does not exist LINE 1: INSERT INTO "account_profile" ("user_id", "city_id", "phone... should i have to put the Profile class in account.models.py in user.models.py together or what exactly should i do, please help and sorry for … -
Django - ModelForm - Filter by user
I need to filter in EmployeeForm just to show me options of Companies related to user is logged in. I'm using ModelForm and CreateViews This is my code: models.py class Company(models.Model): reg_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=255) cuit = models.CharField(max_length=20) class Employee(models.Model): company = models.ForeignKey(Empresa, on_delete=models.CASCADE) name = models.CharField(max_length=255) cuil = models.CharField(max_length=20) forms.py class EmployeeForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ... self.fields['name'].widget.attrs['autofocus'] = True What is the code I need to write in the ellipses? It's currently showing me all companies even ones not owned by the user. Thanks in advance. -
How do I copy to the clipboard in JavaScript? tell me
i used this code const copyBtns = [...document.getElementsByClassName('copy')] copyBtns.forEach(btn=> btn.addEventListener('click', ()=>{ content = btn.getAttribute('data-content') navigator.clipboard.writeText(content) btn.textContent = "تم النسخ" })) copy not working on click in mobile, and it's working with any computer. what is the solution? -
HTML template for displaying forms only if form.DELETE doesn’t exist
I want to achieve something like this, actually "DELETE" shouldn’t exist in form itself, or if it does it should be switched off or not checked. {% if not form.DELETE %} <div class="input-form"> <div class="col-md-12 mb-4 mt-4"> {{ form }} </div> </div -
get all many to many field values + the rest of the model fields in a general query to db
I am studing django and I want to do an API endpoint that brings all the employees in the database with all the fields, including the languages field which has a manyToMany relationship to Languages Model. class Employee(models.Model): name = models.CharField(max_length=50) lastname = models.CharField(max_length=50) salary = models.PositiveBigIntegerField() position = models.ForeignKey(Position, on_delete=models.CASCADE, related_name='employees') languages = models.ManyToManyField(Languages, related_name='employees') def __str__(self): return f'{self.name} {self.lastname}' class Languages(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name I managed to do this but with a query that gets only one employee try: emp = Employee.objects.get(id=id) data = { 'name': emp.name, 'lastname': emp.lastname, 'salary': emp.salary, 'position': emp.position.name, 'languages': [x['name'] for x in emp.languages.all().values()] } except ObjectDoesNotExist: return JsonResponse({"message": "No company found"}) except Exception as ex: return JsonResponse({"message": "Something went wrong."}) return JsonResponse({"message": "success", "data": data}) But now I can't do the same with a query such as Employee.objects.all() or Employee.objects.values(). This is what I would need but with all the employees at once: { "message": "success", "data": { "name": "Fred", "lastname": "Wilson", "salary": 28000, "position": "CTO", "languages": [ "JavaScript", "PHP" ] } } I've tried a lot of things including prefetch but I couldn't get it to work. -
How to pass variable from view.py to javascript without using render() in django
return render(request, 'index.html', {"flag": flag, "form": form}) I want to pass flag value which should be read by javascript to change style of an element in template, but since rendering it again the flag value is lost and set back to "none" ,is there any way to not use render and pass the variable to a url where the page is already rendered -
Django app return error when connecting to Postgres Database django.db.utils.OperationalError
I have a Django web app that connects to a postgres database in Azure, some days ago this was working fine, but now i receive the following error when I run the server: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 244, in ensure_connection self.connect() File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\postgresql\base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "exampleyv.postgres.database.azure.com" (52.182.136.38), port 5432 failed: FATAL: no pg_hba.conf entry for host "186.31.127.234", user "exampleyv", database "exampleyv", SSL on The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run self.check_migrations() File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 576, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File … -
Django-native/ORM based approach to self join
Trying to set up a Django-native query that grabs all rows/relationships when it shows up on the other side of many-to-many relationship. I can explain with an example: # Django models class Ingredient: id = ... name = ... ... class Dish: id = ... name = ... ... class IngredientToDish # this is a many to many relationship ingredient_id = models.ForeignKey("Ingredient", ...) dish_id = models.ForeignKey("Dish", ...) ... I'd like a Django-native way of: "For each dish that uses tomato, find all the ingredients that it uses". Looking for a list of rows that looks like: (cheese_id, pizza_id) (sausage_id, pizza_id) (tomato_id, pizza_id) (cucumber_id, salad_id) (tomato_id, salad_id) I'd like to keep it in one DB query, for optimization. In SQL this would be a simple JOIN with itself (IngredientToDish table), but couldn't find what the conventional approach with Django would be... Likely uses some form of select_related but haven't been able to make it work; I think part of the reason is that I haven't been able to succinctly express the problem in words to come across the right documentation during research. Any help would be appreciated... thank you!! -
django image upload in different template
How can I display uploaded images in a different template from the form> in Django. I don't get it how to render it to another page. I the upload template has the form to upload image. And I want to display those images in profile but I am not able to do so . It is only working ienter image descript -
How to pass a Django Object to Javascript File (template buyed in envato elements)
dears!! I'm trying to get a Django object in a Javascript file. My objective is to to connect a Django template to a Javascript file and render my model info in the website. My models.py: class Event(models.Model): _id = models.ObjectIdField(blank=True, null=False) title = models.CharField(max_length=200) slug = models.SlugField(max_length=100) description = models.TextField(blank=True, null=True) event_date = models.DateTimeField(null=True, verbose_name="Date") event_creation = models.DateTimeField(verbose_name="Creation", auto_now_add=True) start = models.DateTimeField(null=True, verbose_name="Start") end = models.DateTimeField(null=True, verbose_name="End") event_updated = models.DateTimeField(verbose_name = 'Updated',auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'event_{self.title}' class Meta: db_table = 'event' My serializers.py: class EventSerializer(serializers.ModelSerializer): # _id = serializers.ReadOnlyField() channels = Event class Meta: model = Event fields = '__all__' My views.py: class Calendar(LoginRequiredMixin,TemplateView): template_name = "calendar.html" queryset = Event.objects.all() serializer = EventSerializer(queryset, many=True) data = JSONRenderer().render(serializer.data) def get(self, request): context = {'event': self.data} return render(request, 'calendar.html', context) #FOR THE FUTURE: I WANT TO USE POST METHOD # def post(self, request, *args, **kwargs): # serializer = self.get_serializer(data=request.data) # serializer.is_valid(raise_exception=True) # event = serializer.save() # return Response({ # "event": EventSerializer(event, context=self.get_serializer_context()).data, # "token": AuthToken.objects.create(event)[1] # }) the Javascript file (I've detected that the object that render events on calendar are the one in commented lines. What I want is to pass my Django Object into that list, … -
How Can I get a Particular User Group Name in Django Form Query
I have a Django form with a Drop Down from User Groups which is Created from Django Admin Panel. I have 3 groups with various permissions so in this form I want to get only the Group named 'Guest' from the drop down and disabled. What is the best way of doing it. Below is what I have tried but I am getting the following errors: ImportError: cannot import name 'getgroups' from 'os' class GuestUserForm(UserCreationForm): email = forms.EmailField group = forms.ModelChoiceField(queryset=Group.objects.get('Guest'), required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'group'] -
Django can not import site module
I am trying to run a simple Hello World app with Django but for some reason, it does not import myapp from mysite. -
Serve static files from Cloudflare's R2
Architecture Description I have a Django app hosted on an Azure App Service container and proxy through Cloudflare's DNS. The app works great, and using WhiteNoise I am able to serve static files stored in the Azure App Service storage container that is provided with the App Service (10 GB). Thing is, the storage serves files used by the Web App only (files uploaded during build, there's no option to manually add other files), and it is limited to 100GB/month of egress bandwidth. I would like to try and use [Cloudflare's R2] storage, as it has unlimited bandwidth, and allows you to upload any kind of files. I'll mainly be using images. Question How can static files be serve from Cloudflare's R2 on a Django app? -
Reverse Lookup for Inherited Models in Django
I have several Django model definitions. There is a parent class contains a foreign key to another class, and there are multiple model classes that inherit from the parent. class Foo(models.Model): pass class Parent(models.Model): foreign_key = models.ForeignKey(Foo, on_delete=models.CASCADE) class Child1(Parent): pass class Child2(Parent): pass Given an object of type Foo, I am trying to perform a reverse lookup to find all objects that are either of type Parent or subclass Parent and that link to that specific object. However, if I use foo.parent_set I would only get the objects of the Parent class that are related to foo, while if I try doing so with any of the child classes it errors out because those don't directly specify a relationship with the class Foo. Is there any way to get a list of all objects that are of type Parent or inherit from Parent that contain a foreign key to an object of type Foo? -
Django query with conflicting fields returns duplicate answers
Query: cameraSystems = DWCloudSystem.objects.filter(isShared=False).filter(company_key=comp) cameraSystems = cameraSystems | DWCloudSystem.objects.filter(isShared=True).filter(location__owners=comp) DWCloudSystem is a model with that contains: "company_key" a foreign key representing a Company model object, "location" a foreign key representing a place object, "isShared" a Boolean field A place object also contains a "owners" ManyToMany field for company objects. Essentially the goal is to have a DWCloudSystem which is owned by a company which is at a place to be returned if isSharing is false or ifSharing is true then any company that belongs to the place object will be able to access that DWCloudSystem along with its "owner" company which is represented by the company_key field (which may or may not be a member of the "owners" field that is apart of the place model) The issue is this query is returning the same company twice even though isShared is set to True and thus the other query should be empty. Both work correctly if not combined. -
Django REST Framework, implicatoins of [] in search
I have a very basic Django API which makes a query in elasticsearch. The output shows the query_parameters and the search.query. Why I cannot pass the country variable in this case 'DE' to the search.query as shown in the output? Could you please explain the implications of [] in country[]? class ESNumView(APIView): """Obtain number of articles after a search in titles and abstract in ES""" def get(self, request, *args, **kwargs): query = self.request.query_params.get('query') country = self.request.query_params.get('country') print(self.request.query_params) search = Search(index=constants.ES_INDEX) q = Q('bool', must=[ Q('multi_match', query=query, fields=['title', 'abstract']), Q('terms', country=country) ] ) s = search.query(q) pprint(s.to_dict()) num_count = s.count() return Response(data=[{'search_count': num_count}]) The output is; <QueryDict: {'query': ['membrane'], 'country[]': ['DE']}> {'query': {'bool': {'must': [{'multi_match': {'fields': ['title', 'abstract'], 'query': 'membrane'}}, {'terms': {'country': None}}]}}} -
why does the sqlite3 keeps telling me that i don't have a table called User?
i create a model on django this way: class User(models.Model): username = models.CharField(max_length=50) email = models.CharField(max_length=50) password = models.CharField(max_length=50) phone = models.CharField(max_length=80) and i then i use both commands: python manage.py makemigrations python manage.py migrate and still i get the error: django.db.utils.OperationalError: no such table: myapp_User (im using sqlite3 as a default database) is there a way to solve it or should i use PostgreSQL better? -
TypeError NoneType in Python script when running Django application
I get the error: TypeError: 'NoneType' object is not subscriptable. You can view the code below. The strange thing is when I run the code in Notebook it works. But when I run this in Django I get this NoneType error in return. I need this code in my Django application, so can someone please help. def update_pie(year, changed_id): dff = data[data['year'] == year] if changed_id[-1] == "." or changed_id[-1] == "1": dff = dff.groupby('air quality', as_index=False).count() dff = dff.rename(columns = {"country": "count"}) elif changed_id[-1] != "1" and changed_id[-1] != ".": dff = dff[dff['continent code'] == int(changed_id[-1]) - 1] dff = dff.groupby('air quality', as_index=False).count() dff = dff.rename(columns = {"country": "count"}) -
Host match not found. Google firebase messaging
I am buliding uber-like-delivery app using django. I just implemented the firebase messaging but each time i try to add a phone number so that it sends a verification code it give me the error "Hostmatch not foundenter image description here" so please anyone with an idea on how i can solve this. I tried the whitelisting thing , itdoesnt change anything or maybe its my code. ` Phone Number <div id="recaptcha-container"></div> <div id="get-code" class="input-group mb-3 {% if request.user.customer.phone_number %} d-none {% endif %}"> <label> <input type="text" class="form-control" placeholder="Your phone number"> </label> <div class="input-group-append"> <button class="btn btn-warning" type="button">Send code</button> </div> </div> <div id="verify-code" class="input-group mb-3 d-none"> <label> <input type="text" class="form-control" placeholder="Verification code"> </label> <div class="input-group-append"> <button class="btn btn-success" type="button">Verify code</button> </div> </div> <div id="change-phone" class="input-group mb-3 {% if not request.user.customer.phone_number %} d-none {% endif %}"> <label> <input type="text" class="form-control" disabled value="{{ requeat.user.customer.phone_number }}"> </label> <div class="input-group-append"> <button class="btn btn-warning" type="button">Change</button> </div> </div> </div> function onVerify(idToken) { var form = document.createElement("form"); form.method = "POST"; var element1 = document.createElement("input"); element1.name = "id_token"; element1.value = idToken; form.appendChild(element1); var element2 = document.createElement("input"); element2.name = "action"; element2.value = "update_phone"; form.appendChild(element2); var element3 = document.createElement("input"); element3.name = "csrfmiddlewaretoken"; element3.value = "{{ csrf_token }}"; form.appendChild(element3); document.body.appendChild(form); form.submit(); … -
Use data from get_context_data in form_valid method
How can i use value from dictionary context in form_valid? eg. def get_context_data(self, **kwargs): context_data = super(ProductView, self).get_context_data(**kwargs) product_obj = Product.objects.get(id=self.kwargs['pk']) user_id = product_obj.user_id user_obj = User.objects.get(id=user_id) context_data['email'] = user_obj.email return context_data def form_valid(self, form, **kwargs): email = context_data['email'] # need use this value return super(ProductView, self).form_valid(form)