Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Install requirements.txt on EC2, django APP
I am trying to install my django app on amazon EC2. for that I created a virtual env with sudo pip install virtualenv --> virtualenv env --> source venv/bin/activate Now when I try in install my requirements.txt I get a permission error: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/SoftScores-Final/venv/lib/python2.7/site-packages/appnope' Consider using the `--user` option or check the permissions. so I tried to use --user as mentioned in the error message but I get then : Can not perform a '--user' install. User site-packages are not visible in this virtualenv. I am kind of lost could you please help me to figure it out ? thx you ;) -
Set the DATABASE_URL environment variable
I am trying to create my own kind of project structure by looking at two scoops of django. The project structure looks something like this .envs .local .django .postgres .production .django .postgres in postgres inside local, the following items are listed POSTGRES_HOST=postgres POSTGRES_PORT=5432 POSTGRES_DB=marketing POSTGRES_USER=username POSTGRES_PASSWORD=password DATABASE_URL=postgres://username:password@localhost:5432/marketing the settings file is divided into 3 parts as base.py, local.py and production.py in base.py, I have configured the DATABASES key as following DATABASES = { 'default': env.db('DATABASE_URL'), } However I am getting an error django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable Though, I have DATABASE_URL in .envs/.local/.postgres, I am getting above error. Why is that so? -
How to serialize field from intermediate model into the main model of a many to many through relationship?
I am using django 2 with Django Rest Framework and I have the following models: class Product(models.Model): name = models.Charfield() description = models.TextField() class ProductStorageCenter(models.Model): product_id = models.ForeignKey(Product) storage_center_id = models.ForeignKey(StorageCenter) quantity = models.IntegerField() class StorageCenter(models.Model): name = models.Charfield() city = models.ForeignKey(City) products = models.ManyToManyField(Product, through="ProductStorageCenter") I would like to know which products I have in each StorageCenter and also the quantity of a product available in that StorageCenter. How could show a list of StorageCenters containing all its Products and the quantity of each Product for that StorageCenter? The JSON return would be like this: [ { "id": 1, "name": "My Storage Center", "city": 1, "products": [ { "id": 1, "name": "My Product 1", "description": "My Product Description 1", "quantity": 200 }, { "id": 2, "name": "My Product 2", "description": "My Product Description 2", "quantity": 500 } ] }, { "id": 2, "name": "My Storage Center 2, "city": 2, "products": [ { "id": 1, "name": "My Product 1", "description": "My Product Description 1", "quantity": 350 } ] } ] -
How to make this particular rendered content in HTML as downloadable text file in Django?
<div class="container" > {% if sr %} {% for k in sr %} <p>Name: {{k.name}}</p> <p>Email: {{k.email}}</p> <p>Contact Number: {{k.contact_number}}</p> {% endfor %} {% endif %} </div> THis is my html code and it is rendering perfectly when executed but i tried writing a function to download the rendered content as text file. And it is downloading the html code as text file not the actual rendered content. Please help me fix this. Thanks in advance. -
how to save csv file in static folder in django?
I want to save a csv file in django static folder. I tried creating a file named 'data.csv' in my app, but the file is saved in base directory. Where and how can I most easily save a csv file in django? file=open('data.csv','w') header='product_name,Price,seller\n' file.write(header) -
Legacy database and Django?
I have a small legacy database on my sytem, which is maintained by an applacation on my Raspberry Pi3. I am updating this legacy database very 30 seconds. I have a completely separate application utilising Django framework where I wish to update a web page with information from this database every 30 seconds. What I have done so far. I followed this tutorial to import the database into Django. I know how to query the database using QuerySelect. In SQL terms, a QuerySet equates to a SELECT statement, What I am asking: I had to integrate my legacy database with Django manually. Thus the manage.py file described by the tutorial above was created manually. Since data is being added on to this database continously, is there a way to access the data being added after the first manual integration? Other information, not necessarily relevant: According to the official docs: If you do want to allow Django to manage the table’s lifecycle, you’ll need to change the managed option above to True (or simply remove it because True is its default value). -
Django inline formset validation
I have the following models: class CaseForm(ModelForm): class Meta: model = Case fields = '__all__' class ClientForm(ModelForm): class Meta: model = Client fields = '_all__' CaseClientFormset = inlineformset_factory(Case, Client, form=ClientForm, extra=0, max_num=2, min_num=1, validate_max=True, validate_min=True) When I fill in the top part of the form (caseform) it saves correctly. When I fill in the caseform and a clientform it saves correctly. If I fill in the caseform but partially fill in the clientform no validation appears to take place, and a case is saved and the client information goes missing and is never saved. class CaseCreateView(LoginRequiredMixin, AdviserExistenceMixin, CreateView): model = Case form_class = CaseForm def form_valid(self, form): context = self.get_context_data() clients = context['clients'] self.object = form.save() if clients.is_valid(): clients.instance = self.object clients.save() return super(CaseCreateView, self).form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.POST: context['clients'] = CaseClientFormset(self.request.POST) else: context['clients'] = CaseClientFormset() context['navbar'] = str(self.model.__name__).lower() return context The other issue I have is that despite specifying min_num=1 and validate_min=True, I appear to be able to save a case without a clientform being filled in. Any help would be appreciated. -
Django: Activation Email Not Automatically Logging User In
When a user clicks an account activation link, they are redirected to my activate view: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = CustomUser.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return redirect('/') else: return HttpResponse('Activation link is invalid!') For some reason, when they are redirected with redirect('/'), they are not automatically logged in, i.e., in the index template, user.is_authenticated is False. If anybody knows why this is, and could help me automatically log the user in after clicking the activation link, I would be very grateful for their help. Thanks, Jack -
Setting virtualenv and install Django (MACOSX)
I don't know why I can't create virutalenv for my projects. I create the folder and type the command to install Django pipenv install Django But I have an error I can't identify what is it. Warning: the environment variable LANG is not set! We recommend setting this in ~/.profile (or equivalent) for proper expected behavior. Creating a virtualenv for this project... Pipfile: /Users/pedrosantos/Desktop/helloworld/Pipfile Using /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 (3.6.6) to create virtualenv... ⠋Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pipenv/pew/main.py", line 8, in import pew File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pipenv/patched/pew/init.py", line 3, in from . import pew File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pipenv/patched/pew/pew.py", line 44, in from pew._utils import (check_call, invoke, expandpath, own, env_bin_dir, File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pipenv/patched/pew/_utils.py", line 25, in encoding = locale.getlocale()[1] or 'ascii' File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/locale.py", line 581, in getlocale return _parse_localename(localename) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/locale.py", line 490, in _parse_localename raise ValueError('unknown locale: %s' % localename) ValueError: unknown locale: UTF-8 Virtualenv location: Creating a Pipfile for this project... Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/bin/pipenv", line 11, in sys.exit(cli()) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 722, in call return self.main(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 697, in main rv = self.invoke(ctx) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 1066, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File … -
How to compare text area widget inputs?
I'm new to Django and would appreciate any help! I have created a Text Area ModelForm, that I have added twice to my website template. Like so: I'd like to compare the contents of these two text areas using Python code that I have already written but I'm unsure how to read this data in. Any ideas? forms.py: class HomeForm(forms.ModelForm): textInput = forms.CharField(required=False, widget=forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'Input text...', } )) class Meta: model = Post #import Post model from home models.py fields = {'textInput',} #comma required to ensure tuple capability views.py: class HomeView(TemplateView): template_name='home/home.html' def get(self, request): form = HomeForm posts = Post.objects.all() args = {'form': form, 'posts': posts} return render(request, self.template_name, args) def post(self, request): form1 = HomeForm(request.POST) form2 = HomeForm(request.POST) if form1.is_valid(): form1.save() if form2.is_valid(): form2.save() #post = form.save(commit=False) #saves data (thanks to the model form) #comit is false as object still needs to be modified #post.user = request.user #post.save() #return redirect('home:home') args = {'form': form1, 'form': form2} return render(request, self.template_name, args) -
Alternative to blocktrans tag with long `with` clause
Context I'm trying to use the django template engine to render translatable part of a page using variable from the context. Specifically, this is my use case {% blocktrans trimmed with type=training.type title=training.title city=training.city %} Training {{ type }} "{{ title }}" at {{ city }} {% endblocktrans %} This works fine, however, my issue with it that the blocktrans length grows very quicky above the acceptable (at least, for me). As an alternative, I could do {% with training.title as title %} {% with training.type as type %} {% with training.city as city %} {% blocktrans trimmed %} Training {{ type }} "{{ title }}" at {{ city }} {% endblocktrans %} {% endwith %} {% endwith %} {% endwith %} Or using one separate with clause. But that does not really ease the readability of that code, especially if there is more variables to expose to the translation string. Solution I thought of My initial idea was to extends the blocktrans tag onto several lines : {% blocktrans trimmed with type=training.type title=training.title city=training.city %} Training {{ type }} "{{ title }}" at {{ city }} {% endblocktrans %} Unfortunately for me, django does not support multilline tags in … -
Set DataTimeField model field value to timezone.now + timezone.timedelta(hours=another_model_field)
I am trying to add an end date to an advertisement: class AdvertisePost(Post): ... duration = models.IntegerField(default=48) finish = models.DateTimeField(blank=False, null=False, default=timezone.now + timezone.timedelta(hours=duration)) The duration is the number of hours the advertisement is supposed to run. So I want finish to equal the creation time of AdvertisePost + duration. I have attempted to do this with: finish = models.DateTimeField(blank=False, null=False, default=timezone.now + timezone.timedelta(hours=duration)) I was told default=timezone.now is to be used instead of default=timezone.now() as the latter will return the current time and not the time of creation. As for the other part of the field, hours=duration is returning the following error: TypeError: unsupported type for timedelta hours component: IntegerField Any idea how I can go about getting finish to be a date object that equals the creation time of AdvertisePost + duration? -
How to set periodic task on Django using celery?
My current code: from celery.task.schedules import crontab from celery.decorators import task, periodic_task @periodic_task(run_every=crontab(hour=15, minute=55, day_of_week="wed")) def demo(): print("testing------------------------") It's not working, Am i missing something, Thanks In advance -
Postgresql type bytea not displaying text in html
In my postgresql db i have the following fields: Field O is of type bytea called "File" and X is called "Document_name". When I call for that column to be displayed in my html file, it shows what i think is hex format: <tr> <td>{{ item.Document_name }}</td> <td>{{ item.File }}</td> </tr> test <memory at 0x7fecefe9e1c8> Document_name <memory at 0x7fecefe9e288> Document_name <memory at 0x7fecefe9e348> Document_name <memory at 0x7fecefe9e408> Proposal Document <memory at 0x7fecefe9e588> test <memory at 0x7fecefe9e4c8> How do I make it so it displays the text I see in my DB e.g. User_storeis_for_PTK.docx instead of memory at 0x7fecefe9e288 -
Django CreateView how to save multiple rows in form_valid()
I use CreateView with the following form_valid method: def form_valid(self, form): """ This method is called when valid form data has been POSTed. """ # Update related model kommentar, created = models.Kommentar.objects.get_or_create( kommentar=form.cleaned_data['kommentar'], bruger=self.request.user ) # Insert foreign key to related model model = form.save(commit=False) model.kommentar = kommentar # Save the form and keep the return value (the value of get_success_url) success_url = super(ForventetRegnskabCreate, self).form_valid(form) for i in range(12): self.object.maaned = i + 1 form.save() messages.success( self.request, constants.CREATE_FORVENTET_REGNSKAB_SUCCESS_MESSAGE % self.object.beloeb ) return success_url I would like to save not one, but twelve copies of the object to be saved in the database. Each object represents a month of the year. This is why I put in the for loop with range(12). How can this be done "the right way"? Currently this is what I know: Bulk create is the right way to insert multiple objects, however, it does not insert the primary key for AutoFields (which I am using) - this applies to my backend at least. Can the primary key be inserted anyways? I could copy the object after it is inserted and then insert the copied object. This seems to be inefficient. Raw SQL - yet not really … -
Installing screen reader
I am creating new web page which includes accessibility control tools. Actually I am not web developer I am doing this because I fall in love with creating web pages. I have a question how I should include screen reader on my webpage? -
Django - Rpy2 code in Django App
I want to write following code in Django App. What is the best way to write rpy2 code in Django (rows--> from database) filterdata= filterdata=pd.DataFrame(rows,columns=col_names) r_dataframe = pandas2ri.py2ri(filterdata) func=robjects.r(""" ff <- function(d) { --- function def --- }""") df=func(r_dataframe) df = pandas2ri.ri2py(df) -
DRF Specify required Header
Is there a way to specify a required custom header for specific View classes? On an API I am working, some information are passed using headers and I need to return BAD_REQUEST or similar if a header is missing. I can think of ways of implementing it using mixins, but not sure if there is something in place that already does it. -
Django - ChatterBot
I want to integrate chatterbot as a Django-APP chatbot in my existing Django application. My application structure is : Now, their is a chatbot folder, i want to do everything for chatbot in that directory. in a different view page such as "http://127.0.0.1:8000/chatbot". Would anyone help me for this, I am new to this. In my settings.py, i have added : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gameplay', 'player', 'crispy_forms', 'chatterbot.ext.django_chatterbot' ] and in my urls.py : urlpatterns = [ path('admin/', admin.site.urls), # path('player/', include('player.urls')), url(r'^player/', include('player.urls')), url(r'^games/', include('gameplay.urls')), path('', welcome, name="tictactoe_welcome"), url( r'^chatterbot/', include('chatterbot.ext.django_chatterbot.urls', namespace='chatbot') ), ] Now, when i am running python manage.py runserver, i am getting following error : Please suggest and correct me, Thanks. -
Django modles: @property
Is there are 'rule' when to add @property and when not? Both works fine, so I am looking for another rule or best practice. view.py order_items_qty = self.ticket.sold_tickets vs. order_items_qty = self.ticket.sold_tickets() models.py @property def sold_tickets(self): return self.attendees.filter(canceled=False).count() -
Django | using compare variables in template
Its my table.html {% for table in table_data %} <tr> {% for data in table_fields %} <td>{{ table.data }}</td> {% endfor %} </tr> {% endfor %} I want to show all values in my tables from databases in one template. My data variable collect name of column (id, username, email etc.), when im using for example table.id, table.username in my code everything works fine, but i want to automatize this. So there is any possibility to connect table and data variables to show my results, or should i try another solution. -
Queries with LIKE (sql) equivalent in Python and string description
I want to make a query in python using the equivalent of LIKE in sql. So for I've been using the __contains option like this : results = objectName.objects.filter(variable__contains='someword') But now I want to put a constraint on the variable like : filter(variable__contains='_A%') and it doesn't work :( Does someone know how to do this ? -
Update value of a certail column in django post_save signals
I have a class Video whose structure is as below: class Video(models.Model): video = models.FileField(upload_to="media_items/video", blank=True) video_mp4 = models.CharField(blank=True, max_length=500) def __unicode__(self): return unicode(self.video.name) or u'' and signals.py is as @receiver(post_save, sender = Video) def insert_video_mp4(sender, instance, created, **kwargs): if os.path.exists(created_path): #some code else: #some code to insert value in video_mp4 column I want to update the value of video_mp4 as explained above in post_save signals. Please let me know how to achieve this. -
How to change default sqlite3 of Django to another version in centos6.1
I have installed two versions of sqlite3: /usr/bin/sqlite3 is version 3.6.20 /usr/local/bin/sqlite3 is version 3.24.0 Now , I wanna change my sqlite3 version3.6.20 to 3.24.0 used by my Django. How to do it ? Thanks for first! -
Django calculate cumulative sum of a column from database
I have a column in db, say amount Amount 1 2 3 4 5 Now i have to find a cumulative sum of amount and store in database column name cum_sum I already had created cum_sum column in db So my cum_sum column in db will be, cum_sum 1 3 6 10 15