Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid port number in django app url in comination with apache2
My django website is hosted on ubuntu apache2 vps which reserves port 80. I want to hide or avoid portnumber in django url. By googling i learnt using port 80 will help for that. But apache2 has reserved port 80. Is there any workaround to fix it ? Any hint will be greatly apprecitated. -
how to include a page in every page? (django)
I have a file named common.html. I want to show this HTML page in every page; with Django. like when you include something with WordPress hooks. -
Save() is prohibited to prevent data loss
I'm getting a save() prohibited to prevent data loss due to unsaved related object 'user' in my account views. The line with account = form.save() to be exact. Here's my views, account model, and registration form: Registration form: class RegistrationForm(UserCreationForm): steam_uid = forms.CharField(max_length=17, help_text="Required. Add a valid id") email = forms.EmailField(max_length=255, help_text="Required. Add a valid email") class Meta: model = account fields = ('steam_uid', 'email', 'username', 'password1', 'password2') def clean_email(self): email = self.cleaned_data['email'].lower() try: account = account.objects.get(email=email) except Exception as e: return email raise forms.ValidationError(f"Email {email} is already in use.") def clean_username(self): username = self.cleaned_data['username'] try: account = account.objects.get(username=username) except Exception as e: return username raise forms.ValidationError(f"Username {username} is already in use.") class AccountAuthenticationForm(forms.ModelForm): password = forms.CharField(label="Password", widget=forms.PasswordInput) class Meta: model = account fields = ("username", "password") def clean(self): if self.is_valid(): username = self.cleaned_data['username'] password = self.cleaned_data['password'] if not authenticate(username=username, password=password): raise forms.ValidationError("Invalid Login") Register view: def register_view(request, *args, **kwargs): user = request.user if user.is_authenticated: return HttpResponse("You are already authenticated as " + str(user.email)) context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): account = form.save() email = form.cleaned_data.get('email').lower() raw_password = form.cleaned_data.get('password1') # Account has already been authenticated at this point. Causes 'AnonymousUser' object has no attribute '_meta' error. … -
Django - Left Click on the link not working but right click with new tab works
I have a DropDown Menu in my Navbar which shows the recent Notifications for the user. The data is coming dynamically from the Database through Django, and every notification is linked to another Page (to access that, I am getting the ID of the Notification and sending that to views.py) My problem is, I can not left click on the Notification. I have tried to make lots of changes but still with no result. The links do work if I Right Click on any of them and open them in New Tab. The .html file contains this following code which shows all the notifications, <ul class="setting-area"> <li> <a href="#" title="Notification" data-ripple=""> <i class="ti-bell"></i> {% if fetch_notification_count > 2 %} <span class="text-danger"> (2+) </span> {% else %} <span>{{fetch_notification_count}}</span> {% endif %} </a> <div class="dropdowns"> <span>{{fetch_notification_count}} New Notifications</span> <ul class="drops-menu"> {% for i in fetch_notification %} <li> <span><a href="{% url 'opennotification' i.post_id.id %}" title=""></span> <div> {% if i.show_user.User_Image %} <img class="card-img-top" style=" vertical-align: middle;width: 50px;height: 50px;border-radius: 50%;" src={{ i.show_user.User_Image.url}} alt=""> {% elif t == 1 %} <img class="card-img-top" style=" vertical-align: middle;width: 50px;height: 50px;border-radius: 50%;" src={{ i.User_Image.url}} alt=""> {% else %} <img class="card-img-top" style=" vertical-align: middle;width: 60px;height: 60px;border-radius: 50%;" src="static\images\resources\no-profile.jpg"> {% endif %} … -
Django send_mail() is not grouping emails together based on subject in outlook and apple mail
I am using Django's send_mail() for my email notifications, and I need to send multiple follow up mails which needs to be grouped together based on the same subject. Gmail groups the emails automatically based on the same subject line, but for some reason Outlook and Apple Mail doesn't group them. This results in email spamming in the inbox.I even tried to change the outlook settings to thread conversations, but still no luck.Is there anything I am missing out here ? -
how to separate sentences and assign each sentence to a list element on template
how do I separate the list of strings by "." and render them into separate "li" elements on the template. Currently, it just displays everything in one "li" element. I would really appreciate it if someone can help, thx! models.py class Product(models.Model): benifits = ArrayField(models.CharField(max_length=800), blank=True) @property def benifits_slicing(self): benifit = self.benifits for point in benifit: test = point.split(".") return point HTML <div id="BENIFITS"> <li class="benifits-style">{{ products.benifits_slicing }}</li> </div> what it looks like rn: -
database does not exist postgresql
I am working on connecting a Postgres DB to Django. I have created the db through pgAdmin 4 under the user postgres. I've set my environment variables as followed DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } try: if sys.argv[1:2] != ['test']: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': env('PGHOST'), 'USER': env('PGUSER'), 'NAME': env('PGDATABASE'), 'PASSWORD': env('PGPASSFILE'), 'PORT': env('PGPORT'), } } except: pass with my .env file containing each variable. When I try to migrate it through ubuntu command line I get the error database <dbname> does not exist I've installed psycopg2 and pillow and set local all postgres peer to local all postgres md5. my os is windows 11 so I am wondering if this is happening because my project directory is through ~/directory/to/path and postgres and pgAdmin are installed in /etc/postgresql/ and /mnt/c/'Program Files'/PostgreSQL? Should I move those files from / to ~? NOTE: I've run psql canvasDB and got back role "awilbur" does not exist -
change superuser password in django
I tried to change my admin password but I have an error while running user = User.objects.get(username='normaluser') -
How to get a url param in a django template?
I need to get the param of the url inside a html file, but I need to know if is possible in a tag, or how can I get the url params using Class-based views? My urls.py file from django.urls import path from .views import UsersView urlpatterns = [ path('list/<int:pk>/', UsersView.as_view(), name='user_list'), ] My html file: <!DOCTYPE html> <html lang="en"> <head> <title>Users</title> </head> <body> {{ request.GET.pk }} </body> </html> -
Is there a way to use both UserPassesTestMixin and PermissionRequiredMixin?
I'm trying to create a moderator using Django class-based views in my blog app. It uses the UserPassesTestMixin to prevent other users from editing content that's not theirs. What I'm trying to implement is a group called Manager that has change_blog permissions and I am using PermissionsRequiredMixin in views.py Here is my code so far class UserAccessMixin(PermissionRequiredMixin): def dispatch(self, request, *args, **kwargs): if (not self.request.user.is_authenticated): return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) if not self.has_permission(): return redirect('/') return super(UserAccessMixin, self).dispatch(request, *args, **kwargs) class IssueUpdateView(LoginRequiredMixin, UserPassesTestMixin, UserAccessMixin, UpdateView): raise_exception = False permission_required = 'issues.change_issue' model = Issue fields = ['title', 'content', 'mark_as', 'assignee'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): issue = self.get_object() if self.request.user == issue.author: return True return False When I test this code out as written, the permissions don't work and I get a 403 error page, but everything else functions normally. However, if I delete UserPassesTestMixin and leave PermissionRequiredMixin in, it works but then new problems arise. The original poster can no longer update their own post but when a mod user updates the post, it completely overwrites everything as if the mod user was the original poster. Is there a way to tweak either UserPassesTestMixin or … -
Django admin - Allow inline entires once selected item
I am trying to populate a dropdown in the Django admin panel based on a selected item. I have a customer model class Customer(BaseModel): name = models.CharField(max_length=128) company = models.ForeignKey("Company", models.PROTECT) def __str__(self) -> str: return f"{self.name}" def save(self, **kwargs): return super().save(**kwargs) An invite model class Invite(BaseModel): full_name = models.CharField(max_length=128, blank=True) email = WIEmailField(unique=True) customer = models.ForeignKey( to="Customer", on_delete=models.PROTECT, related_name="invites", ) Customer Invite model that defines the invite and customer class CustomerLocationInvite(BaseModel): location = models.ForeignKey( to=Location ) invite = models.ForeignKey( to=Invite, blank=True, ) Inline for invite class CustomerInviteInline(admin.TabularInline): model = CustomerLocationInvite fields = ("invite", "location", "created_at", "modified_at") readonly_fields = ("created_at", "modified_at") extra = 0 When creating a new Invite, Is it possible to: Display the inline once a company has been selected? When selecting a location from the inline, Filter out the locations based on the company they selected? -
Python zipfile.ZipFile zips a corrupt file
I have a Django view which users can call to zip files at my local server. It uses zipfile.ZipFile to compresses multiple files into a single zip as follows: with ZipFile(env_dir + 'folder.zip', 'w') as zipObj: zipObj.write(dir + '1.json') zipObj.write(dir + '2.json') Then I return this file to the user in response: folder_file = open(full_path, "r", encoding='Cp437') response = HttpResponse(FileWrapper(folder_file), content_type='application/zip') But the downloaded file is corrupt, I can't open it using ubuntu archive manager. Then when i try to unzip the file using python with the same package in my django server, I still get the error: with ZipFile(file_path, 'r') as zip_ref: zip_ref.extractall(dir) The error I get is: File ".../views.py", line 38, in post with ZipFile(file_path, 'r') as zip_ref: File "/usr/lib/python3.8/zipfile.py", line 1269, in __init__ self._RealGetContents() File "/usr/lib/python3.8/zipfile.py", line 1354, in _RealGetContents fp.seek(self.start_dir, 0) OSError: [Errno 22] Invalid argument Any idea what am I doing wrong here? -
Django ignore TemplateSyntaxError. Vue Syntax
I'm building a pwa on top of django. In the pwa.html I use valid vue syntax: {{ counter() }} or {{ el| removehtml() | truncate(40) }} Works flawless in a non Django project. I get an TemplateSyntaxError on runserver, how can I ignore this, cause this is valid for vue syntax. -
Modify how a field displays on Django tables2 table
I am trying to take a date field and display it in a django tables2 table. The issue is my field uses Djangos DateTimeField and has the time added on to the end which I don't care to display. My initial thought was to use a property decorator, and reference that in my table rather than using my original date field. But when I try to use split inside my property function nothing gets displayed in my table. If I modify the function to just print a string without using split it seems to work as intended. It seems that I can't use split anywhere in the function, even if I return a hard coded string instead of whatever I am splitting. Using split within the function just breaks it and makes it display nothing. Why can I not use split inside my function, and is there an alternative or better way of modifying what the date looks like when it displays on my table? #tables.py class ReportTable(tables.Table): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: attrs = {"class": "mytable"} model = models.Report fields = ("formatted_date") #models.py class Report(models.Model): id = models.AutoField(db_column="RootCauseID", primary_key=True) date = models.DateTimeField(db_column="date", blank=False, null=True) @property def … -
how fix Django error column accounts_sitename.languageCode does not exist
i create models.py in accounts for the siteName model but i dont know how to fix error it. how fix Django error column accounts_sitename.languageCode does not exist ProgrammingError at /ar/admin/accounts/sitename/ column accounts_sitename.languageCode does not exist LINE 1: ...tename"."user_id", "accounts_sitename"."site_id", "accounts_... ^ class siteName(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) site = models.ForeignKey(Site, on_delete=models.CASCADE) languageCode = models.CharField( max_length=10, choices=LANGUAGES,unique=True ) nameHome = models.CharField(max_length=111, blank=True) imageHome = models.ImageField( upload_to='site/' ) bioHome = models.TextField(max_length=5500, blank=True) nameVideo = models.CharField(max_length=111, blank=True) imageVideo = models.ImageField( upload_to='site/' ) bioVideo = models.TextField(max_length=5500, blank=True) nameForum = models.CharField(max_length=111, blank=True) imageForum = models.ImageField( upload_to='site/' ) bioForum = models.TextField(max_length=5500, blank=True) def __str__(self): return self.nameHome ProgrammingError at /ar/admin/accounts/sitename/ column accounts_sitename.languageCode does not exist LINE 1: ...tename"."user_id", "accounts_sitename"."site_id", "accounts_... ^ -
how to use triple nested quotes in django tempates?
i'm trying to use inline CSS and loading an image as a background in Django template. i need three quotes but don't know how to do it. how can i fix the code bellow? <div class="full-background" style="background-image: url("{% static '/img/curved-images/white-curved.jpg' %}")"></div> -
Django Admin Page execute javascript on Custom Action Buttons
I'm trying to add a custom button in each row next to a user to the django admin page which makes it easier for the admin to click the button and generate a password reset link for a particular user rather than navigate to the hidden actions section of the django admin page. Something like this - https://hakibenita.com/how-to-add-custom-action-buttons-to-django-admin Following is the code I've implemented and it works and navigates to a new page with the correct reset-password request and the reset_password() method executes with a link being sent to the user. However, when I click the button, I would like to send an AJAX GET request to the same url as above and just a show an alert to the admin on request completion instead of navigating to a new page. Currently I'm unable to run the javascript code using the format_html method in Django (see code below) Is there a way to run the class UserAdmin(Admin.modelAdmin): list_display = ('name', 'email', 'custom_actions') form = forms.UserAdminForm def get_urls(self): urls = super().get_urls() custom_urls = [ url( r'reset-password/(?P<user_id>.+)', self.admin_site.admin_view(self.reset-password), name='reset-password', ), ] return custom_urls + urls def custom_actions(self, obj): user = user_model.User.get(user_id=obj.id) password_reset_url = reverse('admin:reset-password', args=[user.id]) return mark_safe(format_html( f'<a class="button" onclick="parent.location=\'{password_reset_url}\'" >Reset Password</a>&nbsp;' … -
How to substract custom date in models.DateField from now()?
I still can't find a working solution, hence I decided to throw my first post. Note, I'm a beginner in Django. Building a portal that displays days since the user has been verified. I tested my model without using custom DateField (verified_since), just with date_joined, and it works properly - showing the count of days remaining (I countdown from 365 days, I am not worried about the leap year yet) since the user has registered in the database vs. today. class Profile(models.Model): verified_since = models.DateField(default=now) @property def ver_since(self): return 365 - (now() - self.user.date_joined).days Now if I use verified_since instead date_joined, I get an error. I suspect this is due to a different format of a date, or maybe a string format instead of a date which can't be subtracted then from datetime.now() verified_since is manually entered date on the form by user. class Profile(models.Model): verified_since = models.DateField(default=now) @property def ver_since(self): return 365 - (now() - self.user.verified_since).days Here is settings: TIME_ZONE = 'CET' USE_I18N = True USE_L10N = False USE_TZ = True TIME_INPUT_FORMATS = ('%H:%M',) DATE_INPUT_FORMATS = ['%d/%m/%Y'] -
Post Blob Image to django rest framework with ajax
I have a html page that allows a user to take a screenshot from their camera. This screenshot is then rendered in the page with the function from main.js down below. If i do console.log(image) i get image tag with a src to a blob:http that has the image. Now for the fun part. I want to post this image to my api in django rest framework. Basically how do i go from a blob image to a post request to the api? I tried using $.ajax but I dont know how to format the "blob data" to be accepted for the "data:" parameter field in ajax. Note also that i'm not using forms in the html, when i do that the html page gets refreshed as soon as i take a screenshot so the image does not stay on the page.. If I have to use forms in order to make this work, please let me know and I will try another approach. main.js async function grabFrame() { const img = await imageCapture.grabFrame(); const url = URL.createObjectURL(await imageCapture.takePhoto()); document.querySelector("img").src = url #id_image is where the screenshot is located const image = document.getElementById('id_image') console.log(image) index.html <button onclick="grabFrame()">Grab Frame</button> <img id="id_image" … -
Hovering over Morris Chart is not working as expected
Hovering is not working for my chart, any suggestions as to what it could be? This is a django template with the Morris Chart within. I've got Morris Chart working on other django templates just fine so I'm not sure if it's the payload that the chart doesn't like or just a simple syntax issue - thanks!! {% for item in data_alpha %} <div class="row"> <div class="col-lg-12"> <div class="panel panel-primary"> <div class="panel-heading"> Load Time | {{ item.link }} <button class="btn btn-sm btn-default vertical-allign-baseline pull-right" data-toggle="modal" data-target="#helpLoadTime"> <i class="fa fa-question-circle" aria-hidden="true"></i> Help </button> </div> <div class="panel-body"> {% for key, value in regions.items %} <span class="regions" style="background-color: {{ value }}"></span> <span> {{ key }}</span> {% endfor %} <div id="tg-load-chart_{{ forloop.counter }}" style="height: 300px;"></div> <script> rawData = {{item.tg_load_time_graph|safe}}; aws_regions = Object.keys({{item.tg_load_time_graph|safe}}); processedData = processRawData(rawData, aws_regions); chartData = processToChartData(processedData); colours = Object.values({{regions|safe}}); new Morris.Line({ element: 'tg-load-chart_{{ forloop.counter }}', data: chartData, xkey: 'datetime', ykeys: aws_regions, labels: aws_regions, hideHover: 'auto', pointSize: 0, xLabels: '10min', lineColors: colours, }); </script> -
Django-ckeditor dialog box fields are not displaying properly
I'm trying to use Django-CKEditor for a RichTextField, the text editor is showing fine, but the dialog boxes for its options are displaying with a ruined text field in my forms. The editor and dialog boxes are working fine in admin forms, I tried to use bootstrap4 but the problem is still there. {{form.media}} is on my page here is a picture of the problem. -
.Env file in Django project
I write this lines in .env file in django project to link my project to my Data base but visual code make a problem to the file -
ZMQ - Multiple workers with the same socket Dealer
I have a Python package with the purpose of serving as Dealer to several pieces of code scattered in my solution. But until now it was only being used in a Django Views, so within an application. But now I would like to use this package in a separate script and it seems to me that the script is failing to execute zmq.Context.instance().socket(zmq.DEALER).connect(SOCKET_ADDR) because it is already being used by views.py. Does it make sense? dealer.py (package): imports... context = zmq.Context.instance() workerCnctn = context.socket(zmq.DEALER) workerCnctn.identity = 'xxxxx' workerCnctn.setsockopt(zmq.LINGER, 0) workerCnctn.connect(SOCKET_ADDR) class A: def __init__(self): self.workerCnctn = workerCnctn def send(self, arg1, arg2): ... self.workerCnctn.send_string(msg) views.py: imports ... import dealer ... @api_view(["POST"]) def send(request): ... dealer = dealer.A() A.send(arg1, arg2) ... script.py: imports ... import dealer ... def main(): ... dealer = dealer.A() A.send(arg1, arg2) ... The script is to be called manually and the Django application is running constantly. What I noticed is that in the logs of the Router I can only catch messages that come from views.py. So I ask, can't I have different workers with the same purpose using the same socket? -
Django websockets and channels group_send not working
I started looking into websockets and I would liek to implement realtime communication between web-client (Angular 13) and Python app. As backend I used Django with implemented websockets and channels As i am having problem i simplified code as much as i could so a lot of values are hardcoded for a sake to make it work. (Right now it is One WebClient and one Bot) I implemented 2 Consumers. Bot and webclient: class BotConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.channel_layer.group_add("bot","dev") async def disconnect(self, close_code): await self.channel_layer.group_discard("bot","dev") async def receive(self, text_data): await self.channel_layer.group_send("dev",{"type": "recv","text": "test"}) print("Data sent to group") class WebClientConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.channel_layer.group_add("client","dev") async def recv(self,event): print("Consumer received smthing from channels") async def disconnect(self, close_code): await self.channel_layer.group_discard("client","dev") async def receive(self, text_data): print("Smthing received") my channel_layer setup in Setting.py CHANNEL_LAYERS = { 'default': { # 'BACKEND': 'channels_redis.core.RedisChannelLayer', # 'CONFIG': { # "hosts": [('192.168.1.10', 6379)], # }, "BACKEND": "channels.layers.InMemoryChannelLayer" }} I tried both Redis with local server running and in memory channels My websocket's routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'live/bot', consumers.BotConsumer.as_asgi()), re_path(r'live/webclient', consumers.WebClientConsumer.as_asgi()), ] My behavior: Django logs: HTTP POST /core/UpdateAvailableServers 200 [0.07, 127.0.0.1:50494] HTTP POST /core/GetPostInfo 200 [0.02, … -
Djnago Adding ManytoMany objects to an object after being created
Im trying to add a many to many field to an object after it is created but keep running into the same error: Direct assignment to the forward side of a many-to-many set is prohibited. Use dogs.set() instead. in my models.py class linkedDog(models.Model): linked_dog = models.ForeignKey(Dog, blank=True, null=True, on_delete=models.CASCADE) service_chosen = models.ManyToManyField(Service, blank=True) shampoos_chosen = models.ManyToManyField(Shampoo, blank=True) total_time = models.IntegerField(blank=True, default=0) class PsuedoAppointment(models.Model): client = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) dogs = models.ManyToManyField(linkedDog, blank=True) total_time = models.IntegerField(blank=False, default=0) I am trying to add a linkedDog object to dogs field in my views I've used this question as a reference Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead But can't figure out what I'm doing differently or where its going wrong @login_required def loggedin_appointment_view(request): if request.method == "POST": form = linkedDogForm(request.POST, user=request.user) if form.is_valid(): dog = form.save() dog_id = dog.id dogsquery = linkedDog.objects.filter(id=dog_id) appointment = PsuedoAppointment.objects.create(client=request.user, dogs=None, total_time=None) for dog in dogsquery: appointment.dogs.add(dog) return render(request, 'home.html') else: dog_form = linkedDogForm(user=request.user) return render(request, "appointment_template/loggedin_appointmentmaker.html", context={'dog_form' : dog_form}) I also tried dog = form.save() dog_id = dog.id dogsquery = linkedDog.objects.filter(id=dog_id) appointment = PsuedoAppointment.objects.create(client=request.user, dogs=None, total_time=None) appointment.dogs.set(dogsquery)