Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No module named 'registration' in django 2.2.5
I am using django 2.2.5 with python 3.6 i have installed django-registration by adding it to my project's installed apps and then doing a pip install django-registration. All this worked fine but now when i am trying to perform a python mange.py makemigrations am getting this error. I read a lot of solutions online and they don't seem to work, i tried downgrading the django-registration version to 2.4 but then it uninstall django 2.2.5 because it works with django 1, which will cause some other serious problems. here is my installed app section: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'wewriteapp', 'crispy_forms', ] Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Ahmed\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'registration' -
Django request.user modification not happening in test
I have a view that is changing a field of request.user: def test(request): request.user.is_provider = False request.user.save() print(request.user.is_provider) return HttpResponse(status=200) Now I am testing the function and I have the following test: class RoleSwitchTests(TestCase): def test_switch_to_customer(self): User = get_user_model() user = User.objects.create_user( username='test', email='test', password='test', first_name='test', last_name='test', is_provider=True, is_admin=False, ) self.client.login(username='test', password='test') response = self.client.post('/test/', follow=True) print(user.is_provider) self.assertEqual(response.status_code, 200) self.assertFalse(user.is_provider) self.assertFalse(user.is_provider) fails here. For some reason, request.user.is_provider is False in test, but in test_switch_to_customer, user.is_provider is True. I know these refer to the same user because they have the same id, so why is the modification not being preserved here? -
Django execute order by before filter
i'm using django 2.0.7 so, i want to order a queryset and then select distinct entries, after that, i'm gonna perform some filtering as you can see here i'm doing the order and select distinct stuff forms = Form.objects.order_by('user','-created_at').distinct('user') and here i'm filtering some attributes filterd_qs = forms.filter(**query) the problem is that the order_by query is executed after the filter query which causes unexpected results (it's applying the filter on the whole queryset), the sql query resulted from the last filter : SELECT DISTINCT ON ("table"."user_id") fields FROM "appname_form" WHERE where_clause ORDER BY "appname_form"."user_id" ASC, "appname_form"."created_at" DESC; so how do i force django orm to wrappe the orderby query by the filter query !! any suggestion will do -
Serialize view class django
i need to send the same info via json this is my view class class ContatoreDetailView(LoginRequiredMixin, DetailView): model = Contatore def get_context_data(self, object: Contatore=None, **kwargs): context = super().get_context_data(**kwargs) context['Letture'] = Letture.objects.all().filter(srf=object.srf) return context I need to have a json version of this view, is there any way? -
mozilla-django-oidc issue with Azure AD B2C
I am trying to configure the "mozilla-django-oidc" package in Django. To authenticate I use Azure Active Directory B2C policy, so this is my federation server. When I click in the login button I got this URL which looks wrong to me, I will split it, just for convenience: https://TENANTID.b2clogin.com/TENANTID.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1_TENANTID_signin?response_type=code&scope=openid+email&client_id=XXXXXXXXXXXXXXX&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Foidc%2Fcallback%2F&state=pt8aYXicnYRSQkkB8kwHSv4hQwt9Xzre&nonce=UfLfk6QovA2inpfo9W7zS2MZHLpO1tkJ and the URL I need has this format: https://TENANTID.b2clogin.com/TENANTID.onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1_TENANTID_SIGNIN&client_id=XXXXXXXXXXXXX&nonce=defaultNonce&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Foidc%2Fcallback%2F&scope=openid&response_type=id_token&prompt=login In the home page I have this code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home page</title> </head> <body> <h3> Welcome to home page </h3> {% if user.is_authenticated %} <p>Current user: {{ user.email }}</p> <form action="{% url 'oidc_logout' %}" method="post"> <input type="submit" value="logout"> </form> {% else %} <a href="{% url 'oidc_authentication_init' %}">Login</a> {% endif %} </body> my code in the settings.py OIDC_RP_SIGN_ALGO = "RS256" OIDC_RP_CLIENT_ID = "xxxxxxxxxxxxxx" #fake client id just for this post # OIDC_RP_CLIENT_SECRET = os.environ['OIDC_RP_CLIENT_SECRET'] OIDC_OP_AUTHORIZATION_ENDPOINT = "https://TENANTID.b2clogin.com/TENANTID.onmicrosoft.com/oauth2/v2.0/authorize? p=b2c_1_TENANTID_signin" OIDC_OP_TOKEN_ENDPOINT = "https://TENANTID.b2clogin.com/TENANTID.onmicrosoft.com/oauth2/v2.0/token? p=b2c_1_TENANTID_signin" # OIDC_OP_USER_ENDPOINT = "<URL of the OIDC OP userinfo endpoint>" LOGIN_REDIRECT_URL = "http://localhost:8000/oidc/callback/" LOGOUT_REDIRECT_URL = "http://localhost:8000/welcome/ Note: I don't know what to put in this variable "OIDC_RP_CLIENT_SECRET" and also "OIDC_OP_USER_ENDPOINT" Any help please to get the right URL in this configuration? Thanks -
QuerySet to get top x of something - Django
first time here, so please be nice (? I want to be able to show a Top X of "alojamientos" in my website. #models.py class post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) text = models.TextField() class comment(models.Model): post = models.ForeignKey("appname.author", on_delete=models.CASCADE) author = models.ForeignKey("auth.User", on_delete=models.CASCADE) text = models.TextField() #views.py def index(request): top_comm = #I know it has to be Django aggregation, but I can't make it. return render(request, 'home/index.html', {"top_comm" : top_comm}) #index.html {% for row in top_comm %} {{row.author|linebreaksbr}} {{row.text|linebreaksbr}} {% endfor %} -
Add all the rows in a column and display it at the end of the file
I am trying to add all the rows in the column and display the output in a single row. Here is my source code: csvio = StringIO() header = ['Name','Unit1','Unit2','Marks'] writer = csv.writer(csvio) writer.writerow(header) for ut in uts: data = marks_helper() tot = 0 row = [] if data['a'] > 0.01 or data['b'] > .01 or data['a'] > .01: row.append(ut.name) row.append(round(data['a'],1)) row.append(round(data['abd'], 1)) tot = Decimal(data['abd']) - Decimal(data['a']) row.append("{}".format('%.2f' % tot)) if len(row) >= 1: writer.writerow(row) local = open( 'filename' , 'w') local.write(csvio.getvalue()) local.close() csvio.seek(0) breakdown = csvio.getvalue() I am trying to get the sum of all the rows in Marks column and display that in a new row. I have tried this: for x in tot: x += int(row[3]) row.append(x) but I get this error: 'Decimal' object is not iterable -
In Django, Save new record and updated existing in two separate models when user clicks one of two cards
TL;DR Question: How do I have a user's button click create a new record in one model and update an existing record in a second model? Disclaimer: no idea what I'm doing, limited knowledge of Python/Django/web development in general. I'm just messing around trying to learn something new during quarantine. I know Django is a weird place to start but I like a challenge. Any suggestions on tutorials/examples would be helpful too. This post is long enough, but if I forgot anything, this is just for fun so I have no problem sharing more. Objective: I'm trying to create a page where the user can choose between two "ideas". I then track these choices with the goal of ranking them based on the aggregation of these "pairwise" choices. The page needs to record the choice, then calculate a new "score", then update the "ideas" table with the current score. Current status: I was doing pretty well following some tutorials and googling. I have two models built, one to just hold the ideas and one that's basically just a log of the results (with some other logic that I'm not sure is working yet). I have the page populating two ideas … -
Is this possible? Using signals to set a global variable
I have made this function that runs every time a user logs in. I want to get the branch from 'user' but every time the session is set it's only available to the function even after setting it to BRANCH_ID in the settings file. any help? plus I don't want to do anything in view function with the request as it's not accessible from models def perform_some_action_on_login(sender, request, user, **kwargs): """ A signal receiver which performs some actions for the user logging in. """ request.session[settings.BRANCH_ID] = user.profile.branch_id branch = request.session.get(settings.BRANCH_ID) print(branch) user_logged_in.connect(perform_some_action_on_login) -
Django2.2 SQL Server How to store Checkbox input to Database
I have 2 checkboxes and I can check them in HTML but apparently I can't send them to my database, only the id increases but not one checked checkbox information is send to database. My model: class Qskontrolle(models.Model): qsid = models.AutoField(db_column='QsID', primary_key=True) mhd = models.BooleanField(db_column='MHD', blank=True, null=True) etiketten = models.BooleanField(db_column='Etiketten', blank=True, null=True) verpackungseinheiten = models.BooleanField(db_column='Verpackungseinheiten', blank=True, null=True) class Meta: managed = False db_table = 'qskontrolle' My view: def qskontrolle_view(request): qskontrolle = QskontrolleForm() if request.method == 'POST': qskontrolle = QskontrolleForm(request.POST) if qskontrolle.is_valid(): qskontrolle.save() context = { 'object': qskontrolle } return render(request, "pages/qswareneingang.html", context) My form: class QskontrolleForm(ModelForm): class Meta: model = Qskontrolle fields = '__all__' My HTML: <form action="" method="post"> {% csrf_token %} <div class="card-group"> <div class="col-md-4"> <div class="card"> <div class="card-header"> <h5 class="card-category">Wareneingangn QS-Prüfung</h5> <h4 class="card-title"> Kontroll-Check</h4> </div> <div class="card-body"> <div class="table-full-width"> <table class="table"> <tr> <td> <div class="form-check"> <label class="form-check-label"> <input type="checkbox" class="form-check-input" name="mhd"> <span class="form-check-sign"></span> </label> </div> </td> <td class="text-left">MHD </td> <td class="td-actions text-right"> </td> </tr> <tr> <td> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" name="etiketten"> <span class="form-check-sign"></span> </label> </div> </td> <td class="text-left">Etiketten </td> <td class="td-actions text-right"> </td> </tr> </form> What can I do to successfully transmit the checked or unchecked checkboxes to my database, after the user clicked on … -
Django database not working properly when deployed to Heroku
I've been having issues when creating a new Django website and deploying to Heroku. I have followed the tutorials almost exactly for how to create a portfolio website using Sql databases on realpython.com, and followed the Heroku Deployment tutorial on the mozilla developer website. The trouble seems to be with the migration of the database for my blog entries and projects from SQLLite to the Heroku compatible Postgres database. I have verified that the Heroku database exists using the Heroku Postgres add-on, my database exists in data.heroku.com, and my DATABASE_URL environmental variable is setup in Heroku. I am quite baffled as the Heroku logs do not seem to have any error messages or anything, the database entries just appear blank. When I runserver locally the website appears as I'd expect. Django Website Tutorial: https://realpython.com/get-started-with-django-1/ Heroku Deployment: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment Website Code is in GitHub: https://github.com/kevinjweiss/website The sample website is also at kevinjweiss.com Any ideas would be appreciated. I got this far and am about to give up - have spent multiple days trying to sort out this issue and have running into a brick wall. -
My form is showing multiple times on template
I want two different forms to be in the same template but the first form is showing twice instead of the second one, besides, i don't know if the Password no set advice will dissapear doing this, some help please? template <div class="tab-pane container p-0 active" id="home1"> <form method="POST" action="#" id="datosForm" > {% csrf_token %} <p>Por favor, no dejes ningún campo en blanco. {{ form.as_ul }} <button class="btn btn-primary py-1 px-2" type="submit" name="datosForm"> Save </button> </p> </form> </div> <div class="tab-pane container p-0 fade" id="home2"> <form method="POST" action="#" id="contraForm"> {% csrf_token %} <p>Por favor, llena los siguientes campos para cambiar tu contraseña. {{form.as_ul }} <button class="btn btn-primary py-1 px-2" type="submit" name="contraForm" > Save </button> </p> </form> </div> views.py def profileedit_view(request): form= PerfilEditadoForm(request.POST or None) if request.method== 'POST'and 'datosform' in request.POST: form.instance = request.user if form.is_valid(): form.save() return redirect('profileedit') else: form= PerfilEditadoForm(instance=request.user) args= {'form': form} return render(request, 'profileedit.html', args) context = { 'form': form } return render(request, "profileedit.html", context) def change_password_view(request): if request.method == 'POST' and 'contraform' in request.POST: form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Contraseña cambiada con éxito') return redirect('profileedit') else: messages.error(request, 'Ha ocurrido un error.') else: form = PasswordChangeForm(request.user) context = { … -
Django Choice Form add selected options
Hi all its my code if i choice in select list django work but i want after submit choices not be change. After submit first choices again seeing. My Form class PostSorguForm(forms.Form): HIKAYE_CHOICES=(('1','En Son Çıkanlar'),('2','En Çok Okunanlar')) sorgu_form = forms.ChoiceField(choices=HIKAYE_CHOICES,required=False) My view class ArticleListView(FormMixin,ListView): context_object_name = 'articles' template_name = 'includes/article/article-list.html' paginate_by = 15 form_class= PostSorguForm def get_queryset(self): queryset = Article.objects.all() if self.request.GET.get("sorgu_form"): selection = self.request.GET.get("sorgu_form") if selection == "2": queryset = Article.objects.all().order_by('-hit_count_generic__hits') else: queryset=Article.objects.filter(published=True).order_by('created_date').reverse() return queryset my template <form method="GET" action=""> <div class="form-group"> <select class="form-control" name="sorgu_form" id="id_sorgu_form" onchange="this.form.submit()"> {% for x,y in form.fields.sorgu_form.choices %} <option value="{{x}}">{{y}}</option> {% endfor %} </select> </div> </form> i want after query option selected -
Django: Best practices for using Model data in clientside javascript
I'm new to working with django and I am trying to send information to my clientside javascript. I have a list of FooBarModels that I want to use with my clientside Javascript. Currently, I'm using the django template to generate an array of dictionaries that holds the information I'll use with the Javascript. This feels like a hacky solution, is there a better way to achieve this? models.py class FooBarModel(models.Model): bar = models.ForeignKey(Bar, on_delete=models.CASCADE) @property def desc(self): # logic here @property def display_name(self): # logic here template.html <script> var $fb_list = [ {% for fb in foobar_list %} { "name": {{fb.display_name}}, "desc": {{fb.display_name}} }, {% endfor %} // a bunch of code that uses the $fb_list ] </script> What's the best practice for handling this type of situation? Should I be sending a package of JSON to the clientside and parsing it? -
Django : How do I pass an object id to a class based view from my template?
So, I started learning Django and HTML a few days ago and I'm kinda stuck. In my template, I print out multiple reviews for a Professor and I wish to add an edit feature for the reviews. My question is, how do I pass the review's 'pk' to ReviewUpdateView so that I can edit the correct review? Right now it looks like this and is probably laughably incorrect. <p>{{ review.body }}</p> {% if review.author == user %} <div> <a href="{% url 'update-review' pk2=review.pk %}" class="btn btn-secondary btn-sm">Edit</a> <a href="#" class="btn btn-danger btn-sm">Delete</a> </div> {% endif %} And this is how urls.py looks path('profs/<int:pk>/update/<int:pk2>/', ReviewUpdateForm.as_view(), name='update-review'), views.py :- class ReviewUpdateForm(UpdateView): form_class = ReviewForm def get_object(self): return Prof_review.objects.filter(pk=self.kwargs['pk2']).first() def form_valid(self, form): form.instance.author = self.request.user form.instance.professor = Professor.objects.filter(pk=self.kwargs['pk']).first() return super().form_valid(form) The form.instance.professor = Professor.objects.filter(pk=self.kwargs['pk']).first() is just to assign the professor this review is for. Any and all help will be appreciated. Thank you so much :) -
IntegrityError at / NOT NULL constraint failed: todolist_todolist.ischecked
i wonder what is causing this error, deleted migration folder then again performed makemigrations todolist and migrate . Kept null=True , all these efforts in vain models.py class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name = ("Category") verbose_name_plural = ("Categories") def __str__(self): return self.name class ToDoList(models.Model): title = models.CharField(max_length=200) content = models.CharField(max_length=500) created_on = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) due_date = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) category = models.ForeignKey(Category,on_delete=models.DO_NOTHING,default="general",null=True, blank=True) //kept blank and null field true class Meta: ordering = ["-created_on"] def __str__(self): return self.title views.py def index(request): ToDos = ToDoList.objects.all() catogories = Category.objects.all() if request.method == 'POST': if "taskAdd" in request.POST: title = request.POST["description"] category = request.POST["category_select"] date = str(request.POST["date"]) content = title + "--" + date + "--" + category ToDo = ToDoList( title = title, content = content, due_date = date, category = Category.objects.get(name=category), ) ToDo.save() return redirect("/") if "taskDelete" in request.POST: checkboxlist = request.POST["checkedbox"] for todo_id in checkboxlist: todo = ToDoList.objects.get(id=int(todo_id)) todo.delete() return render(request,"index.html",{"ToDos" : ToDos,"catogories" : catogories}) 0001_initaly.py //migration code migrations.CreateModel( name='ToDoList', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('content', models.CharField(max_length=500)), ('created_on', models.DateField(default='2020-03-29')), ('due_date', models.DateField(default='2020-03-29')), ('category', models.ForeignKey(blank=True, default='general', null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='todolist.Category')), ], options={ 'ordering': ['-created_on'], }, ), error pic admin/todolist pic //which doesn't contain ischecked field thanks in advance -
TypeError: 'class Meta' got invalid attribute(s). python(django) how fix this error?
i have this error --> raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) TypeError: 'class Meta' got invalid attribute(s): models i want create page where people can register but i have this error. how fix? i search google but couldn't find a reason. what's the problem? forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.contrib.auth import password_validation from django.db import models class SignUp(models.Model): class Meta: models=User models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is … -
Video conversion flow for HLS (m3u8) with Django and CloudFront
I was trying to find out how to do something like HLS to prevent BEGINNERS from hacking my content, and I think I got it a little after researching all night. Currently, I know I have to do the following: install ffmpeg convert the video after upload (I think it will be this way) send the files, and offer the link to the .m3u8 file (which will be together with the .ts files) The question now is: I don't know yet how to set the cloudfront I don't know if I will need to use signed urls / cookies I don't know how to create the video conversion stream (I must use ffmpeg to convert and create the files, and then use the aws Python SDK to upload to AWS, and then change the video field, or even even delete the original video after upload, maybe in the save method?) -
Error during template rendering - Required parameter name not set - bootstrap code
I am a new developer that is stuck on this problem. The issue seems to be with the bootstrap code that I copied from their site, which is confusing. My site was working fine until I deployed it to Heroku. When I add a new post to my site I am presented with the following error: Image of Error Here is views.py code: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) If you need anything more information to assist me please let me know. -
My application runs fine through Django server, but when I connect it to Apache it complains it can't load MySql
I'm trying to configure my Apache 2.4 instance on my mac High Sierra machine to connect to my Django application. I have set up this configuration ... <VirtualHost *:80> ServerName maps.example.com # Next, add the following directory block <Directory /Library/WebServer/Documents/maps/maps> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess maps python-home=/Library/WebServer/Documents/maps/venv python-path=/Library/WebServer/Documents/maps WSGIProcessGroup maps WSGIScriptAlias / /Library/WebServer/Documents/maps/maps/wsgi.py </VirtualHost> My requirements.txt is as follows ... (venv) localhost:web davea$ cat requirements.txt asgiref==3.2.3 attrs==19.3.0 Babel==2.8.0 click==7.1.1 click-plugins==1.1.1 cligj==0.5.0 Django==2.0 django-address==0.2.1 django-extensions==2.2.8 django-mysql==3.3.0 django-phonenumber-field==4.0.0 djangorestframework==3.11.0 Fiona==1.8.13.post1 geographiclib==1.50 geopandas==0.7.0 geopy==1.21.0 gunicorn==20.0.4 munch==2.5.0 mysqlclient==1.4.6 numpy==1.18.1 pandas==1.0.1 phonenumbers==8.11.2 pycountry==19.8.18 pyproj==2.5.0 python-dateutil==2.8.1 pytz==2019.3 PyYAML==5.3 ruamel.yaml==0.16.6 ruamel.yaml.clib==0.2.0 Shapely==1.7.0 six==1.14.0 sqlparse==0.3.0 However, when I restart Apache and visit my URL through Apache, the application dies complaining about not being able to load MySql. In the Apache errors logs, I see this ("django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.") ... [Sun Mar 29 13:27:38.906093 2020] [wsgi:error] [pid 60345] Traceback (most recent call last): [Sun Mar 29 13:27:38.906261 2020] [wsgi:error] [pid 60345] File "/Library/WebServer/Documents/maps/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> [Sun Mar 29 13:27:38.906277 2020] [wsgi:error] [pid 60345] import MySQLdb as Database [Sun Mar 29 13:27:38.906291 2020] [wsgi:error] [pid 60345] File "/Library/WebServer/Documents/maps/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> [Sun Mar 29 13:27:38.906302 2020] [wsgi:error] [pid 60345] from . import … -
Django Models: Selecting information in the most recent record on join
I have a Python script that visits a real estate website and collects information about the properties that are listed there. It runs at a set interval and adds new information to the database in the form of Django model instances. I would like to create a view (virtual table) that always displays the most recent information, as shown below. This is the view that I want to create: +---------+----------+------------------------+------------------------+--------------------------+---------------------+ | name | price | property_category_name | num_checked_properties | num_available_properties | datetime_last_check | +---------+----------+------------------------+------------------------+--------------------------+---------------------+ | Flat 1 | 123000 | Apartments | 24 | 10 | 2020-03-29T18:45:35 | | House 5 | 456000 | Houses | 30 | 15 | 2020-03-28T14:02:00 | | ... | ... | ... | ... | ... | ... | +---------+----------+------------------------+------------------------+--------------------------+---------------------+ The view combines information from four different models. name comes from the Property model price comes from PropertyStatusCheck (most recent price, found using the datetime from the related PropertyCategoryCheck) property_category_name comes from PropertyCategory num_checked_properties, num_available_properties, datetime_last_check come from PropertyStatusCheckGroup (values from the most recent entry) Below are the simplified models from my models.py file: # A single property on the website class Property(models.Model): name = models.CharField() url = models.CharField() # What a property looked … -
tinymce shared images but did not activate the raw code
hello I would like to know how to share code in its site as an example I know that | safe allows to write code but on the other hand the code is not visible but converted into action but personally I want that images can be shared but no code the code is written like this site in a black square -
Can I set max task or max memory limits for gevent pools?
We are using celery to run asynchronous tasks for a Django site. The current worker setup is -pool=prefetch with --max-memory-per-child 5120000. The max memory threshold is important, because our tasks are leaking memory. Now, we found in a recent analysis that our tasks are I/O bound and would work much better with a thread based execution pool like gevent, e.g. we can get much higher throughput. However, neither the max-memory-per-child parameter nor the max-tasks-per-child setting are supported for thread based execution pools. The documentation says (source): pool support: prefork Is they any other celery configuration that could help me limit the max worker memory and/or force a worker restart after x task executions or is our only option to restart the worker with cron? -
Django Sessions: Correct way to get logged in user data from client?
I have my API set up using SessionAuthentication. Once a user logs in, I redirect them to their profile page in React. Once they are redirected to their profile page, I want to make a REST call to retrieve their profile data and insert it in the proper location on the page. I see a couple ways I can do this: When a user logs in, put their User ID into the Response object (DRF) and then store that in the client somewhere (Redux store, session storage, or local storage). Then when they are redirected to the login page, make a REST call to /users/. With Django sessions the logged in user is automatically tied to each request. So do I even need to follow Rest here? I can make a call to /users, and if the user is authenticated, return their data. I would appreciate any help with this. Thank you. -
Connecting to mongo atlas gives me pymongo.errors.ServerSelectionTimeoutError: localhost:27017
I am trying to connect to mongoDB Atlas from my Django application using models. I have changed the database configuration in settings as below DATABASES = { 'default': { 'ENGINE': "djongo", 'NAME': "test", 'HOST': "mongodb+srv://admin:<mypassword>@cluster0-9jtq2.mongodb.net/test?retryWrites=true&w=majority", 'USER': "admin", 'PASSWORD': "<mypassword>", } } Now when i execute migrate # python3.7 manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/migrate.py", line 87, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/usr/local/lib/python3.7/dist-packages/django/db/backends/base/introspection.py", line 48, in table_names return get_names(cursor) File "/usr/local/lib/python3.7/dist-packages/django/db/backends/base/introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "/usr/local/lib/python3.7/dist-packages/djongo/introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "/usr/local/lib/python3.7/dist-packages/pymongo/database.py", line 856, in list_collection_names …