Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extender usuario de Django
El problema lo tengo no en extender el modelo de Django es que necesito crear más de un tipo de usuario en concreto dos Estudiante y Profesor cada uno con atributos en común pero con otros propios de cada uno, alguien me pudiera dar alguna idea o ejemplo. -
Convert dynamic JSON array to HTML
I have a Django view that will return JSON data depending on what is given to it. Each JSON element will have the same fields but the returned JSON array will have a dynamic amount of elements. Here is an example of the possible JSON data that could be returned: [ { "Open Job Lines": 0, "Open Hours": 0, "Repair Order": "123454", "Expected Pay": 1.9, "Actual Pay": 1.0, "Pay Status": "Underpaid" } ] Here is an example or a JSON return with multiple elements: [ { "Open Job Lines": 0, "Open Hours": 0, "Repair Order": "123454", "Expected Pay": 1.9, "Actual Pay": 1.0, "Pay Status": "Underpaid" }, { "Open Job Lines": 0, "Open Hours": 0, "Repair Order": "123454", "Expected Pay": 1.9, "Actual Pay": 1.0, "Pay Status": "Underpaid" } ] Using JavaScript, I would like to turn this into HTML similar to following and assign it to a variable. Open Job Lines: 0 <br> Open Hours: 0 <br> Repair Order: 123454 <br> Expected Pay: 1.9 <br> Actual Pay: 1.0 <br> Pay Status: Underpaid <br> Open Job Lines: 0, <br> Open Hours: 0 <br> Repair Order: 123454 <br> Expected Pay: 1.9 <br> Actual Pay: 1.0 <br> Pay Status": Underpaid <br> -
Reverse for 'account_email_verification_sent' not found. 'account_email_verification_sent' is not a valid view function or pattern name
I'm trying to use allauth and rest-auth in my project and try to use the built in function in allauth to do this but this what i get : and here is my codeenter image description here settings.py ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_EMAIL_REQUIRED = True urls.py urlpatterns = [ re_path(r'^', include('rest_auth.urls')), re_path(r'^registration/', include('rest_auth.registration.urls')), ] -
Differentiating between Methods and Functions [duplicate]
This question already has an answer here: Difference between methods and functions [duplicate] 4 answers Difference between a method and a function 33 answers Relevant background: I have gone through LPTHW (while reading the official documentation as a point of reference), and am now learning about Django. When learning about functions, I never really stopped to think about the different ways that I called them. What different ways am I referring to? Well, for example: add(a, b) compared to: string.split() I started googling to try and find out why some are called with arguments, while others are simply called like '.function()'. I realised that .split(), in this case, may very well be a method rather than a classic function, and that that might be the reason for it being used this way. Are all functions that get called like ''.function()'' really methods, defined in classes? If so, does that mean that .split() is part of the string class? Are string-classes instantiated by just defining a string? Thank you! -
Django: separate shops
I would like to create a Django project which will do the following: There is a platform example.com which already have a "shop" functionality (app). This platform should provide an ability to users to create their own store inside platform. Users can set up a a shop on and will receive a url like user1.example.com user2.example.com In this cases each url is a separate store. The problem is: I don't know how to make each store to have its own shopping cart, order history, etc. I just need an advice: what is best to use to solve this problem (maybe, sessions or some other Django features?) -
Only protocol 3 supported error
I'm trying to configure Django with PostgreSQL on Windows Server 2012. but after a while i get this error only protocol 3 supported I'm using Postgres 9.6 and psycopg2 2.7.3 and Django 1.11 and mod_wsgi. In settings.py I have DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydb', 'USER': 'postgres', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', } } i read this question and also this question but did not found any solutions. Do you know any solutions for the problem? -
How to edit path for django unit tests?
I'm trying to run the standard 'python manage.py test` however I'm getting a: `ImportError: No module named 'draft1.app'` for all 9 of my apps in my project (9 errors). Full error example: ImportError: Failed to import test module: draft1.profiles Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) ImportError: No module named 'draft1.profiles' My project tree is: /draft1 /draft1 /profiles ... /bin /lib /include Any idea what the problem is? -
what is the best Ide and language for creating stock market analysis website which uses python code?
I want to create a website which shows all stocks price with real time charts and price which gets refreshed in few seconds. I was thinking to start this in python as it is quite fast and it will be easy to plot different type of charts on stocks previous data. Whereas I am proficient in asp.net mvc but I am confused whether I should learn Django or any other python framework for this or not. Because going forward I want to use machine learning on my website as well it would be easier to execute machine learning scripts written in python. Please suggest, Thanks in advance. -
CSRF verification failed (Django)
I'm getting this error when trying to log in to my django app. Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests. Help Reason given for failure: CSRF cookie not set. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: - Your browser is accepting cookies. - The view function passes a request to the template's render method. - In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. - If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. - The form has a valid CSRF token. After logging in in another browser tab or … -
Django login as modal - issues checking if the username inputted exists
I'm attempting to produce a global login form in a modal pop-up using custom login middleware. middleware.py (custom login form middleware): class LoginFormMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.method == 'POST': login_form = AuthenticationForm(data=request.POST, prefix="login") if login_form.is_valid(): user = login_form.get_user() username = login_form.cleaned_data['username'] if User.objects.filter(username=username).exists() and user: login(request, user) return HttpResponseRedirect(request.path) else: raise login_form.ValidationError(u'Aw, snap! Looks like the username "%s" doesn\'t exist. Perhaps you should register?' % username) if reverse('logout') in request.get_full_path(): return HttpResponseRedirect('/') else: login_form = AuthenticationForm(request, prefix="login") request.login_form = login_form return self.get_response(request) Essentially - this works great when logging in a user. Very happy. I have some client side form validation checks - mainly to check that both the username and the password fields have something (anything) in them. The issue for me lies with the server side checks. The current state is that the above middleware isn't raising the form errors when required...it just redirects back to the home page :'( My template looks like this (inside base.html which all other templates extend from, ignore the rather hacked forloop counter stuff - that's just to get certain Bootstrap.js stuff working): <!--Start Django Login Form --> <form id="loginForm" action="." method="POST"> {% csrf_token %} … -
Fillter jvectormap markers on button click
I am trying to add a filter that will activate on-click. The way I have it set up is I built a JSON in the back-end, and send it to the front-end(JS). Cool? On click, I would like to filter the JSON and re-assign the data variable passed into the map. Here is the code... var data = {{map_data|safe}} var filterMarkers = ['recommend', 'upcoming', 'trip', 'residence', 'saved'] var filteredData; var filters = []; var color = data.color; $(".map-legend-circle").click(function(e) { e.preventDefault(); data = {}; filteredData = {}; filteredData = data; $(this).toggleClass('map-legend-filtered'); $(this).children().children().toggleClass('map-legend-filtered'); var idName = $(this).prop('id').split('-')[0]; if ($(this).hasClass('map-legend-filtered')) { // remove it from filterMarkers // filter it against the filterMarkers and get rid of it. filterMarkers = filterMarkers.filter(function(marker) { return marker !== idName; }); console.log(filterMarkers, "filterMarkers"); for (var marker in filteredData.marker) { for (var i = 0; i <= filterMarkers.length; i++) { if (filteredData.marker[marker].type.toLowerCase() === filterMarkers[i]{ filters.push(filteredData.marker[marker]); } } } data = {marker: filters, color: color}; } else { filterMarkers.push(idName); // dont worry much about this yet. } }); So I want to update data cos I am then passing it into here... $('#world-map').vectorMap({ map: 'world_mill', markers: data.marker, // more code The JSON updates, but not the filters. I suspect I … -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'
I have two apps : Characters and Accounts. Here is Characters' models : from django.db import models class Character(models.Model): characterid = models.AutoField(primary_key=True, unique=True) charactername = models.CharField(max_length=100) characterspell1 = models.CharField(max_length=100) Now, here is Accounts' models : Persos = Character.objects.all() class Profile(models.Model): PERSO_CHOICES=[] for Perso in Persos: PERSO_CHOICES.extend([(Perso.characterid ,Perso.charactername)]) user = models.OneToOneField(User, on_delete=models.CASCADE) character = models.IntegerField(choices=PERSO_CHOICES, null=False, blank=False, default=0) def __str__(self): # __unicode__ for Python 2 return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() Now, I would like to do something like this in Accounts' Profile class : Character_info = Character.objects.filter(characterid = Profile.character) characterspell1 = Character_info.characterspell1 (Or something like this) Here is the error I'm having : TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' How can I fix that ? -
Django Live Project not showing media/images
I have a site that collected finaly the CSS, but now i have an issue with the Media files. The blog part is not showing the images for each post. the site is on: http://beta.reichmann.ro:8000/posts/ My media settings are: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "media_root") The location on the server is: The images are broken so they are not linked up to the page. PS. I will not gonne have a lot of images there, i will write maybe 1 posts per month, therefore shouldn't be an issue with the space etc. Please advise. -
I want to add a location field in django model which take location input by putting lattitude and longitude
I also want to pick the location through Django REST API Through template..please suggest necessary django packages for it and how to write locationField in the Django Model -
notify user if similar model created _Django
I have a model.that I need to if any model with specific field created in database.send a Email to user for notify.I did some search too many apps are there for handling the notify. thats not my concern .I dont know how deploy this structure.any guide or example for this.for example : if x = book.objects.create(title="book1") : print("the book created") if this action happend do something. -
How is not displayed news?
How is not displayed news - plugin djangocms aldryn-newsblog? Con be exemple visible last news from admin panel? Screens: https://image.ibb.co/ewP8zG/b9481709_d6dc_4b77_890a_6d0ca852866f.png https://image.ibb.co/mcZaeG/3bd573d3_36d0_429a_bd50_436a9ee26cc3.png https://preview.ibb.co/dALFeG/5841cbf1_259f_4a2d_93eb_f7352dc3ddb8.png -
TypeError: 'GoodsCategory' object does not support indexing
goods.py class Goods(models.Model): category = models.ForeignKey(GoodsCategory, verbose_name='xxx') goods_sn = models.CharField(default='', max_length=50, verbose_name='xxx') name = models.CharField(max_length=300, verbose_name='xxx') click_num = models.IntegerField(default=0, verbose_name='xxx') sold_num = models.IntegerField(default=0, verbose_name='xxx') import_goods_data.py from apps.goods.models import Goods, GoodsCategory, GoodsImage from db_tools.data.product_data import row_data for goods_detail in row_data: goods = Goods() goods.name = goods_detail['name'] goods.market_price = float(int(goods_detail['market_price'].replace('¥', '').replace('&', ''))) goods.shop_price = float(int(goods_detail['sale_price'].replace('&', '').replace('$', ''))) goods.goods_brief = goods_detail['desc'] if goods_detail['desc'] is not None else '' goods_goods_desc = goods_detail['goods_desc'] if goods_detail['goods_desc'] is not None else '' goods.goods_front_image = goods_detail['images'][0] if goods_detail['images'] is not None else '' category_name = goods_detail['categorys'][-1] category = GoodsCategory.objects.filter(name=category_name) if category: goods.category = category[0] goods.save() Because I got a error.So let me try to write it this way: categories = GoodsCategory.objects.filter(name=category_name) if categories.exists(): category = categories[0] else: category = GoodsCategory.objects.create(name=category_name) goods.category = category[0] goods.save() But I had another error. TypeError: 'GoodsCategory' object does not support indexing -
How to populate django models with form information
Right now I am having a bit of struggle trying to understand how forms work, and I am learner by example. Right now, I am trying to set up 2 models: Teacher and Student so that these models get their entries from logged users (teachers and students) but also from admin panel. So I made these 2 models and I made different views and forms for teachers so that they can create accounts by extending the AbstractUser. This model only provides me username, email, password and password confirmation. As you can see, for example,in my student model; photo, email and phone are blank=True. That is, because I want supervisor to add name, surname and student_ID only. When student creates account, he will be needed to enter these other fields as well. And also, I want that if his name, surname and student_ID don't match those from the model, he will not be able to create his account. I don't know if this approach is good or if I started bad, so I want a bit of advice. Here is what I tried: class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'student_signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return … -
Where are the built in django template tags located?
I found a directory called template tags in the django repo, but I do not see the template tags I'm looking for. Specifically, this one: {{ testdate | date:'m-d-Y, H:i a' }} -
how to call different settings from manage.py in django
I'm trying to call environment specific settings in django. I found that you can do something close in django admin according to: https://docs.djangoproject.com/en/2.0/topics/settings/#the-django-admin-utility I tried this with the manage.py: python3 manage.py runserver --settings=mysite.settings.prod_settings I get the error: ModuleNotFoundError: No module named 'mysite.settings.prod_settings'; 'mysite.settings' is not a package How can I call environment specific settings? Thanks -
Django - join between different models without foreign key
Imagine I have two simple models (it's not really what I have but this will do): Class Person(models.Model): person_id = models.TextField() name = models.TextField() #...some other fields Class Pet(models.Model): person_id = models.TextField() pet_name = models.TextField() species = models.TextField() #...even more fields Here's the key difference between this example and some other questions I read about: my models don't enforce a foreign key, so I can't use select_related() I need to create a view that shows a join between two querysets in each one. So, let's imagine I want a view with all owners named John with a dog. # a first filter person_query = Person.objects.filter(name__startswith="John") # a second filter pet_query = Pet.objects.filter(species="Dog") # the sum of the two magic_join_that_i_cant_find_and_posibbly_doesnt_exist = join(person_query.person_id, pet_query.person_id) Now, can I join those two very very simple querysets with any function? Or should I use raw? SELECT p.person_id, p.name, a.pet_name, a.species FROM person p LEFT JOIN pet a ON p.person_id = a.person_id AND a.species = 'Dog' AND p.name LIKE 'John%' Is this query ok? Damn, I'm not sure anymore... that's my issue with queries. Everything is all at once. But consecutive queries seem so simple... If I reference in my model class a "foreign key" (for … -
Download file with boto3 in s3, why my files are delete after download?
Download file with boto3 in s3, why my files are delete after download ? I tried several ways to download a file to my S3 bucket, but each time the file is deleted. Here is the mechanism of the program: 1) First I display the contents of my bucket. 2) Then via a client interface, I send the name of the file via ajax on a page in python. 3) Finally, I send a request on AWS thanks to Boto3 to have a url of downloading. I do not want to download directly into a local folder, the person must be able to choose the folder of destination and therefore I must generate a link on the bucket. Here is my Class : import boto3,botocore,sys, os import urllib class AWS: def __init__(self): self.aws_access_key_id='xxxxx' self.aws_secret_access_key='xxxxxx' class S3(AWS): def __init__(self,request): AWS.__init__(self) self.client_s3 = boto3.client('s3', aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key) self.bucket='bucket' self.path='path/' def download_file(self,request,name_file): if not (name_file is None): url = self.client_s3.generate_presigned_url('get_object', Params = {'Bucket': self.bucket,'Key': self.path+name_file}) urllib.request.urlopen(url) #url=self.client_s3.get_object(Bucket=self.bucket,Key=self.path+name_file) #with open(name_file, 'wb') as data: # self.client_s3.download_fileobj(self.bucket, self.path+name_file, data) urllib.request.urlopen() In this example, with generate_url my object is deleted and i can't download the object. But with boto3 function like download_file, i can download but it still … -
Django: Difference between using ASGI (Asynchronous Server Gateway Interface) and WSGI(Web Server Gateway Interface) . Which is better?
I would like to know the following: Difference between WSGI and ASGI in django. What is a WSGI application? How to Use ASGI/WSGI In Django ? -
django: how to display possible solutions according to user input?
The page should have a list where user can select desired option, and an submit button. On click of the submit button the results of the page should get displayed for eg: if the user selects india the results should be all the languages people speak in india. -
variable field in an "if"
how can I force the insertion of this "fascia" variable here: fascia = input("fascia [1-9]:") if iscritti.corso**+fascia+**_id==None: ... contatore1= Iscrizione.objects.filter(corso**+fascia+**_id=corsi)