Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
no module named 'multiselectfield' (docker / Django)
I am trying to run a database on my server using docker. I am using django and postgreSQL. After adding the multiselectfield library to my repo it keeps failing to run the container with following error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'multiselectfield' Even though i pip installed the library on all python versions i have installed (requirement already satisfied....) It is included in the requirements.txt and is installed as well when building the container. -
Filter Embedded Documents that match a condition in MongoEngine, Django, GraphQl
Document Structure Data class Data(EmbeddedDocument): v = FloatField() q = StringField() co2 = FloatField() price = FloatField() ts = DateTimeField() Meters Data class MetersData(DynamicDocument): meta = {'collection': 'dk_heating'} _id = ObjectIdField() ident = StringField() meteringPointId = StringField() customer = StringField() cvr = StringField() type = StringField() unit = StringField() address = StringField() period = EmbeddedDocumentField(Period) hourly_data = ListField(EmbeddedDocumentField(Data), db_field='data') daily_data = ListField(EmbeddedDocumentField(Data)) monthly_data = ListField(EmbeddedDocumentField(Data)) # monthly_data = EmbeddedDocumentListField(Data) yearly_data = ListField(EmbeddedDocumentField(Data)) I am using this Query. Query MetersData.objects.filter(address=address, customer=customer).fields( monthly_data={"$elemMatch": {"q": "E"}}, address=1, customer=1, cvr=1, ident=1, meteringPointId=1, type=1, unit=1, period=1) It returns me only the first matching element. I have read the documentation and it reads that $elemMatch is supposed to return only the first matching result. But in my case, I need all the matching results. Result of the Query I have searched everywhere but I am unable to find a solution. -
How to test foreignkeys to self in django
Django allows a foreign key to "self" as in class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, verbose_name="User", related_name="user_profiles", ) entity = models.ForeignKey( Entity, on_delete=models.CASCADE, verbose_name="Entity", related_name="entity_profiles", ) email = models.EmailField( max_length=255, help_text=_("Automatically generated to use entity email domain"), ) supervisor0 = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="Supervisor0", related_name="supervisor0_profiles", help_text=_("Employees only."), ) supervisor1 = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="Supervisor1", related_name="supervisor1_profiles", help_text=_( "Employees only. Only the executive head is his/her own \ supervisor." ), ) supervisor2 = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="Supervisor2", related_name="supervisor2_profiles", help_text=_( "Employees only. Only the executive head is his/her own \ supervisor." ), ) supervisor3 = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="Supervisor3", related_name="supervisor3_profiles", help_text=_( "Employees only. Only the executive head is his/her own \ supervisor." ), ) The supervisor0 is the user and being supervisor0 identifies him/her as an employee. The other supervisors also have to be already in the database for them to be able to be referenced. The help_texts explain the situation of the executive head. The question is how to test these relationships to "self". I have no problem with relationships to other models. Using pytest, I record only supervisor0 in the ProfileFactory for the moment. class ProfileFactory(factory.django.DjangoModelFactory): class Meta: model = Profile user … -
How i can to prevent to create multiple instance while multi request in django?
Hi everyone i have project include about payment function between user and user. But i have a problem when many user buy a product.the many payment object will created more than product avaliable. How i can to solve this ? products_avaliable = Product.objects.filter(on_sell=true) for product in products_avaliable: payment = Payment() payment.buyer = .... payment.seller = product.owner payment.save() product.on_sell = False product.save() when add deley products_avaliable = Product.objects.filter(on_sell=true) for product in products_avaliable: payment = Payment() payment.buyer = .... payment.seller = product.owner payment.save() time.sleep(10) # simulate to slow server or many request product.on_sell = False product.save() when i try to time.delay before payment create (simulate when server to slow or may request by user) the payment will create many object -
Django could not detect newly added database after adding router
I have three database out of which one is set to default. I have already created router for ringi database and it working perfectly fine. Now i would like to add one more database and after creating the new router for database named cms, its not working. So my project name is wshp and one of router for ringi database, i placed it in same folder as settings.py. I created another app called mypage and created router for cms and name of router is cmsrouter. settings.py DATABASE_ROUTERS = ['wshp.router.myrouter','app_mypage.cms_router.cmsrouter'] DATABASE_APPS_MAPPING = { 'ringi':'ringi_db', 'cms':'cms_db' } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mypage', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, 'ringi_db':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ringi', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, 'cms_db':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'cms', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } cms_router.py class cmsrouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'cms': return 'cms_db' else: return None def db_for_write(self, model, **hints): if model._meta.app_label == 'cms': return 'cms_db' else: return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'cms' or \ obj2._meta.app_label == 'cms': return True else: return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'cms': … -
form.errors won't display upon invalid form submission
I'm having difficulty with displaying custom defined errors on a page when a user submits an invalid form submission. I set novalidate on the form element with the intent of disabling a browser's default form validation messages. At the same time the error messages that are defined on QuestionForm are not displaying on the page. It's not clear to me why the form error messages aren't showing? Is setting novalidate causing this to occur? class Page(TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data() context['search_form'] = SearchForm() return context class AskQuestionPage(Page): template_name = "posts/ask.html" extra_context = { 'title': "Ask a public question" } def attach_question_tags(self, tags): question_tags = [] for name in tags: try: tag = Tag.objects.get(name=name) except Tag.DoesNotExist: tag = Tag.objects.create(name=name) finally: question_tags.append(tag) return question_tags def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = QuestionForm return context def post(self, request): context = self.get_context_data() form = context['form'](request.POST) if form.is_valid(): tags = self.attach_question_tags( [tag.lower() for tag in form.cleaned_data.pop("tags")] ) try: question = form.save(commit=False) question.profile = request.user.profile question.save() except IntegrityError: form.add_error(None, "This post is already posted") context['form'] = form else: question.tags.add(*tags) form.save_m2m() return SeeOtherHTTPRedirect( reverse("posts:question", kwargs={ "question_id": question.id }) ) return self.render_to_response(context) <div class="question_posting_form"> <h2>{{ title }}</h2> {% if form.non_field_errors %} <ul class="non_field_errors"> {% for … -
Login page is not appearing while it directly catch register form
login.html {% extends 'main.html' %} main.html extended {% block content %} block content added {% if page == 'Login' %} if url is login will open login section {% csrf_token %} Sign Up {% else %} {% csrf_token %} {% for field in form %} {{field.label}} used for auto filling of fields {{field}} fields are fetched directly from model.py {% endfor %} Already signed up yet? Login {% endif %} {% endblock content %} -
Is there a way to override ClockedSchedule model from Django Celery Beat?
I want to add unique=True attribute to clocked_time field of ClockedSchedule model. Current Scenario is, when multiple threads try to get_or_create schedule, it creates more than one of similar records given schedule is not found, and when next time some thread tries to get the schedule it throws MultipleObjectsReturned exception. So, I was thinking adding a DB constraint might work here. Attaching the code for reference: schedule, created = ClockedSchedule.objects.get_or_create(**clocked_options) return schedule And the model looks like: class ClockedSchedule(models.Model): """clocked schedule.""" clocked_time = models.DateTimeField( verbose_name=_('Clock Time'), help_text=_('Run the task at clocked time'), ) class Meta: """Table information.""" verbose_name = _('clocked') verbose_name_plural = _('clocked') ordering = ['clocked_time'] def __str__(self): return '{}'.format(self.clocked_time) Let me know your thoughts, thanks! -
Ajax get request stays on readystate 1, but when i log the response text in the console it displays it without a problem
I cant display the result in my html because the request stays in state 1 and the response text displays undefined. When I access the url it displays the value I want to show on my html. Why is this happening? I'm using django on server side btw. Kinda new to ajax but I haven't been able to find an answer to this problem on other already solved questions. Code that executes the request: const getHighScore = (gameID, levelID) => { let ajaxPrueba = $.ajax({ url: `/get-data/${gameID}/${levelID}`, type: 'get', success: function(data) { return data; }, failure: function(data) { console.log('Got an error dude'); } }); return ajaxPrueba; } The parameters i pass on are 1 for gameID and 1 for levelID The url i'm talking about Also this is what the console returns: ajaxPrueba = $.ajax({ url: `/get-data/1/1`, type: 'get', success: function(data) { return data;… Object { readyState: 1, getResponseHeader: getResponseHeader(e), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(e, t), overrideMimeType: overrideMimeType(e), statusCode: statusCode(e), abort: abort(e), state: state(), always: always(), catch: catch(e) , … } abort: function abort(e) always: function always() catch: function catch(e) done: function add() fail: function add() getAllResponseHeaders: function getAllResponseHeaders() getResponseHeader: function getResponseHeader(e) overrideMimeType: function overrideMimeType(e) pipe: function pipe() progress: function … -
Deserializing json to a python object without actually save the object in DB
I use Django and the model classes to access data from DB. I would like to add cache layer on top of DB. For example, let's say I have a User model and UserSerializer (inherited from ModelSerializer). When storing an User object in cache, I need to serialize the object to json import json serializer = UserSerializer(obj) serialized_data = json.dumps(serializer.data) However, when I retrieve this json from cache, I had trouble to convert it back to User object data = json.loads(serialized_data) deserializer = UserSerializer(data=data) user_obj = deserializer.save() # this return an User object but intenally it will create a new record in DB Any better ideas that I can use the serializer that django provided to deserialize json to object without actually creating the record in DB? -
Hyperlinks in Django Quill Editor are not displaying as expected
Problem I added the Quill Editor to my Django admin. When I input hyperlinks in the QuillEditor such as "www.example.com", instead of creating the hyperlink exactly as I type it, the URL will appear on the template page as "localhost:8000/plants/www.example.com". Directing me to a broken page instead of www.example.com Context I've read through the full quill documentation but I don't see a way to make sure hyperlinks added in the QuillEditor display without the project domain being prepended to the front of the hyperlink url. Heres how I input the URL 'www.example.com' in the django admin: Here is how the URL appears on the actual template page (you can see the url in the bottom left when I hover over it: Maybe I need to edit something in the urls.py? plants > urls.py urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('accounts/', include('django.contrib.auth.urls')), path('', include('pages.urls')), path('plants/', include('plants.urls')), ] -
Wrap python decorator with another decorator
I have a common decorator call throughout my Django codebase: @override_settings( CACHES={ **settings.CACHES, "default": generate_cache("default", dummy=False), "throttling": generate_cache("throttling", dummy=False), } ) def test_something(): ... The decorator code is too verbose. I'd love to wrap this code into a new decorator called @use_real_cache so the test function looks much cleaner: @use_real_cache def test_something(): ... How can I wrap a decorator with another decorator? -
Using fonts in django HTML email templates
I have a html template for a password reset email that I am trying to set up instead of the default django email. The code is as follows: <!DOCTYPE html> <html> <head> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300&display=swap" rel="stylesheet" /> <style> body { font-family: "Inter", sans-serif; font-size: 20px; color: #434343; margin: 0; } .main-container { max-width: 60%; } .centered-contents { display: flex; justify-content: center; } .pswd-button { background: #677db6; border-radius: 25px; color: #ffffff; cursor: pointer; text-decoration: none; padding: 15px; padding-top: 10px; padding-bottom: 10px; } .top-bar { width: 100%; background-color: #d9d9d9; display: flex; align-items: center; } .top-bar-title { color: #677db6; margin: 20px; } </style> </head> <body> <div class="top-bar"> <p class="top-bar-title">Nombre de Web</p> </div> <div class="centered-contents"> <div class="main-container"> <p style="font-size: 24px"> Hola <span style="color: #677db6">nombre</name></span>! </p> <p> Está recibiendo este correo porque ha solicitado un cambio de contraseña en <span style="color: #677db6">web</span>. Para continuar, por favor utilice el botón que se muestra a continuación: </p> <div class="centered-contents"> <a class="pswd-button" href="#"> Restablecer Contraseña </a> </div> <p> Le recordamos su nombre de usuario: <span style="color: #677db6">usuario</span> </p> <p> Si no ha solicitado ningún cambio de contraseña, no se preocupe. Puede ignorar este correo. </p> <p>Atentamente,</p> <p>El equipo técnico de <span style="color: #677db6">Web</span></p> </div> </div> </body> </html> And, rendered … -
generated json to csv to django model
Is there any way to do what I'm trying to do - generate json from api url request, transform it to csv, store in Django model? No idea how to make this work views.py def view(request): if request.method == 'GET': data1 = request.GET.get("data1") data2 = request.GET.get('data2') url = f'https://api.com/{data1}?d={data2}&format=json' response = requests.get(url=url) df = pd.json_normalize(response.json()) file = df.to_csv('data.csv') csv_file = File.objects.create(csv_file=file) csv_file.save() return render(request, 'template.html') models.py class File(models.Model): file = models.FileField() -
Want a unicode character in django crispy strictbutton
I'm trying to get a chevron to be the value in a crispy strictbutton. It should look like this: https://icons.getbootstrap.com/icons/chevron-down/ But, all I get is code in a little box: unicode in the box I've tried this: def __unicode__(self, this_char): return u"%s" % this_char StrictButton(self.__unicode__('\uF282'), css_class="btn btn-outline-secondary btn-sm", id="button-id-right") and this: StrictButton('\uF282', css_class="btn btn-outline-secondary btn-sm", id="button-id-right") and get the same result. I've tried embedding the html string hoping the browser would catch it - didn't work. Thanks -
Is there an efficient way to get the Django model of a modeladmin object from within an Admin action?
I have an action that is added to multiple Django model admins. Part of that action relies on the modeladmin and queryset like so: def my_action(modeladmin, request, queryset): queryset_model_name = queryset.first().__class__.__name__ model_to_update = apps.get_model(app_label='main', model_name=queryset_model_name) # more code here that relies on both queryset_model_name and model_to_update Is there a way to refactor this? Possibly a way to get the model string itself directly from modeladmin instead? I did a search through the django doc page for ModelAdmin but came up short. Any assistance would be appreciated! Thank you in advance. -
Is there a way to convert from ISO Date format to an Month, DD, YYYY at local time in Python
I am trying to convert my last_updated field from ISO Date format 2022-06-05T14:38:59.927753-07:00 into June 5th, 2022 at 2:38pm My code is try: if timefield.school_id: school = SchoolBell.object.get(school_id=timefield.school_id) return '{}'.format(datetime.strftime(school.last_updated)) except School.DoesNotExist: return '' Is there a way to call it inside the table field last_updated into the word format -
Django python requests library send and receive array values through POST
I am sending a POST request (with indexed array value) in Django (Python 3+) like: def wordgrpocc_ajax(request): woccs= [] postVars= request.POST print('postVars= '+str(postVars)) # OUTPUT: postVars= <QueryDict: {'syear': ['0'], 'eyear': ['0'], 'word_id[]': ['629c48a694c367c0e07f1d3a', '629c481e94c367c0e07ee8bc', '629c48c694c367c0e07f2864']}> url = skpsettings.API_URL+"word/group/occurrence" headers = {'Content-type': 'application/json'} bresplist = requests.post(url= url, data=json.dumps(postVars), headers=headers) woccs= bresplist.text return HttpResponse(woccs, content_type="application/json") Output of the print in above def: postVars= <QueryDict: { 'syear': ['0'], 'eyear': ['0'], 'word_id[]': ['629c48a694c367c0e07f1d3a', '629c481e94c367c0e07ee8bc', '629c48c694c367c0e07f2864']}> When I catch the request (in skpsettings.API_URL+"word/group/occurrence"), the array value is corrupted. Only the last value of the array is received: @csrf_exempt def api_WordGroupYearOcc(request): wocclist= [{}] if request.method == "POST": postVars= json.loads(request.body) word_ids= postVars.get("word_id") #word_ids= request.POST.getlist('word_id', []) syear = int(postVars.get("syear", 0)) eyear = int(postVars.get("eyear", 0)) print('postVars= '+str(postVars)) # OUTPUT: postVars= {'syear': '0', 'eyear': '0', 'word_id[]': '629c48c694c367c0e07f2864'} Output of the print in above def: postVars= {'syear': '0', 'eyear': '0', 'word_id[]': '629c48c694c367c0e07f2864'} What am I doing wrong? Thanks in advance. -
Browser loads an empy css
css located in my_blog/my_blog/blog/static/blog/style.css manage.py in my_blog/my_blog head of html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'blog/style.css' %}"> <title>{% block title%} My blog {% endblock %}</title> </head> I'm using pycharm pro. Browser successfully load css file, but it's empty. Why this is happenning? -
How Django async view handle simultaneous requests
I test 2 views in Django 3.2: def sync_view(request): return HttpResponse("Hello, sync Django!") async def async_view(request): await asyncio.sleep(10) return HttpResponse("Hello, async Django!") start uvicorn as uvicorn myapp.asgi:application First request to async_view, right after to sync_view. My expectation that sync_view will response immediately, however it is handled only after 10 seconds. What is wrong? Why requests are not handled simultaneously? -
How to pass pk argument within class based view to queryset in Django
I have the following Django urls/views and Models: Models ORDER_COLUMN_CHOICES = Choices( ('0', 'id'), ('1', 'code'), ('2', 'code_type'), ('3', 'created'), ('4', 'updated'), ('5', 'valid'), ) class Identifier(TimeStampMixin, models.Model): code_type = models.CharField(max_length=10, null=True) code = models.CharField(max_length=12) account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) actflag = models.CharField(max_length=1, blank=True) valid = models.BooleanField(default=False) def __str__(self): return self.code class Meta: db_table = "portfolio_identifier" def query_identifier_by_args(**kwargs): draw = int(kwargs.get('draw', None)[0]) length = int(kwargs.get('length', None)[0]) start = int(kwargs.get('start', None)[0]) search_value = kwargs.get('search[value]', None)[0] order_column = kwargs.get('order[0][column]', None)[0] order = kwargs.get('order[0][dir]', None)[0] order_column = ORDER_COLUMN_CHOICES[order_column] # django orm '-' -> desc if order == 'desc': order_column = '-' + order_column queryset = Identifier.objects.all() total = queryset.count() if search_value: queryset = queryset.filter(Q(id__icontains=search_value) | Q(code__icontains=search_value) | Q(code_type__icontains=search_value) | Q(created__icontains=search_value) | Q(updated__icontains=search_value) | Q(valid__icontains=search_value)) count = queryset.count() queryset = queryset.order_by(order_column)[start:start + length] return { 'items': queryset, 'count': count, 'total': total, 'draw': draw } URLS from . import views from rest_framework.routers import DefaultRouter from apps.portfolio.views import IdentifierViewSet router = DefaultRouter() router.register(r'portfolio', IdentifierViewSet) urlpatterns = [ path('portfolios/', views.portfolios, name="portfolios"), path('portfolio/<str:pk>/', views.portfolio, name="portfolio"), path('api/', include(router.urls)), ] Views def portfolio(request, pk): portfolio = Account.objects.get(id=pk) identifiers = Identifier.objects.filter(account=pk) context = {"portfolio": portfolio, "identifiers": identifiers} return render(request, 'portfolio.html', context) class IdentifierViewSet(viewsets.ModelViewSet): queryset = Identifier.objects.all() serializer_class = IdentifierSerializer authentication_classes = … -
Django: Code only executing on watcher reload?
I'm working with Django and I have code that I'm attempting to execute on page load, but it isn't executing. All I've set it to do is print something and it only prints when Django's watcher sees a code change (and it's immediate on watcher reload, after that it won't print at all)... Here's my codebase: https://github.com/varlenthegray/wcadmin/blob/master/qb/views.py#L590 Here's the view: def update_db_from_changes(request): # Get all records that do not equal 12 for service interval all_non_standard_invoices = Invoice.objects.filter(~Q(service_interval=12)).select_related('job_site') print("I don't get it, this should work.") return HttpResponse("Did nothing!") Watcher results: System check identified no issues (0 silenced). June 09, 2022 - 16:01:06 Django version 4.0.5, using settings 'wcadmin.environment.production' Starting development server at http://127.0.0.1:3000/ Quit the server with CONTROL-C. I don't get it, this should work. Watching for file changes with StatReloader Page refresh results: Watching for file changes with StatReloader [09/Jun/2022 16:06:50] "GET /qb/update_changes/ HTTP/1.1" 200 12 Page results: Did nothing! Any thoughts on how to best approach debugging this issue? -
Access domain (and port) URL in settings.py file while in localhost development
How do you dynamically access the domain name URL in the settings.py file of Django? (ie "http://localhost:8000") I am trying to overwrite a package CDN while the internet is unavailable during development, and want to point to the local file in the static files directory. While os.path.join(BASE_DIR, "path/to/local.file") should work, it is context-dependent as to which app/url (ie "http://localhost:8000/app/static/css/bootstrap.min.css "), and not just the main domain with the static file location appended to the starting server with ./manage.py runserver 0:8000 (ie " http://localhost:8000/static/css/bootstrap.min.css"). Notes: Because this is in the settings.py, I can't load any apps or reverse because of the error *** django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I am not in a template, so I can't use the static url statically defining it won't allow for different port loadings when starting via ./manage.py runserver 0:8000 Basically in the settings.py file: # If in local dev if "RDS_DB_NAME" not in os.environ: # the setting for the package I am pointing to a local version BOOTSTRAP5 = { "css_url": { ### dynamically get domain here ### # "href": os.path.join(LOCAL_DIR, "static/css/bootstrap.min.css"), "href": "static/css/bootstrap.min.css", } -
Django model form won't save/validate
I am new to Django and I have a comments form on a listing page of a marketplace site I am working on. When trying to enter a comment they don't save. I assume the is_valid() is not returning True so the saving never occurs, but I don't see why it wouldn't be valid. I thought that function primarily checked all fields were filled with valid data. As I said I'm new to Django so any advice would be appreciated. The Else redirect is temporary until I get it working correctly. Views.py @login_required def comment(request, listing): listing = AuctionListings.objects.get(name=listing) form = NewCommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.listing = listing comment.save() return HttpResponseRedirect(reverse("listing", args=[listing.name])) else: return HttpResponseRedirect(reverse("listing", args=[listing.name])) models.py class Comments(models.Model): listing = models.ForeignKey(AuctionListings, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=255, validators=[MinLengthValidator(1)]) date = models.DateTimeField(auto_now_add=True) forms.py class NewCommentForm(forms.ModelForm): class Meta: model = Comments fields = [ 'comment' ] widgets = { 'comment': forms.Textarea(attrs={ 'placeholder': 'Enter your comment (255 char. max)', }) } -
Reliably accessing request.user in Django custom LoginView
I have a custom LoginView and I'd like to take the shopping cart of a LazyUser pre-login and consolidate it with the cart of the user after login: class LoginView(FormView): ... def form_valid(self, form): request_user = self.request.user user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password']) if user is not None: login(self.request, user) try: user.consolidate_carts(request_user) except Exception as e: print('error in consolidate_carts: ', e) return HttpResponseRedirect(self.success_url) else: return render(self.request, 'users/login.html') This seems to work some of the time, but it is unreliable - I believe that is because I am simply referencing self.request.user and it is a SimpleLazyObject. What would be the pythonic/optimal way to store the user pre-login?