Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to give initial data to put method ,Django (I want to create edit profile page)
I want to have an edit profile page in django,and I want when user enter this page current username fill username box and if he want then he can change username. I have this put method: def get_object(self, pk): try: return User.objects.get(pk=pk) except Exception as e: raise Http404 def put(self, request, pk, format=None): user = self.get_object(pk) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) how can i do this? -
django user registration error with django_rest_auth package
i used django rest auth in my project,but i get these error when i try to create a new user [WinError 10061] No connection could be made because the target machine actively refused it -
Django: Where generic forms like LoginView renders functions dictionary fill and how can I change it
I use LoginView class in Django. We can use this class as login view with a HTML template, like below: urls: from django.contrib.auth.views import LoginView urlpatterns = [ path('', LoginView.as_view(), {'template_name': 'login.html'}), ] login.html: <head> <title>test<title> {% load static %} </head> <body> <form method="POST"> {% csrf_token %} {{ form.as_p }} </form> </body> my question is where renders function dictionary or httprequest fill? and how can I change, form.as_p to login_form.as_p, for example? -
Django DateTimeField says 'You are 5.5 hours ahead of server time.'
In one of my model I am storing time_stamp = models.DateTimeField(default=timezone.now) But when I save the model it says You are 5.5 hours ahead of server time. for example local time in my machine is 13:02 but after saving what gets stored in db is 7:16 I got one related here but it does not an have a satisfying answer... models.py class Comment(models.Model): time_stamp = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.time_stamp = timezone.now() return super(Comment, self).save(*args, **kwargs) -
adding and removing a class to element using javascript
I have a javascript intended to add specific ads to favorite list when user click on favorite icon. Now, I want to change this icon from empty to solid (through removing and adding different class). Note: I am using Django for the backend and font awesome for the icon I wrote a javascript line to select the specific icon has been clicked. However, I got an error telling me that Cannot read property 'classList' of null. I added if statement to make sure that specific code is executed.Hence, I got rid of the error but the code still not working as I want and still not be able to add and remove the class upon the user add and remove the item to and from the favorite list. here is the code: <i id="favouriteBtn_{{item.id}}" onclick="currentAddFav({{item.id}})" title="add this ads to favorite list " class="fa fa-star-o favo_ls"> </i> this is the javascript portion: function currentAddFav(item_id){ if (localStorage.getItem('favourites')) { // If there are favourites var storage = JSON.parse(localStorage['favourites']); if (storage.indexOf(item_id) == -1) { // not found storage.push(item_id); localStorage.setItem('favourites', JSON.stringify(storage)); console.log('item has been added to favorites') cc="#favouriteBtn_"+item_id console.log(cc) var fav_solid = document.getElementById(cc); if (fav_solid){ fav_solid.classList.remove("fa-star-o"); fav_solid.classList.add("fa-star");} } else { // found storage.splice(storage.indexOf(item_id),1) localStorage.setItem('favourites', JSON.stringify(storage)); … -
Create a table for each entry in a model
I am new to python and django, I Want to add a table dynamically in the database when a new user register (in python way of course), in other words when a user inserts a new data into a model i want to create a table explicitly for that entry, to add extra Data which will related with that entry. I think python has an easy way to handle this kind of situation Image representation -
How to use user uploaded image in Django template
Before marking this question duplicate please be informed that I have tried looking existing q/a and other tutorial along with documentations. My problem is I am unable to use images in templates that are uploaded by an admin with admin interface. I have configured my settings and urls according to documentation. in browser inspect element it is showing <img src(unknown)> uploaded image by an admin using admin interface is stored in the /media/ which is media root. location of the image is /media/img/imagename.jpg settings.py # media MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py (my project url file) from django.conf import settings from django.conf.urls.static import static ## urlpatterns here if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_URL) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_URL) models.py class AboutMe(models.Model): image = models.ImageField(upload_to='img') ## other fields views.py def index(request): aboutme = models.AboutMe.objects.all() context = {'information': aboutme,} return render(request, 'portfolio/index.html', context) template/index.html {% for info in information %} <img src="{{ info.inage.url }}"/> <div class="name-profile t-center"> <h5 class="uppercase">{{info.name}}</h5> </div> {% endfor %} -
django:type(int instance) shows long
order = OrderCacheTab.objects.filter(order_id=3001180).first() print type(order.status) #order.status=7 》》》》<type 'long'>` with DB mysql,the order.status is INT(11) with frame django 1.6.11, status = models.IntegerField() # python console showed the right answer:int pycharm run console and degug console shows wrong answer type 'long' -
I updated Python to a newer version, now running python in my virtualenv prints out errors
I get this error when I try to run python myvenv) C:\Users\SONY\Desktop\djangoproject>python Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Current thread 0x000021f0 (most recent call first): Any ideas on how I can fix this please?? -
Illustrated texts in Django model
I am trying to make one Blog using Django 2.0 and I have already created a primitive one. It has a Post model which is as follows: class Post(models.Model): PriKey = models.CharField(max_length=255,primary_key=True) Heading = models.CharField(max_length=100) DateOfPost = models.DateField(default=datetime.date.today()) Content = models.TextField() As it can be seen, the content area is only textual and as of now, I can't add any special style or pictures inside my content. I thought of using HTML tags inside the text content but they are appearing unchanged when the web page is rendered. So my question is, is there any way of storing pictures along with the text in the content field of the Post model? I want to make something like this Is there any way of showing the pictures in there respective positions using Django model? If no, is there any other way of doing this? Also, is there any way of storing HTML codes inside django models and render them as it is when the website is run? -
Angular push to Django for user login form error "SyntaxError: Unexpected token < in JSON at position 2 at JSON.parse (<anonymous>)"
I'm assuming that the < is because it's returning a HTML or XML response. This is my login part where it's failing. public login(user) { this.http.post('/api-token-auth/', JSON.stringify(user), this.httpOptions).subscribe( data => { console.log('login success', data); this.updateData(data['token']); }, err => { console.error('login error', err); this.errors = err['error']; } ); user returns {username: "user", password: "password"} JSON.stringify(user) returns {"username":"user", "password":"pass"} this.httpOptions returns {headers: HttpHeaders} with array content-type application/json console is returning the err 'login error' and I don't know why This is the error: HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8000/api-token-auth/", ok: false, …} error: {error: SyntaxError: Unexpected token < in JSON at position 2 at JSON.parse (<anonymous>) at XMLHttp…, text: "↵↵<!doctype html>↵<html>↵<head>↵ <base href="/"…s"></script>↵</body>↵</html>↵ "} headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message: "Http failure during parsing for http://localhost:8000/api-token-auth/" note: I temporarily disabled csrf middleware because I was running into an issue there as well, not sure if related. -
Getting and cleaning data from non-model form
I'm pretty experienced with model forms and know how to obtain data from them within a view. Example: if form.is_valid(): instance = form.save(commit=False) name = instance.name I'm using a non-ModelForm (i.e. forms.Form) for the first time. Within my view, I'm not sure how to obtain the cleaned form data from the form before saving it to a model. I've tried the following, but it doesn't seem to work. if form.is_valid(): name = form.get('name') Within the 'if form.is_valid():' section of a view, how would you: a) Obtain the form data b) Clean the form data Thanks so much! -
How to fetch Django related model rows and return as a list of dictionary?
AM using Django v1.11 I have the following models: class LineItem(): quote = models.ForeignKey(Quote, related_name="quote_line_items") sku = models.ForeignKey(SKU) class Quote(): def fetch_as_list_of_dict(self): return LineItem.objects.filter(quote=self).select_related('sku__product').values() class SKU(): product = models.ForeignKey(Product) My fetch_as_list_of_dict fails to contain the sku.product_id or sku.product object. I only need to get the sku.product_id as part of a dictionary which in itself is one of many in a list. How do I achieve this? -
Django db_index=True not creating index, but class Meta indexes yes
In my django model, when creating indexes via db_index=True in field definitions, the index is not created. Only if I created in the class Meta class Agreement(UUIDPrimaryKey): job = models.ForeignKey( 'posts.Job', on_delete=models.CASCADE, verbose_name=_("job"), ) class Meta: indexes = ( models.Index(fields=['job']), ) And if I run makemigrations, the index is created. Create index agreements__job_id_eb7df0_idx on field(s) job of model agreement But If I change my model to: class Agreement(UUIDPrimaryKey): job = models.ForeignKey( 'posts.Job', on_delete=models.CASCADE, verbose_name=_("job"), db_index=True, ) And I run makemigrations, the index is deleted. Remove index agreements__job_id_eb7df0_idx from agreement Should not be the same both definitions? -
If-statement not evaluating correctly in template
I've got the following logic in one of my templates. The message variable is set to "Close Demo" with my view as seen below. views.py messages.error(request, "Close Demo", extra_tags='errortag') I've got the following code in my template to exclude the message if it equals "Close Demo". Template {% if messages %} {% for message in messages %} {% if message != "Close Demo" %} {{message}} {% endif %} {% endfor %} {% endif %} Despite this, the "Close Demo" error still shows up on my page. I'm absolutely baffled why my if-statement isn't executing as desired. Thanks! -
How to fire up all docker containers on a same local ip address in django?
I am writing a django based application with docker where there are 3 projects apps running in different containers. All django applications run at 0.0.0.0:8000. But when I check the ip address of containers to browser the application in browser, they all run at different ip addresses: project1 runs at 172.18.0.10:8000 can be accessed at: 172.18.0.10:8000/app1 project2 runs at 172.18.0.9:8000 can be accessed at: 172.18.0.9:8000/app2 project3 runs at 172.18.0.7:8000 can be accessed at: 172.18.0.7:8000/app3 which makes the hyperlinks of my app unusable. How do I run all the containers at one single ip, 'localhost:8000'? Any suggestions where I am going wrong? -
adding results that generated from views to models(database) generating an error : null value in column "price" violates not-null constraint
my views generally does basic stuff like adding multilying etc now all this will be stored in a variable called grand_total now i want to add this grand_total to my model(database) i have done this by calling my model instance and adding it to it and saving def admin_order_pdf(request, order_id, *args, **kwargs): queryset=D.objects.all() order = get_object_or_404(queryset, id=order_id) type=order.type price=order.price meters =order.meters price_total=price*meters discount=order.discount total=price_total grand_total=total-discount # direct=D.objects.update_or_create(grand_total=grand_total) direct=D() direct.grand_total=grand_total direct.save() i expect the data should be updated in to my grand_total field when i run this function here is the complete error IntegrityError at /pro/bill/17/pdf/ null value in column "price" violates not-null constraint DETAIL: Failing row contains (26, , null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 2018-12-29 06:25:38.733529+00, 10). -
How Facebook Messenger bot (on Django) can ask a question, so next reply by user will be considered as answer?
I have build a bot on Django, and it sends messages if received messages are specific words, and saves them to the model with id of fbid(facebook id). Now I want to send a question (e.g. What is your address?). How to make the bot to send a "question"(not a message), so it knows that the next message from user will be answer. When making buttons in chat, they are with "payloads", so chat knows which button is clicked. Is there any way to apply that principle in messaging? -
Django Model custom field compare previous and new values
I have a field in admin like this: Currently, adding new items to the field replaces the entire field with new files (File Input allows multiple images). However, the goal is to be able to do two things: Uploaded photos append to the existing list of photos instead of replace Clicking "Clear" checkboxes remove photos The current underlying database representation is postgres JSONField. In order to achieve current state, I have overriden ClearableInputField widget and ImageField form field to support multiple files. I have also created a custom Photos Model field that uses JSONField to upload files. Now, here comes my biggest issue. In a typical scenario, if a field is cleared, the file/image will be deleted if it is required by application logic. However, due to the fact that I am fiddling with contents of a field in order to delete photos from the storage, I am not sure where to delete the photos. I like to think about it this way. My Field is basically a "Model" that has some properties. However, this raises one big question. Because I am working at a field level, I can't access previous value to compare values for deleting or appending photos. … -
Using this d3 gauge in django?
I have never used javascript nor d3 in django yet, can anyone run me through on how to include this gauge in my html file in django? I have already npm installed d3-simple-gauge, but I am not sure how to actually use it. https://www.npmjs.com/package/d3-simple-gauge My current understanding is: I have to put a script tag including the link, although I am not sure why. My current don't knows: Do I include the usage part in the d3-simple-gauge documentation all between a script tag? -
Displaying a specific object field in ChoiceField
I've got a ChoiceField in my form. The options that appear in the dropdown are equal to "industry name - frequency" (eg. Car Maintenance - Annual). I want the options in the dropdown to only be equal to the value in the frequency field of the choices that I initialize (eg. Annual). Models.py class IndustryFrequency(models.Model): industryname = models.ForeignKey(Industry, on_delete=models.CASCADE) frequency = models.CharField() def __str__(self): return '{} - {}'.format(self.industryname, self.frequency) Forms.py class UserOrderForm(forms.Form): frequency = forms.ChoiceField() def __init__(self, *args, **kwargs): super(UserOrderForm, self).__init__(*args, **kwargs) self.fields['frequency'].choices = [(t.id, t) for t in IndustryFrequency.objects.filter(industryname=industry)] Thanks for your help! -
Django: store value after user logs in or signs up
I need to create a random value when user stars session and store it after user logs in or signs up. Must be deleted after user logs out. I'm using session.session_key, but could be anyother random value. Why session.session_key? Because it gets automatically generated when user enters website. When user enters website they can add items to their shopping cart, but cannot buy until logs in or signs up. All cart_items use the random value as a token, so if I can save this value after user logs in or signs up I can query the cart_items that are already saved in DB and restore items user had already put in this shopping cart. So when user enters a new session.session_key is created but after user logs in or signs up another session.session_key is created. Making it impossible to use this value to establish a flow between user not logged in and user logged in. My logic: 1.- Save session.session_key in Cookie. 2.- After user logs in or signs up a new session.session_key is created. We need to replace this new session.session_key with the one saved in Cookie. 3.- Get old session.session_key to query all objects created using this value … -
Django Table - loading data table, accessing values
My background is 100% in Excel VBA. But I'm working on building some of my first web applications in Django framework. Please pardon me if this question is ridiculous. I have a giant table (5000 rows x 7 columns) in a CSV file. I would like to somehow load this table into the Django framework -- and access the values in the table. If the table were smaller, I could create a new model, then load the CSV into the model. But instinctively, it feels wrong to create a model with thousands of fields. Is there another way to load the table into Django framework, and reference the values via something like a vlookup function? Thank you for any assistance! -
Django creating a new user using a form
I am trying to allow people to create an account by submitting a form. This is currently just continuing to a login screen but not creating the actual user or coming up with any errors. Debug is currently enabled. I have tried adding an else statement after the user_form.is_valid() to ensure it wasn't invalid but the same issue was happening. I am guessing it is an issue with how the form is saving but I am newer to Django, so any help is appreciated. view: def home(request): if request.user.is_authenticated: return redirect('user_dashboard') else: user_form = CreateUserForm(request.POST or None) if request.method == 'POST': if user_form.is_valid(): user_form.save() context = { 'user_form': CreateUserForm, } return render(request, 'Main/index.html', context) Model: class CreateUserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = [ 'username', 'email', 'password', ] def clean_password(self): password = self.cleaned_data.get("password") confirm_password = self.cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "password and confirm_password does not match" ) else: return password -
Django on Windows with DB2 fails
I am using: Windows 10 Pro IBM DB2 V11.1 Python 3.7 Django 2.1.4 ibm_db 2.0.9 ibm_db_django 1.1.1.2 After setting the connection information in settings.py and running python manage.py runserver I get the errors (tail only): File "D:\Python37\lib\site-packages\django\db\models\options.py", line 203, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "D:\Python37\lib\site-packages\django\db__init__.py", line 33, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) File "D:\Python37\lib\site-packages\django\db\utils.py", line 203, in getitem conn = backend.DatabaseWrapper(db, alias) File "D:\Python37\lib\site-packages\ibm_db_django\base.py", line 155, in init super( DatabaseWrapper, self ).init( *args ) File "D:\Python37\lib\site-packages\django\db\backends\base\base.py", line 101, in init self.client = self.client_class(self) TypeError: 'NoneType' object is not callable The same setup works fine on MacOS. A simple python program using ibm_db works fine on Windows.