Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Select2 Conditional POST
I'm a new developer and I have the select2.js plugin working correctly and my logic in the application is working. The next step is the POST, which i'm struggling at. My javascript uses the div class to show/hide the div based on the selected data_id. I'm trying to POST only the results of the data in the multi selector when the submit button is POSTed. I think i'm close, but i'm not sure how to handle a conditional for the data: in the ajax. My example is focused on the group situation being selected, but all others will follow the same. $(document).ready(function () { $('#accesslevelid').change(function () { $this = $(this) $('.content_box').each(function () { $select = $('select', this); if ($select.data('id') == $this.val()) { $(this).show(); $select.show().select2(); } else { $(this).hide(); $('select', this).hide(); } }); }); }); $('#submit-button').click(function (event) { event.preventDefault(); $.ajax({ url: "{% url 'submitted' %}", data: JSON.stringify({ ?:? }), dataType: 'json', type: 'POST', success: function (serverResponse_data) { }, }); }); }); My linter tool gives me an unexpected token on this line, regardless of if I add field:variablename in place of the ?:?, i just left the ?:? because i'm unsure of how to handle the conditional: data: JSON.stringify({ ?:? }), … -
Rackspace cloud object
I am trying to embed a video into my project, I have a the video on rackspace cloud which currently in private. I am using pyrax API and Django framework.I got the exact object of my file, but i could find documentation only on how to download the content not embed them to website. Can anyone help me how to embed this content to a webpage thanks in advance -
Django Project Live not Collecting Static
I have a django project which is deployed on a webserver http://beta.reichmann.ro:8000/. The thing is that it doesnt collect the static files. I run python manage.py collectstatic, but somehow the path is broken. The it from the site told me that the server searches for beta.reichmann.ro:8000/static/css/bootstrap.min.css. My settings are: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'contact.apps.ContactConfig', # am pus asta aici cand am creat for apliktie noua.for se ia din apps din apliktia contact si settings--contactconfig 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'posts', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] ROOT_URLCONF = 'chn.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', ], }, }, ] WSGI_APPLICATION = 'chn.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'ro' from django.utils.translation import ugettext_lazy as _ TIME_ZONE = 'Europe/Bucharest' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), … -
Web scraping using beautifulsoup, output keep varying
I'm currently want to scrape the review from the website foursquare.com. I used the following code to do it url = "https://foursquare.com/v/pantai-klebang/4c7c12d22d3ba14318e595d0" r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") containers = soup.findAll("li", {"class": "tip"}) filename = "review.csv" f = open(filename, 'w') for container in containers: review = container.find("div", {"class": "tipText"}).text print(review.decode('unicode_escape').encode('ascii','ignore')) I should get 144 data when I run the above code. Sometimes I get all of the data and sometime i get only 56 of the data Why does the output keep varying? Is it the issue with the code or the internet connectivity? -
django learning is going no where prefer a techinal answer not moral science
i ve learning django for 10 days now, made polls app ,blog app and some other apps present on tutorial websites.The concepts of django ain't sticking in head that's why i see my learning is going no where.Could you suggest some technical and practical measures to step up my learning and confidence? -
TransactionManagementError in Django
I created a Custom User Model in Django. I am now want to extend this model with an additional model called Ambassadors. The error I am getting is "TransactionManagementError". No matter what I tried or read I don't find the issue. Do you have any idea where the problem could be? Attached the Traceback as well as models.py Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/accounts/myuser/add/ Django Version: 2.0.1 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 574. return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func 58. return func.__get__(self, type(self))(*args2, **kwargs2) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/utils/decorators.py" … -
Django ORM, getting variables from three tables
I am basically trying to do two joins in one line in Django, but I cannot seem to find a solution. Below you can see the models.py. from django.db import models class Person(models.Model): name = models.CharField(max_length=100) surname = models.CharField(max_length=100) birthdate = models.DateTimeField() phonenumber = models.CharField(max_length=100) address = models.ForeignKey(Address,on_delete=models.CASCADE) def __str__(self): return self.name class Address(models.Model): name = models.CharField(max_length=100) number = models.IntegerField() city = models.ForeignKey(City,on_delete=models.CASCADE) def __str__(self): return self.name class City(models.Model): zippcode = models.CharField(max_length=10,primary_key=True,unique=True) name = models.CharField(max_length=100) def __str__(self): return self.name I want to filter the people with surname Smith, and show their name, date of birth, their street name and the name of their city. I came so far: Person.objects.filter(surname='Smith').values('name','birthdate','address__name','address__city__name') This doesn't work because of the last part in values 'address__city__name'. I am trying to figure out how to get the city name in some other way, but I can't seem to figure this out. Any suggestions? -
Namespace and URLs Multi-site
I am pretty new to Python and Django, but I am working on a multi-site Django, created on 1.9 I am currently trying to make it work with Django 2.0 but I don't understand how the namespace and URL Works. Here is how it worked with the 1.9 version (Account is mapped in Search site) : /* HTML, did not change */ <li><a href="{% url 'account:profile' %}">Profil {{ user.firstname.0 }}. {{ user.lastname }}</a></li> The old version /* Main project URLS.PY */ from search import urls as search_urls urlpatterns = [ url(r'^frontend/', include(frontend_urls)), url(r'^search/', include(search_urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) /* search project URLS.PY */ ACCOUNT_PATTERNS = [ url(r'^profil$', views.MyProfileFormView.as_view(), name='profile'), ] urlpatterns = [ url(r'^gestion/', include(ACCOUNT_PATTERNS, namespace='account')), ] And here is the 2.0 modified version I am trying to work with : /* Main project URLS.PY */ temppatterns = [ path('admin/', admin.site.urls), path('search/', include(search_urls)), ] urlpatterns = temppatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) /* search projects did not change */ But when I go to /search, I got this NoReverseMatch at /search/ 'account' is not a registered namespace I do believe there was some huge change on the URLConf but I can't find any documentation to help me understand what and why. To … -
Django automatic database upload
I'm developing application with react-native and Django REST api. what I want to do is to build a database using open api. I made codeline for I have implemented getting json format data through open api. But I have no idea what to do next. How can I put the data I have received into the relation table defined by Django model? -
Django race condition inside a transaction
I have Django 1.11 app with PostgreSQL. Take a look at code below. Is it possible to have race condition there? I am afraid I could get race condition on diff=-account.hours. Does transaction.atomic save from race condition? from django.db import transaction def write_off(account_ids): account = Account.objects.filter(id__in=account_ids) with transaction.atomic(): MyLog.objects.create( hours=0, operation_type=LOG_OPERATION_WRITE_OFF, diff=-account.hours, ) Account.objects.filter(pk=account.pk).update(hours=0) -
django group model extension duplicated key entry
I created a (second!) model that subclasses auth_models.Group: class SecondModel(auth_models.Group): display_name = models.CharField(max_length=48) class Meta: db_table = 'second_model' verbose_name = 'SecondModel' As mentioned above, there is already a first model the subclasses auth_models.Group in the same way (second -> first). Both models exist, FirstModel has entries and SecondModel as well. I now would like to add the subclassing to SecondModel. The generated migration part looks like this: migrations.AddField( model_name='second_model', name='group_ptr', field=models.OneToOneField(auto_created=True, default=1, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group'), preserve_default=False, ) Problem: when executing the migration script I get the following error: psycopg2.IntegrityError: could not create unique index "second_model_pkey" DETAIL: Key (groupl_ptr_id)=(1) is duplicated. .. django.db.utils.IntegrityError: could not create unique index "second_model_pkey" DETAIL: Key (group_ptr_id)=(1) is duplicated. I tried change the name put this does not solve anything. -
Post a form value to Django rest framework to retrieve json
How do i post a HTML form value from a django view to django-restframework view? I am constructing a Django application. It has an app called 'API' from this app i configured the urls.py as url(r'^programdetail/(?P<pk>[0-9]+)/$', ProgramDetail.as_view(), name='programdetail') when i visit http://127.0.0.1:8000/programdetail/1/ The program detail whose primarykey is 1 is displayed. I used the following code class ProgramDetail(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'test.html' def get(self, request, pk): pg = get_object_or_404(Program, pk=pk) serializer = ProgSerializer(pg) return Response({'serializer': serializer, 'data': pg.name}) Now i have a html form and a view to render it. The codes are <body> <h1>Programs</h1> {% csrf_token %} <form action ="" method="GET" novalidate> <select name="pk"> {% for program in programs %} <option value="{{ program.program_id }}">{{ program.name }}</option> {% endfor %} </select> <button type="submit">View</button> </form> </body> and the view i used is def programsform(request): progs = Program.objects.all() return render(request, 'allprograms.html', {'programs':progs}) This view gives me a HTML form that shows a drop down list of program names. Now the question is about action attribute. To which URL do i POST or GET these values to construct a the URL like http://127.0.0.1:8000/programdetail/{the posted program_id} and display them in my template. I tried posting these values to the same ProgramDetail class … -
How to show local time in template
I'm using PostgreSQL to store an object with a DateTimeField. The DateTimeField is using auto_now_add options. And it is created automatically from serializer in Django Rest Framework. As described in Django docs, I tried to get local timezone and activate it. from django.utils.timezone import localtime, get_current_timezone tz = get_current_timezone() timezone.activate(tz) session.started_at = localtime(session.started_at) In template index.html, I also try to load timezone. {% localtime on %} Session: start time {{ item.session.started_at }} {% endlocaltime %} In settings.py USE_TZ = True TIME_ZONE = 'UTC' I'm using GMT+7 timezone but it still shows UTC time on template. I'm using Django development server to test. Am I missing something?