Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000002523CE84E48>>": "Balance.user" must be a "User" instance
I'm working on the Wallet Balance ASPECT of my django website. I want a situation where as soon as new user registers on the website his wallet balance is set to '0', But my code is throwing the above error. Kindly assist. VIEW @unauthenticated_user def registration(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') group = Group.objects.get(name='customer') user.groups.add(group) Customer.objects.create( user=user, name=user.username, ) instance = Balance(user=request.user, balance=10) instance.save() messages.success(request, 'Account was created for ' + username) return redirect('loginuser') context = {'form': form} return render(request, 'account/registration.html', context) MODEL class Balance(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) balance = models.IntegerField() def __str__(self): return str(self.user) if self.user else '' TRACEBACK Traceback (most recent call last): File "C:\Users\ienovo\Domination\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\ienovo\Domination\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\ienovo\Domination\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ienovo\Domination\accounts\decorators.py", line 12, in wrapper_func return view_func(request, *args, **kwargs) File "C:\Users\ienovo\Domination\accounts\views.py", line 64, in registration instance = Balance(user=request.user, balance=10) File "C:\Users\ienovo\Domination\venv\lib\site-packages\django\db\models\base.py", line 482, in __init__ _setattr(self, field.name, rel_obj) File "C:\Users\ienovo\Domination\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 219, in __set__ self.field.remote_field.model._meta.object_name, Exception Type: ValueError at /registration/ Exception Value: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000002523CE84E48>>": … -
How to extract charts of xlsx to save on database using django
I want to know how can I extract the charts which exist in an excel file (xlsx) and save them on a database (as an image/pdf/excel chart). I am working with django and reading the other data on spreadsheet using openpyxl. I have found this question and answer but it works using win32 which clearly I can't work with on Linux cPanel. The excel file is received from a user and its certain cells are saved to database at the time of uploading. Any help is appreciated -
Django Rest Framework - React - Unable to login immediately after logout
This is very strange. I have a react front end and a django backend with djangorestframework and django-allauth for authentication. Everything works fine from Postman. But in the browser when I successfully sign in, successfully sign out, and then try to sign in again, I get a 401 unauthorized error. The correct user credentials are sent to the server just as the first successful time, yet a 401 error. However, after I refresh the browser then I am able to sign in normally again. I use jwt for authentication and I append the token to the authorization header before sign out. I even tried clearing out the authorization header after a successful sign out but to no avail. It is the same problem with my react native front end. I don't know if this is a react or a django problem. Please does anyone have any idea what the problem might be? Thanks. -
Django Import Export : How to append rows before import
I am trying to import this csv file in django model import export but the end results doesn't show any data and shows "skipped" in the preview -
django-rest-framework : one ManyToManyField connected to many Models
So the question is assume there are two models lets say dog and cat and one ManyToManyField. then when user click on a cat on frontend then that get appended in ManyToManyField and after that user click dog it get appended into ManyToManyField. Like that it will be a list of cats and dogs according user click sequence. -
Does GeoDjango have a way to bulk update a geom field based on latitudes / longitudes already present in the database?
I first tried a basic implementation through a simple for loop as below. It works but takes too long as there are 10k records. panoramas = Panorama.objects.all() for panorama in panoramas: panorama.geo_location = Point([panorama.longitude, panorama.latitude]) panorama.save() Based on Django's update method, I then tried something like this: geo_location = Panorama.objects.all().update(geo_location=fromstr(f'POINT({longitude} {latitude}', srid=4326)) This does not work though as I'm trying to get Django to pick out the lat/long for each record and update geo_location based on those two fields but django doesn't know what longitude or latitude is. Is there a way I could implement this using update()? -
render HTML with AJAX
I have an user favorite list and I want the user to use AJAX to navigate through it. For now my AJAX function returns a list of dictionaries of the products characteristics. This is my AJAX: $(".nav_button_2").on("click", function(event) { event.preventDefault(); var page = $(this).val(); var url = '/register/account/'; $.ajax({ url: url, type: "POST", data:{ 'page': page, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(resp) { $('#fav_list').html('') var resp = JSON.parse(resp); $.each(resp, function(i, val) { $('#fav_list').append('<h2>' + val.or_name + '</h2>') }); } }); }); This is $('#fav_list') html: div class='row d-flex justify-content-between'> <div class="card mb-3" style="width: 49%;"> <div class="row no-gutters"> <div class="col-md-2 my-auto"> <img class="mx-auto d-block" style="width:auto; height:auto; max-width:100px; max-height:100px; " src="{{ saved.original_product.picture }}"> </div> <div class="col-md-10"> <div class="card-body"> <h5 class="card-title"><a href="{% url 'finder:detail' saved.original_product.id %}" class="aaccount">{{ saved.original_product.real_name }}/ {{ saved.original_product.real_brand }}</a> </h5> <img src="/static/finder/img/nutriscore-{{ saved.original_product.nutrition_grade}}.svg" style="width:70px;"><br> </div> </div> </div> </div> <div class="card mb-3" style="width: 49%;"> <div class="row no-gutters"> <div class="col-md-2 my-auto"> <img class="mx-auto d-block " style="width:auto; height:auto; max-width:100px; max-height:100px; " src="{{ saved.sub_product.picture }}"> </div> <div class="col-md-9"> <div class="card-body"> <h5 class="card-title"><a href="{% url 'finder:detail' saved.sub_product.id %}" class="aaccount">{{ saved.sub_product.real_name}}/ {{ saved.sub_product.real_brand }}</a> </h5> <img src="/static/finder/img/nutriscore-{{ saved.sub_product.nutrition_grade}}.svg" style="width:70px;"><br> </div> </div> <div class="col-md-1 my-auto mx-auto"> <button type ='button' class=' btn substitut' value='{{ saved.id }}'>{% csrf_token %}<i … -
How do I extract a JSON payload string received on a subscribed topic of a Paho MQTT Javascript Client for consumption by django consumers?
Currently I have my own secure MQTT broker (Mosquitto) that I am connecting a Javascript Paho Client to in my django workflow. This client subscribes to a certain topic which my sensors on arduino are throwing some data. The subscribed client receives this incoming data message as a JSON payload string. My goal was to send this JSON string to the Paho JS client which in turn would send/expose it to my django consumers for specific information extraction and further processing. Right now I can console log that incoming data and surely the paho subscribed client is getting that information. I can't seem to figure out a way of sending the JSON message to django channels over the websocket. I understand that native Javascript websockets created using "vac socket = new WebSocket("ws://" + hostname ....." use functions like onmessage, onopen, onerror, onclose and they integrate perfectly with django channels. However, for the Paho websocket connection with the MQTT broker, the equivalent functions onMessageArrived, onConnected, onConnectionLost seem invisible to django. I know I am probably confusing some things here or doing something wrong. I need some help regarding this issue and please let me know if I should provide any more … -
Django. That IP address can't be assigned to
I am trying to deploy a Django app. I have a server with a public ip such as 194.61.xx.xxx but when I execute python3 manage.py runserver --noreload --nothreading 194.61.xx.xxx:8000 I get the error Error: That IP address can't be assigned to.. I have already set ALLOWED_HOSTS=["*"] and I can connect using ssh to my server with no problem. -
Onclick button does not call js function in django
I have a button that must call my js function, but nothing happens when i do (there is no get requests) My HTML: <button type="button" id="checker" id="button{{answer.id}}" onclick="mark_as_correct({{answer.id}});"> </button> My JS function: function mark_as_correct(qid) { var csrftoken = getCookie('csrftoken'); $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ url: 'url answerajaxcorrect', type: 'post', data: {id: qid}, success: function(data) { document.getElementById('correct' + qid).innerHTML = "Correct!" var button = document.getElementById('button' + qid) button.parentNode.removeChild(button) }, failure: function(data) { alert('error') } }) } I do include my js to template: {% load static %} <script type="text/javascript" src="{% static 'js/main.js' %}"></script> And there is how my view looks like: @login_required def correct_ajax(request): qid = int(request.POST.get("id")) answer = get_object_or_404(Answer, id=qid) if answer.author == request.user: answer.is_correct = True answer.save() return JsonResponse({ "is_correct": True, }) else: return JsonResponse({ "is_correct": False, }) I am new to js and django, so it is hard for me to understand the source of my problem, please help. -
Django select all checkbox doesn't work for Microsoft Edge
I want to select all rows in a table by checking the header checkbox in my CheckBoxColumn. So far I have tried the following code select all rows in django_tables2 , which works fine for most browsers (e.g. Firefox, Chrome). However, when I open the website with Microsoft Edge and try to select all rows by clicking on the upper checkbox only the first row of the table will be checked, all other rows remain unchecked. This is my tables.py: class CRNTable(tables.Table): LinkModelColumn = tables.CheckBoxColumn(accessor='pk', attrs = {"th__input": {"onclick": "toggle(this)"}}, order_by='pk', verbose_name='Model') ... This is my JavaScript: <script language="JavaScript"> function toggle(source) { var checkboxes = document.getElementsByName('LinkModelColumn'); for(var i in checkboxes){ checkboxes[i].checked = source.checked;} } </script> -
Django - GeoDjango read coordinates in the wrong order
first of all thanks for your help. I'm making a form with Django which uses the OSMWidget to save coordinates (Polygons, Lines and Points) to a Geometry field in a PostgreSQL database. It works well, I can save the information in the database without any problem. And when I make a query with PgAdmin I can see the geometric fields data displayed in a Leaflet map correctly. Example of PgAdmin map with the geometric field data. Here's some of what I have in my forms.py: from django import forms from django_select2 import forms as select2_forms from django.contrib.gis import forms as osmforms from django.forms import ModelForm from .models import Dataset class SessionForm(forms.ModelForm): at_choices = [(item.title, item.title) for item in Dataset.objects.all()] key_choices = [(item.keywords_d, item.keywords_d) for item in Dataset.objects.all()] uuid = forms.CharField(label='', max_length=10 , widget=forms.TextInput(attrs={'class': "form-control left-half"})) title = forms.CharField(label='Title', max_length=65536 , widget=forms.TextInput(attrs={'class': "form-control full-size-field"})) abstract = forms.CharField(label='Abstract', max_length=65536 , widget=forms.Textarea(attrs={'class': "form-control full-size-field", 'title': 'Your name'})) keywords_d = forms.MultipleChoiceField(label='Keywords', widget=select2_forms.Select2MultipleWidget(attrs={'class': "form-control left-half",'style': 'width:100%'}), choices=key_choices) activity_type = forms.MultipleChoiceField(label='Activity type', widget=select2_forms.Select2MultipleWidget(attrs={'class': "form-control right-half",'style': 'width:100%'}), choices=at_choices) related_site_we = forms.CharField(label='Related Site', max_length=256 , widget=forms.TextInput(attrs={'class': "form-control full-size-field"})) bounding_box = osmforms.GeometryCollectionField(label='Bounding Box', widget=osmforms.OSMWidget(attrs={'class': "form-control full-size-field",'map_width': 992, 'map_height': 500})) class Meta: model = Dataset fields = ['uuid','title','abstract','keywords_d','activity_type','related_site_we','bounding_box'] And this … -
What do you think represents knowing Django?
Lately I've heard of people asking things like, do you know Django? can you work with Django? to kinda measure the things that you can do with it. As far as I understand, this can vary depending on the usage that you give to the framework. Not all the time you have to create a middleware or create an email back-end inside a Django app, however it seems like you have to know how to do that in order to be able to tell someone that you can work with Django and get a job as a back-end developer. What level of knowledge you believe it's required to say I know Django? What makes you know a framework or a language? -
Django Cms - wrong children url in menu when logged from admin
Hello I've a problem in my site menu. The django cms version is 3.7.2 I've four languages (en, it, de, fr) When an anonymous user use the site the menu is correct. When I'm logged from the admin panel i see some strange behaviors: when I've a second level page the url is composed with the parent slug in the wrong language (and if I do any change to the slug an publish it i still see the old slug) Here's the code for the menu.html {% load menu_tags %} {% for child in children %} <li class="child{% if child.selected %} selected{% endif %}{% if child.ancestor %} ancestor{% endif %}{% if child.sibling %} sibling{% endif %}{% if child.descendant %} descendant{% endif %}"> <a href="{{ child.attr.redirect_url|default:child.get_absolute_url }}" title="{{ child.get_menu_title }}">{{ child.get_menu_title }}</a> {% if child.children %} <ul> {% show_menu from_level to_level extra_inactive extra_active template "" "" child %} </ul> {% endif %} </li> {% endfor %} -
Quickly update django model objects from pandas dataframe
I have a Django model that records transactions. I need to update only some of the fields (two) of some of the transactions. In order to update, the user is asked to provide additional data and I use pandas to make calculations using this extra data. I use the output from the pandas script to update the original model like this: for i in df.tnsx_uuid: t = Transactions.objects.get(tnsx_uuid=i) t.start_bal = df.loc[df.tnsx_uuid==i].start_bal.values[0] t.end_bal = df.loc[df.tnsx_uuid==i].end_bal.values[0] t.save() this is very slow. What is the best way to do this? -
OPEN DJANGO AFTER INSTALLATION
Hello pls after installing django using pip on my command prompt pls how do i open django on my sytem -
getting the count of titles opened by a user only if the first entry also belongs to the same user
Title model: class Title(models.Model): first_author = models.CharField(max_length = 150) title = models.CharField(max_length = 150, unique = True) created_date = models.DateTimeField(auto_now=True) title_url= models.CharField(max_length = 150) Entry model: class Entry(models.Model): title = models.ForeignKey("titles.title", on_delete= models.CASCADE) user = models.ForeignKey("auth.user", on_delete= models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) content = models.TextField(max_length=10000,) In my blog, when a user opens a title the user also has to write the first entry. When the first entry is deleted if there are no other entries in the title, the title also get deleted. So I want to count titles opened by the user only if the first entry of the title still belongs to the same user. The only idea I have is to get all the titles opened by the user: titles= Title.objects.filter(first_author=user.username) Then iterate over titles and check whether the first title still belongs to the same user and if so add it to the count. But since it requires iterating over the queryset the query object is no longer lazy and it takes too much time end effort. I wonder if there is a way of achieving it by only one ORM. -
id gets undefined on click event
I am getting value in details and it also have id in it. But while fetching it shows Id is Undefined html </tr> <script type="text/ng-template" id='display'> <button type="button" class="btn btn-danger btn-sm" ng-click="delete(detail.id)">delete</button></td> </script>``` angular $scope.delete= function(id) { console.log($scope.id); } }); -
Sending images from Django(Server A) to Django-rest-api(Server B)
I built two Django servers. One is for image-processing and the other one is for front-page with forums. I designed like: If users post images to front-server(Django), then it send them to api-server(Django-rest-framework). Is there any ways to implement it? Thanks. -
Query user in Django
first post here. Im trying to query the user so i from the form so i can save the user in my database. This is my code form = lageBruker(request.POST) bruker = User.objects.create(format(request.POST['username'])) print() if request.method == 'POST': if form.is_valid(): fornavn = request.POST['first_name'] etternavn = request.POST['last_name'] email = request.POST['email'] kunde = Kunde.objects.create( #bruker = bruker, fornavn=fornavn, etternavn=etternavn, email=email ) kunde.save() context = {'form': form} return render(request, 'ebutikk/registrer.html', context)``` -
Django signals + channels: message not going through to client
I want a signal to be sent every time a .save() is made from django.db import models from django.forms.models import model_to_dict from django.db.models.signals import post_save from channels.layers import get_channel_layer from django.core.serializers.json import DjangoJSONEncoder from asgiref.sync import async_to_sync import json class DeribitFundingData(models.Model): time = models.DateTimeField() rate = models.FloatField() def __str__(self): return str(self.time) def save_post(sender, instance, **kwargs): channel_layer = get_channel_layer() data = model_to_dict(instance) json_data = json.dumps(data, cls=DjangoJSONEncoder) async_to_sync(channel_layer.group_send)( "echo_group", {"type": "stream", "data": json_data}, ) post_save.connect(save_post, sender=DeribitFundingData) My consumer looks as follows, where stream is supposed to receive the data from save_post: class StreamConsumer(AsyncConsumer): groups = ["echo_group"] async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) async def stream(self, event): data = event["message"] await self.send({ 'type': 'websocket.send', 'text': data }) My .js: <script> var loc = window.location var wsStart = "ws://" if (loc.protocol == 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + "/websockets/" console.log(endpoint) socket = new WebSocket(endpoint); socket.onopen = function(message) { console.log("open", message); } socket.data_stream = function(message) { console.log("stream", message); } socket.onerror = function(message) { console.log("error", message); } socket.onclose = function(message) { console.log("close", message); } </script> In the shell I see that the websockets connection was established. Although the messages I'm sending from post_save are not … -
Error sending POST from React front end to Django,error status 401
I am using Token authentication for Django & React integration. The below POST method fails in React with status 401,however same method give status 200 ok from POSTMAN(with same token,url and id) axios .post(`songs/${id}/like`, { headers: { Authorization: `Token ${token}` }}) .then() .catch(); }; I have ensured that I passed all parameters to axios but something got wrong. Other interaction with backends like login,signup,GET methods work fine. What are the possible causes for the error ? I have set CORSORIGINALLOWALL=True. -
How to implement 2 Boolean Fields conditional OR in django filters?
I am using django-filters. I want to filter my model with 2 boolean fields "men" & "women". From the image below you can see I have 3 records. 2 records have "men" field checked. In my template where I have the filter implemented, when I check "men" checkbox, it returns only one record because it is checking AND conditional. How do I implement conditional OR for those Boolean Fields so that is returns the 2nd record as well where it has "men" checked as well? class UserProductFilter(django_filters.FilterSet): SUB_CATEGORY_CHOICES=Products.objects.values_list('sub_category',flat=True).order_by('sub_category').distinct('sub_category') sub_category=django_filters.ModelChoiceFilter(label='Sub Category',field_name='sub_category',to_field_name='sub_category',queryset=SUB_CATEGORY_CHOICES) men=django_filters.BooleanFilter(label='Men',field_name='men', widget=forms.CheckboxInput) women=django_filters.BooleanFilter(label='women',field_name='women', widget=forms.CheckboxInput) class Meta: model = Products fields = ['sub_category', 'men', 'women'] The Image with records. -
how to use django inlineformset with javascript
i tired of trying many ways but non of them worked in my case . whenever i save my inlineformset it only save the last form , if count=3 then from my front end it will generate 3 fields to add books , but it only the save the last one. i appreciate any helps , and even i'm ready to pay to the solution my models.py class Book(models.Model): book = models.CharField(max_length=20,unique=True) author = models.ForeignKey(Author,on_delete=models.CASCADE) class Author(models.Model): author = models.CharField(max_length=30,unique=True) count = models.IntegerField() this is my forms.py class AuthorForm(ModelForm): class Meta: model = Author fields = ['author','count'] class BookForm(ModelForm): class Meta: model = Book fields = ['book'] InlineFormset_Author = inlineformset_factory(Author,Book,form=BookForm,extra=1) and also this is my views.py class CreateBookView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = Author form_class = AuthorForm def get_context_data(self,*args,**kwargs): context = super(CreateBookView,self).get_context_data(*args,**kwargs) if self.request.POST: context['book'] = InlineFormset_Author(self.request.POST) context['book'] = InlineFormset_Author() return context def form_valid(self,form): context = self.get_context_data() context = context['book'] with transaction.atomic(): self.object = form.save() if context.is_valid(): context.instance = self.object context.save() return super(CreateBookView,self).form_valid(form) and this is my template <form method="POST">{% csrf_token %} {{book.management_form}} {{form.author | add_class:'form-control col-12 col-sm-10 mx-auto'}} {{form.count | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:count'}} <button class="col-4 mx-auto shadow-lg border-right border-left">insert</button> <div id="BOOK" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" aria-hidden="true"> <div class="modal-dialog" … -
Installing collected packages: twisted, daphne, channels Running setup.py install for twisted ... error
''' ERROR: Command errored out with exit status 1: 'c:\users\vikas bahuguna\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Vikas Bahuguna\AppData\Local\Temp\pip-install-mm65vrjl\Twisted\setup.py'"'"'; file='"'"'C:\Users\Vikas Bahuguna\AppData\Local\Temp\pip-install-mm65vrjl\Twisted\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\Vikas Bahuguna\AppData\Local\Temp\pip-record-os___wbn\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\vikas bahuguna\appdata\local\programs\python\python38-32\Include\Twisted' Check the logs for full command output. '''