Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Weird behavior in django __date filter
I'm trying to filter the model by date. class Participant(models.Model): email = models.CharField(unique=True, max_length=255) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email There are 4 entries that were created at date(2020, 3, 28): 2020-03-28 06:28:14.475307+00:00 2020-03-28 06:16:05.312023+00:00 2020-03-28 06:11:27.322146+00:00 2020-03-28 06:03:27.500164+00:00 When I'm doing this: Participant.objects.filter(created_at__gte=datetime.date(2020, 3, 28), created_at__lt=datetime.date(2020, 3, 29)) I'm getting these 4 entries. But, when I'm doing this: Participant.objects.filter(created_at__date=datetime.date(2020, 3, 28)) I'm getting an empty queryset. I have: TIME_ZONE = "UTC" USE_TZ = True I'm in timezone Asia/Kolkata I'm using django version 2.2, Mysql, python version 3.6.7 I have seen this answer: https://stackoverflow.com/a/55608903/5157204 but I'm unable to figure out what the problem is. Can anyone help me figure out the problem? -
Calculate book value of share positions in Django
I'm working on a small project where I want to show a summary of accounts in cash and shares. There is some Python code involved and I want to present the output in a template. I'm trying to calculate the book value of each position of the share portfolio however I’m getting an error and I don’t know what to do. Your help would be much appreciated. model.py class Shares(models.Model): name = models.CharField(max_length=128) ticker = models.CharField(max_length=128) date = models.DateField() quantity = models.FloatField(default=0) price = models.FloatField(default=0) currency = models.CharField(max_length=128) view.py class SharesListView(ListView): model = Shares context_object_name = 'shares_details' def get_context_data(self, **kwargs): context = super(SharesListView, self).get_context_data(**kwargs) latest_fx = fx_table.objects.last() queryset = context['shares_details'].annotate(book_value=Case( When(Q(quantity >0, then=F('price')*('quantity'))), default=Value(0), output_field=FloatField() ) ) context['shares_details'] = queryset context['total_shares'] = queryset.aggregate(sum=Sum('book_value'))['sum'] return context Error details Exception Type:NameError Exception Value:name 'quantity' is not defined Exception Location:...views.py in get_context_data, line 58 Thanks -
Django bootstrap modal not showing
I am trying to show a modal on a button click, however, after I click on the modal it does not show the modal, I do not know what seems to be the issue since I followed the exact tutorial on bootstrap and W3Schools. Here, is my template: {% for comment in comments %} <div class="border-bottom"> <div class="row pt-1 pl-4"> <div class="col-xs"> <img class="img-create-post rounded-circle mr-1" style="width: 2.1rem;height: 2.1rem;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg" alt="Profile image"> </div> <div class="col-xs" style="margin-bottom: 0;"> <span class="text-dark font-size-smaller" href="#" style="font-weight: 500;">{{ comment.name.first_name }}</span> <span class="text-muted small">•</span> <a class="text-muted small" href="#">@{{ comment.name.username }}</a> <span class="text-muted small">•</span> <span class="text-muted small">{{ comment.get_created_on }}</span> <p class="font-weight-light pl-1">{{ comment.body }}</p> </div> </div> <div class="d-flex justify-content-between"> <div> <span class="text-muted small view-replies">view {{ comment.replies.count }} replies <i class="fas fa-caret-down"></i></span> </div> <div> <!-- button to show modal --> <button class="btn btn-sm small float-right text-muted button-outline-light reply-btn" type="button" data-toggle="modal" data-target="modal-comment-reply">Reply</button> </div> </div> <div class="comment-replies"> {% for reply in comment.replies.all %} <div class="row pt-1 pl-4"> <div class="col-xs"> <img class="img-create-post rounded-circle mr-1" style="width: 2.1rem;height: 2.1rem;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg" alt="Profile image"> </div> <div class="col-xs" style="margin-bottom: 0;"> <span class="text-dark font-size-smaller" href="#" style="font-weight: 500;">{{ comment.name.first_name }}</span> <span class="text-muted small">•</span> <a class="text-muted small" href="#">@{{ comment.name.username }}</a> <span class="text-muted small">•</span> <span class="text-muted small">{{ comment.get_created_on }}</span> <p … -
How can I pull data from my database using the Django ORM that annotates values for each day?
I have a Django app that is attached to a MySQL database. The database is full of records - several million of them. My models look like this: class LAN(models.Model): ... class Record(models.Model): start_time = models.DateTimeField(...) end_time = models.DateTimeField(...) ip_address = models.CharField(...) LAN = models.ForeignKey(LAN, related_name="records", ...) bytes_downloaded = models.BigIntegerField(...) bytes_uploaded = models.BigIntegerField(...) Each record reflects a window of time, and shows if a particular IP address on particular LAN did any downloading or uploading during that window. What I need to know is this: Given a beginning date, and end date, give me a table of which DAYS a particular LAN had ANY activity (has any records) Ex: Between Jan 1 and Jan 31, tell me which DAYS LAN A had ANY records on them Assume that once in a while, a LAN will shut down for days at a time and have no records or any activity on those days. My Solution: I can do this the slow way by attaching some methods to my LAN model: class LAN(models.Model): ... # Returns True if there are records for the current LAN between 2 given dates # Returns False otherwise def online(self, start, end): criterion1 = Q(start_time__lt=end) criterion2 = … -
Sprinkling VueJs components into Django templates
I'm working on a Django site and I'm looking to "sprinkle" in some Vue components to the Django rendered templates. I'm working in a single repository and have webpack setup to create style/js bundles that I use within the Django templates. I'm struggling to get the functionality working how I'd like it, mainly regarding renderless Vue components, since I want to handle all (or at least the vast majority) of html within the Django templates and just use Vue components for some logic in some places. I'm using some of the advice from here but it didn't quite work as they'd suggested (although that's exactly how i'm hoping it can work) and I feel like I need to take advantage of scoped-slots. I am using the Vue esm distribution to include the Vue compiler. The setup I'm currently using is as follows: // webpack_entrypoint.js import Vue from "vue"; import RenderlessComponent from "./components/RenderlessComponent.vue" // I will also be registering additional components here in future for other pages // and I'm under the impression that doing it this way allows me to reuse the Vue instance // defined below Vue.component("renderless-component", RenderlessComponent) new Vue({ el: "#app" }) // components/RenderlessComponent.vue <template></template> <script> // Other … -
How to store attachement files(image) to remote location?
I am using django-summernote, now i want to change upload location to remote(Another hosting platform) , Please anyone help me. Thanks in advance. -
How to access django tenant_schemas Tenant URL in browser
Good day! I am using django tenant_schemas (https://django-tenant-schemas.readthedocs.io/en/latest/) to develop a SaaS web application. I have created a Tenant with a domain_url but I cannot access it through a web browser. Here is some parts of my settings.py: ALLOWED_HOSTS = ['*'] SHARED_APPS = ( 'tenant_schemas', 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom Apps # Third Party Apps 'corsheaders', 'rest_framework', 'dynamic_preferences', # For Pref # 'api.apps.ApiConfig', 'revproxy', # For Reports 'tenant_schemas', #'taggit', 'taggit_serializer' # For tags - might not use with Vue..) TENANT_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',) INSTALLED_APPS = ( 'tenant_schemas', 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom Apps # Third Party Apps 'corsheaders', 'rest_framework', 'dynamic_preferences', # For Pref 'api.apps.ApiConfig', 'revproxy', # For Reports #'taggit', 'taggit_serializer' # For tags - might not use with Vue.. ) DEFAULT_FILE_STORAGE = 'tenant_schemas.storage.TenantFileSystemStorage' MIDDLEWARE_CLASSES = ( 'tenant_schemas.middleware.TenantMiddleware', # ...) DATABASE_ROUTERS = ( 'tenant_schemas.routers.TenantSyncRouter', ) TENANT_MODEL = "tenant_public.Tenant" # app.Model Created Tenant using python manage.py shell: tenant = Tenant(domain_url='tenant.demo.com', schema_name='tenant1', name='My First Tenant') Save: tenant.save() However, when I run python manage.py runserver and access tenant.demo.com, I get a 404 Not Found response. -
bulk_update: django-field-history vs django-simple-history
I am using Django v3.0.5. I have been using django-simple-history app in my project. It works well. However, I noticed that it doesn't work with bulk_update. This is known / documented (https://django-simple-history.readthedocs.io/en/latest/common_issues.html#bulk-creating-and-queryset-updating): Unlike with bulk_create, queryset updates perform an SQL update query on the queryset, and never return the actual updated objects (which would be necessary for the inserts into the historical table). Thus, we tell you that queryset updates will not save history (since no post_save signal is sent). Today, I found the django-field-history plugin which is very similar. I was wondering if anyone that has used this app can tell if it has the same limitation with bulk_update like django-simple-history. I browsed the user guide but could not not see anything relevant. In my models, I only need to track history for a fields so I am considering switching to this option if it works with bulk_update. -
Django channels can't connect
I have problem using channels. They work well with localhost connection but don't work with my wifi ip address connection. But HTTP request works well with my wifi ip connection. Redis Server is opend at ip 0.0.0.0 Drf server is opend at 0:8080 With python redis module, both of localhost and my wifi ip connection are available. Settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('my_wifi_ip_address', 1280)], }, }, } With this code, localhost connection is available but connection with my_wifi_ip_address is not available I'm saying ws://127.0.0.01:8080/ws/chat/ this works ws://my_wifi_ip_address/ws/chat/ this does not work Thanks for your help -
Django admin forgin key show all choices inted of relation
I have three models first model is country second model is cities every country have many cities in third model have two drop menu country and cities in admin panel it show all country and all cities but i want to show all cities to choosen country only -
How to resolve an error 404 for django-social?
I want to be able to login through social media. Followed all the steps (registered app), the login works just fine but does not go through because django does not recognize my url. This is my call to the api endpoint facebookLogin(token: string):any{ return this.http.post(environment.api + 'fblogin/', {token:this.token}).subscribe( (onSucess:any) => { localStorage.setItem(this._tokenKey, onSucess.token) }, onFail => { console.log(onFail) } ); } But I get the following error : POST http://127.0.0.1:8000/api/fblogin/ 404 (Not Found). From this I know there to be something wrong with my django urls. And indeed going to http://127.0.0.1:8000/api/fblogin/ gave me a page not found error and that it tried to match several other urls. However I can't see what is wrong with my urls URLS in my app from django.conf.urls import url, include from rest_framework import routers from . import views from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token from social_django import urls router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'fblogin/', include(urls)), url(r'auth/', obtain_jwt_token), url(r'refresh/', refresh_jwt_token) ] URLS in my project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('Backend.api.urls')) ] Other URLS like http://127.0.0.1:8000/api/users/ do work. I also am under the impression that all of my settings are in … -
DJANGO: Pass a specific variable from template to view when button is pressed
I am building an online store that displays products with various fields to show in the template (name, price, item ID, etc), and I am doing this for every product passed in. So when the page loads I have many tags that share the same name. My problem is that I don't know how to pass the item ID into the next view. This value is the unique identifier so I need it to perform a select statement from my database to retrieve all of the items information. That information can then be displayed on another page where the user can see all details and add it to their cart. I tried to use a hidden form and use POST to get the value but I can't seem to get the exact element that I want since there are many with the same div tag ID. When each item is hovered over, a button appears to view the item details. When that button is pressed, this is where I need to send the item ID from the labeled div tag into the next view. views.py # Products page to view all items def products_page(request): args = { 'products': products, } … -
How to debug django staticfiles served with whitenoise, gunicorn, and heroku?
I've got a project that runs on Heroku from a Dockerfile and heroku.yml. The site generally works, but I am having trouble with static files. collectstatic is run when building the pack. I'm trying to use whitenoise but not sure why it's not working. It sounds so simple so I'm sure it's something silly. heroku.yml setup: addons: - plan: heroku-postgresql build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn records_project.wsgi settings.py MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', 'django.contrib.sites.middleware.CurrentSiteMiddleware', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', ... more stuff here... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # for referencing files with a URL STATIC_URL = '/static/' # where to find static files when local STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] # location of satatic files for production STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # how Django should look for static file directories; below is default STATICFILES_FINDERS = [ # defaults "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] # This gives me a 500 error # STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' urls.py urlpatterns here... ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
unexpected indent error installing django
Working through book "Django for Beginners". Have successfully completed 3 projects. Starting on Chapter 4. Forgot to exit pipenv from previous project. Created new directory, issued "pipenv install django==2.2.5", which resulted in following: PS C:\users\phil\desktop\django\blog> pipenv install django==2.2.5 Creating a virtualenv for this project… Pipfile: C:\Users\Phil\Desktop\django\Pipfile Using c:\users\phil\appdata\local\programs\python\python38\python.exe (3.8.2) to create virtualenv… [= ] Creating virtual environment...Already using interpreter c:\users\phil\appdata\local\programs\python\python38\python.exe Using base prefix 'c:\users\phil\appdata\local\programs\python\python38' New python executable in C:\Users\Phil.virtualenvs\django-nLBe_sZT\Scripts\python.exe Command C:\Users\Phil.virtu...T\Scripts\python.exe -m pip config list had error code 1 Failed creating virtual environment pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\cli\command.py", line 235, in install pipenv.exceptions.VirtualenvCreationException: retcode = do_install( pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\core.py", line 1734, in do_install pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\core.py", line 570, in ensure_project pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\core.py", line 505, in ensure_virtualenv pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\core.py", line 934, in do_create_virtualenv pipenv.exceptions.VirtualenvCreationException: raise exceptions.VirtualenvCreationException( pipenv.exceptions.VirtualenvCreationException: Traceback (most recent call last): File "c:\users\phil\appdata\local\programs\python\python38\lib\runpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\phil\appdata\local\programs\python\python38\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 2628, in main() File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 860, in main create_environment( File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 1173, in create_environment install_wheel(to_install, py_executable, search_dirs, download=download) File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 1019, in install_wheel _install_wheel_with_search_dir(download, project_names, py_executable, search_dirs) File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 1046, in _install_wheel_with_search_dir config = _pip_config(py_executable, python_path) File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 1128, in _pip_config config[key] = … -
How can I fetch all news headlines from nested tags?
For starters, i'm new in Python and i'm working with BS not too long. I am trying to get all the news headlines from all the articles on the website, but for some reason these loops doesn't work properly. But why?! I do not understand.. With this program code I tell the computer that I want to find and fetch all the 'a' tags that are inside multiple nested tags, isn't it? And i'm iterating over a nested tag to the next nested tag so i can fetch the "a" tag which contain the news headline. My code: url = "https://loudwire.com/category/news/" content = sessions.get(url, verify=False).content soup = BeautifulSoup(content, "html.parser") section = soup.findAll('section', {'class': 'blogroll row-standard carbonwidget-taxonomy outgrow no-band'}) for stn in section: blog = stn.findAll('div', {'class': 'blogroll-inner clearfix'}) for blogroll in blog: article = blogroll.findAll('article') for i in article: posts = i.findAll('div', {'class':'content'}) for wrapper in posts: a = wrapper.findAll('a', {'class': 'title'}) for link in a: print(link.get('title')) context = {'contex': link.get_text(strip=True)} return render(request, 'music/news.html', context) So, what am I doing wrong? Maybe you can show me where did i make a mistake and how to do this correctly? Thank you, any help will be invaluable! -
Django using custom icon in admin change list view
I want to have custom links in the change list view in Django admin. Currently, I can setup the links and get the three links in the last column: However, I would like to have three images instead of the text, but I do not know how to reference the static files for the images inside the corresponding models.py file. I tried: def get_icons(self): """ Icons with link for admin """ iconV = reverse('submission_view_details', args=[self.id]) imgV = mark_safe(f"<img src='statics/icons/icon_view.png'>") icon_V = mark_safe(f"<a href={iconV} target=_blank>{imgV} </a>") iconE = reverse('submission_edit', args=[self.id]) icon_E = mark_safe(f"<a href={iconE} target=_blank>Edit </a>") iconP = reverse('submission_pdf', args=[self.id]) icon_P = mark_safe(f"<a href={iconP} target=_blank>Print</a>") return icon_V + icon_E + icon_P #--- but this results in: In principle, the static files are well configured since I use custom css and jquery files stored in the static folder where the icons are located. -
Wndows IIS 10 will not serve static files from Django 2.2. . . How can I fix this?
The website displays to localhost without css, js, or images. I setup Windows IIS according to this blog including the final section about static files. The methods outlined are similar to answers from this question, this question, this blog, and this youtube video on how to serve static files from django with IIS. Django settings: STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') # tested in shell, it is where I expect at the same level as manage.py The directory "static" was created with manage.py collectstatic in the expected STATIC_ROOT location with all of the static files contained The static directory was then added as a virtual directory: Then I removed the django handler I created from the static directories handler mappings: I unlocked the handlers at the root: The django application did display properly, with static files, when I tried using Wampserver w/ Apache and mod_wsgi. Unfortunately, it appears windows IIS will be the better solution for other unrelated reasons. Not too mention Wampserver is a development server, not a production server. I defined a path for the environment variable WSGI_LOG, the logs generated have no errors. Just states wfastcgi.py was initialized and will restart when there are changes to … -
Django InlineFormSet differentiate existing db forms vs extra forms
Consider my database has 2 existing instances of MyModel. My InlineFormSet displays both existing instances and 1 extra. Forms with existing instances only the state can be changed Forms with the extra all fields can be changed How do I achieve this? ==== (user can edit bold; italics is locked) [MyModel1 Name] . . [MyModel1 State] [MyModel2 Name] . . [MyModel2 State] [NewExtra Name] . . [NewExtra State] <-- both can be changed ==== I was trying to use {{ form.name.instance }} vs {{ form.name }} But I don't know how to differentiate between existing instances and extras. # forms.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ["name", "state"] MyModelFormSet = inlineformset_factory( MyParent, MyModel, form=MyModelForm, can_delete=False, extra=1 ) # views.py class UpdateMyModelsView(UpdateView): template_name = "update_mymodel.html" model = MyParent fields=[] success_url = reverse_lazy('update_success') def get_object(self, *args, **kwargs): return MyParent.objects.get(admin=self.request.user) def get_context_data(self, **kwargs): context = super(UpdateMyModelsView, self).get_context_data(**kwargs) parent= MyParent.objects.get(admin=self.request.user) context['parent'] = parent if self.request.POST: context['mymodel_formset'] = MyModelFormSet(self.request.POST, instance=self.object) else: context['mymodel_formset'] = MyModelFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() mymodel_formset= context['mymodel_formset'] with transaction.atomic(): self.object = context['parent'] if mymodel_formset.is_valid(): mymodel_formset.instance = self.object mymodel_formset.save() else: return super(UpdateMyModelsView, self).form_invalid(form) return super(UpdateMyModelsView, self).form_valid(form) # update_mymodel.html <form method="POST" class="pretty-form"> {% csrf_token %} {{ mymodel_formset.management_form … -
Data structure for internally generated images on Django
Let's say I have a django app where many images are internally generated after post requests made by users. Where should I stock these images ? As it is internally generated and not uploaded by users, it does not seem necessary to use the file storage systems and the /media/ location. But it does not seem clever to use the /static/ directory either, as many images will be added (and removed) then they are not static. Moreover I'd like to use a model that contains the images and other information about them. What model field class should I use to handle these images ? As the images are not uploaded by users models.ImageField does not seem appropriate. Thank you :) -
What am I unable to send email using Django?
I have turned on the 'allow less secure apps' on my google account. But when I submit the password reset form, it goes to the password_reset_done.html and DOESN'T show any error. But the mail is not sending. It's neither in my sentbox nor in the inbox of the email it's supposed to send to. This is what my urls.py looks like : from django.contrib.auth import views as auth_views path('password_reset/', auth_views.PasswordResetView.as_view(template_name="my_app/password_reset.html"), name="password_reset"), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name="my_app/password_reset_done.html"), name="password_reset_done"), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="my_app/password_reset_confirm.html"), name="password_reset_confirm" ), path('reset_password/', auth_views.PasswordResetCompleteView.as_view(template_name="my_app/password_reset_complete.html"), name="password_reset_complete" ), And here is the settings.py file: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'my_g_mail_id_here@domain.com' EMAIL_HOST_PASSWORD = '**********' I have literally read every other question and tried everything. Nothing is working for me. I am dying here to find out a solution, please help. -
Django sessions behavior
i am trying to understand how django sessions work so in my cart view i set a session variable named cart_id if i does not already exists , in my inspect element storage i see the session_id and i have a value let's say session_id = 1 ( i am not logged in) now when i login the session_id is different let's say session_id=2 but i am still able to retrieve the data from the previous session (1) , i mean if the session changes i shouldn't be able to do that , why can i do that ?? can anyone explain to me the session behavior ? -
How to create video streaming feature with django?
I want to create video streaming feature that, like twitch or something like that, who have any ideas? -
"double salting" a password with python
I am currently reworking a website that was written in php, in django and I need to copy over the old users. The problem is that the old website uses a "double salted" sha1 hashed password and I don't know how to replicate that with python. The code for the double salted password: sha1($salt . sha1($salt . sha1($password))); Addtionaly I really do not know much about php. Hopefully someone can help me with my issue. -
How to access Django database with JS
I have developed a website for an interactive game (mafia) using Django (python), but then i realized i need the displaying data(such as list of alive players, player messages, list of voted for lynch players, etc.) to be real-time and update instantly, whereas my website needs to be refreshed in order to see the updated database content. This is how it looks After realizing that, I started learning JavaScript, but now that I'm almost done, I noticed that Django and JavaScript functions cannot be called interactively, meaning I can't do JS functions and change database attributes at the same time. So I need an interactive frontend that updates data instantly, while being able to access and change database attributes as well(JS doesn't do this apparently). What should I learn for that? Thanks in advance. -
How to pass request.user / user to message in Django
So I want to let a user message another user. I want the 'sender' field automatically to be 'request.user' and the receiver field to be the user whom the sender clicked on through their profile page. How would I go about passing those into the form? forms.py/InstantMessageForm class InstantMessageForm(forms.ModelForm): class Meta: model = InstantMessage fields = ('receiver','sender','message') def save(self, commit=True): user = super(InstantMessageForm, self).save(commit=False) user.receiver = cleaned_data['receiver'] user.sender = cleaned_data['sender'] user.message = cleaned_data['message'] if commit: user.save() return user views.py/instant_message def instant_message(request): if request.method == 'POST': form = InstantMessageForm(request.POST) if form.is_valid(): form.save() return redirect('dating_app:home') else: form = InstantMessageForm() context = {'form':form} return render(request, 'dating_app/instant_message_form.html',context) models.py class InstantMessage(models.Model): receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE ) message = models.TextField() class InstantMessage(models.Model): receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE ) message = models.TextField() instant_message_form.py {% extends "dating_app/base.html" %} {% load bootstrap4 %} {% block content %} <h1>Start chatting now!</h1> <div class='container'> <form method="post" action="{% url 'dating_app:instant_message' %}" > {% csrf_token %} {{ form.as_p }} <button type="submit">Register</button> </form> </div> {% endblock content %}