Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
psycopg2-binary failing to install in docker container
Apologies for newbie question. I've tried all of the answers from other questions here but the don't pay off either. Dockerizing my python/django app with Postgres is proving... daunting. I'm getting the error "Error: pg_config executable not found." consistently when it starts working through my requirements.txt Here's the Dockerfile: FROM python:3.8.3-slim-buster ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD ./ /code/ ...and my requirements.txt... asgiref==3.3.1 Django==3.1.4 psycopg2-binary==2.7.4 pytz==2020.5 sqlparse==0.4.1 django-compressor>=2.2 django-libsass>=0.7 When I run docker-compose up --build I'm getting this error over and over: Step 6/7 : RUN pip install -r requirements.txt ---> Running in e0fd67d2d935 Collecting asgiref==3.3.1 Downloading asgiref-3.3.1-py3-none-any.whl (19 kB) Collecting Django==3.1.4 Downloading Django-3.1.4-py3-none-any.whl (7.8 MB) Collecting psycopg2-binary==2.7.4 Downloading psycopg2-binary-2.7.4.tar.gz (426 kB) ERROR: Command errored out with exit status 1: command: /usr/local/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-fha1c65p/psycopg2-binary/setup.py'"'"'; __file__='"'"'/tmp/pip-install-fha1c65p/psycopg2-binary/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-ewxlxmh6 cwd: /tmp/pip-install-fha1c65p/psycopg2-binary/ Complete output (23 lines): running egg_info creating /tmp/pip-pip-egg-info-ewxlxmh6/psycopg2_binary.egg-info writing /tmp/pip-pip-egg-info-ewxlxmh6/psycopg2_binary.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-ewxlxmh6/psycopg2_binary.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-ewxlxmh6/psycopg2_binary.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-ewxlxmh6/psycopg2_binary.egg-info/SOURCES.txt' Error: pg_config executable not found. -
Django sys.exectuable not running in production mode
Code beneath takes an image and runs it through a python script. Everything works great locally. On production mode it does not seem to run (Droplet on digital ocean). I have tried to debug this as much as i can but i cant seem to retrieve anything of use... import sys from subprocess import Popen, PIPE, STDOUT, run class ImageViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): parser_classes = (JSONParser, MultiPartParser, FormParser,) queryset = UploadImageTest.objects.all() serializer_class = ImageSerializer def post(self, request, *args, **kwargs): self.create(request, *args, **kwargs) inp = request.FILES.get('image').name out = run([sys.executable,'//Users//macbookpro//mywebapp//myprojectenv//Script.py',inp],shell=False,stdout=PIPE, text= True) if out.returncode == 0: stat = 'Success' else: stat = 'Fail' data = { 'info': out.stdout, 'status': stat, } return JsonResponse(data, status=status.HTTP_200_OK) The only difference on the production server is the path below which could be incorrect. out = run([sys.executable,'//mywebapp//myprojectenv//Script.py',inp],shell=False,stdout=PIPE, text= True) On the production server the code above returns as "Fail" which means that it is being processed. For the Script i don't get any feedback. Either the path is faulty or the script is. however i'm not sure how to check if the Script is attempting to run but failing. Any help would be appreciated. -
Django Suggested Pages by User Tracking
I have a project I'm working on similar to a website like Game Informer to try to learn more of django. So I have a section of the website for a blog, for videos, for reviews, and for news. Each has its own model. I'd like to associate a tagging system with each of these models, probably using a many to many field to a model that just contains tags. The part that I'm struggling with is figuring out how I could use this tagging system to generate a list of suggested articles for users that are logged in. I thought about creating a model with a foreign key to the user and a foreign key to the post, then in the view logic, create an object and save it to the model with the user and page visited. But I'm not quite sure how I would access the tags that this person visited the most. I'm also curious if there's a way that I can add more weight to the certain tags if a user has liked a post with those tags and less weight if they've disliked. Any ideas, suggestions, or guidance would be greatly appreciated. I'll post … -
Saving form data upon social login
I'm using Django Allauth. I have few social login buttons (Google, Twitter, Facebook). I also have a form if the user wants to sign up via email. The form contains a hidden field that contains the App ID (if they are on an Android device). If they sign up via email, I have made a way where I can capture that information through the POST request. However, how do I capture this hidden field's data and pass into a social adaptor so that I can save this App ID. class SocialAccountAdapter(DefaultSocialAccountAdapter): def authentication_error(self, request, provider_id, error=None, exception=None, extra_context=None): messages.error(request, "An error occurred while attempting to login via your social media account.") raise ImmediateHttpResponse(redirect('/login/')) def save_user(self, request, sociallogin, form=None): user = super(SocialAccountAdapter, self).save_user(request, sociallogin, form) print(self.request.GET) //This doesn't work, but this is what I've tried Is there a way I can get this local value passed along when a user does social sign up? -
Django create Datepicker field in HTML Template
I am looking to create a datepicker field along with other existing search fields in my HTML template. I am looking for how to create datepicker and initialize it to show calendar. I have looked at all other forums on web and all give options to add datepicker widget in the form and then call form in your template. I want to directly create datepicker in template along with all my other fields in template. Can you please suggest? -
is there an alternative to the way i am doing it ? any help will be appreciated
[https://pastebin.com/1EB5FuAZ][1] I need help, I am new to Django and I am following a tutorial on building a program but when I enter I data to the form. it doesn't input it into my MySQL database and it seems like it is the code that is in breaking it. After I have enter my data to my form and submit it takes me to the error page but when i remove the error it displays I output it couldn't add the data. -
Django Email Templates Rendering as Text
I am using trying to use the Django Dynamic Email Templates over SendGrid API. I understand there are some threads on this already, however I have not been able to get these to work. I have a basic template with some dynamic variables based on searches that I want emailed to the user. This is all works except the html is always rendered in text despite applying what I have seen in a number of other threads here. Would be grateful for any help here. Views.py def customer_selections_sent(request): #make=request.POST['makeselection'] if request.method == 'GET': current_site = get_current_site(request) emailto = request.user.email_user user = request.user.username #call session values from SearchInventory function modelvalue =request.session.get('modelvalue') makevalue =request.session.get('makevalue') subject = 'ShowVroom Selections' #create variables to be used in the email template Email_Vars = { 'user': user, 'make': makevalue, 'model': modelvalue, #'offer': DisplayInventory.GaragePrice, 'domain': current_site.domain, } #create the email msg message = get_template('customer_selections_email.html').render(Email_Vars) message.content_subtype = "html" # Main content is now text/html #send email request.user.email_user(subject, message) #return redirect('customer_selections_sent') return render( request, 'customer_selections_sent.html', { 'title':'Deals are on the way', 'body':'We will email you shortly with more detail on your choices, you can respond to the dealers via the app until you agree to a viewing, test or purchase … -
How to have the choices for a Django Model object come from the corresponding instance of another model?
I am trying to set the choices for a Child field equal to two choices that are fields that come from the Parent class that it's related to (each child only has one parent). How do I access these values? class Parent(models.Model): attribute1 = models.CharField(max_length=100) attribute2 = models.CharField(max_length=100) class Child(models.Model): choices_in = [{{ Parent.attribute1 }}, {{ Parent.attribute2 }}] parent = models.ForeignKey(Parent, on_delete=models.CASCADE) item = models.CharField(max_length=100, null=True, choices=choices_in) -
Is it safe to edit the django-allauth translation files?
I want to edit the django-allauth translation files. When I first opened the en django.po file, PyCharm gave the message: This file does not belong to the project. If I edit the file, is it going to cause problems that I don't want or can I edit the translation without messing something up? -
validation error not seen in template form using form
validation error is not shown before also when i created form using form api i send error but is does not appear in html and now also when created User using UserCreationForm now also error not appered in html submitting this form without fillig single field. views.py file from django.shortcuts import render from .forms import signup # Create your views here. def sign_up(request): fm = signup() if request.method == 'POST': fm = signup(request.POST) if fm.is_valid() : print('until this runs') fm.save() else: fm = signup() print(fm.errors) return render(request, 'at/signup.html', {'form': fm}) forms.py file from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class signup(UserCreationForm): class Meta: model=User fields=['username','first_name','last_name','email'] html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>user regisration</title> </head> <body> {% if messages %} <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} <form action="" method='POST' novalidate> {% csrf_token %} {{form.as_p}} <input type="submit" value='submit'> </form> <form action="" method='POST' novalidate> {% csrf_token %} {% for fm in form %} {{fm.label_tag}} {{fm}} {{fm.errors|striptags}} <br> <br> {% endfor %} <input type="submit" value='submit'> </form> </body> </html> -
How to use Primary Key in Django context view to render on html in python for loop
I have this method in my views followed by my html: `def index(request): context = { "user": User.objects.get(id = request.session['user_id']), "book": Book.objects.all(), "review": Book.objects.get(pk=1).book_reviews.all() } return render(request, "books_home.html", context) {% for Book in book %} {{Book.contributor.id}}<br> Book Title: <a href="{{Book.id}}">{{Book.title}}</a><br> Author: {{Book.author.name}}<br> Contributor: <a href="{{Book.contributor.id}}">{{Book.contributor.first_name}} {{Book.contributor.last_name}}</a><br> {% for book_reviews in review %} <a href="{{User.id}}">{{book_reviews.poster.first_name}} {{book_reviews.poster.last_name}}</a> says: {{book_reviews.content}}<br> Rating: {{book_reviews.rating}}<br> Posted on: {{book_reviews.created_at}}<br> {% endfor %} {% if Book.contributor.id == request.session.user_id %} <a href="reads/{{Book.id}}/delete">Delete All</a>{% endif %} <hr>` I'm having a problem with "review": Book.objects.get(pk=1).book_reviews.all(), the pk=1 is the problem. I don't know how to run through each pk so that each review is rendered, not just those with pk=1. -
Django-mailer customizing admin area
When using django mailer (https://github.com/pinax/django-mailer) I realized that the default tables added to the admin area (such as Message logs and Messages) did not add the message_log field which indeed is available if one looks at the tables that are added. Since the error message is very valuable to me I wanted to add it, and simply added the "log_message" to the app's MessageLogAdmin like this: class MessageLogAdmin(MessageAdminMixin, admin.ModelAdmin): list_display = ["id", show_to, "subject", "message_id", "when_attempted", "result", "log_message"] list_filter = ["result"] date_hierarchy = "when_attempted" readonly_fields = ['plain_text_body', 'message_id'] search_fields = ['message_id'] However, is there really no other way to customize the admin area for django-mailer other than modifying the source code? E.g through settings.py -
Success_url = "detail/int:pk"
class EditBlog(UpdateView): model = Entry template_name = 'entry/edit.html' success_url = "/" fields = ['entry_title', 'entry_text'] def form_valid(self, form): form.instance.entry_author = self.request.user return super().form_valid(form) i want to put in my success URL the name of the path because the URL of my detail page has a PK with it and it's not working the way i want -
django circular import in models
I understand I have a circular import here, but one of them is being used to define some foreign key fields and the other is only there for a property in the other model. models: receipts/models.py from django.db import models from employees.models import Employee class Receipt(models.Model): Supervisor = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='receipt_supervisor') Employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='receipt_employee') amount = models.DecimalField(max_digits=6, decimal_places=2) employees/models.py from django.db import models from receipts.models import Receipt class Employee(models.Model): number = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) @property def receipt_sum(self): receipts = Receipt.objects.filter(Employee=self.pk) sum = 0 for receipt in receipts: sum += receipt.amount return sum I get this error: cannot import name 'Employee' from partially initialized module 'employees.models' (most likely due to a circular import) Is there a way I can get around this so that I can do the receipt query in the Employee property? Or do I need to do this calculation elsewhere? Thanks! -
How load (server-side) localhost webpage from web server?
How can I load a web page running on http://localhost:9001 from my website on http://localhost:9000? Currently the website loads the client's localhost. -
understanding memory in jsonb based querysets (to write to file)
I am trying to write a Django queryset to a file and although it works, it consumes a LOT of RAM and I am not able to write out the entire field values because it runs out of memory. Let me explain my setup: instance_model=SomeModel.objects.all().order_by('created_at') print(instance_model()) # outputs 1million or so entries Now, I start to write out the field values I am interested in like so: with open("write_prices.dat", 'w') as file_handler: for item in prices_model: for each_item in item.prices: #prices is a JSONB field if each_item['symbol']=="PS2": file_handler.write("{}\t{}\n".format(\ item.utc_timestamp['utc_time'],\ each_item['price'])\ ) my models.py looks like so: class SomeModel(TimeStampedModel, AbstractPS2Model): prices = JSONField(blank=True,default=dict) utc_timestamp = JSONField(blank=True,default=dict) def __str__(self): return self.uuid When I try to write out the fields in prices I am interested in, I am hardly able to iterate through 15k or so DB entries - before the script gets killed because of OOM. I assumed everything was a generator and I did not have to worry about memory, but obviously my understanding seems wrong. I think I am doing something super silly here, but I am not able to figure out what :( -
Django and celery DatabaseError: DatabaseWrapper
I build a scraper and the price needs to be updated every 12 hours or so and i use celery to do it, but i get an error after the task is received: django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with al ias 'default' was created in thread id 48931120 and this is thread id 89001448 @shared_task def update_price(): scraper = Scraper.objects.all() for i in scraper: price = amazon_scraper(i.link) i.update(last_price = price, last_checked = timezone.now()) time.sleep(18) /settings.py CELERY_BEAT_SCHEDULE = { 'update_price': { 'task': 'hackaton.tasks.update_price', 'schedule': datetime.timedelta(seconds=120), }, } -
How to display manytomany field in django admin with a related model in a user-friendly way?
I'm struggling to display a manytomany field in the admin with the related model in a user-friendly manner. The project is already up and running so adding a through table is not preferred. The set-up is something along these lines; class User(AbstractUser): is_member_of_organization = models.ManyToManyField(Organization, blank=True, verbose_name=_("is member of organization(s)"), related_name='orgmembers') class Organization(models.Model): name = models.CharField(max_length=60, verbose_name=_("organization name")) the only reasonable way I manage to display the related users with organization admin is via a TabularInline admin.py class UserOrgAdminInLine(admin.TabularInline): model = User.is_admin_for_organization.through extra = 0 @admin.register(Organization) class OrganizationAdmin(admin.ModelAdmin): inlines = (UserOrgAdminInLine,) However, looking up users is not convenient as soon as their number increases. I would like something similar to filer_horizontal but I am not sure how to include it directly in the OrganizationAdmin admin class. Furthermore, I am using fieldsets (which I believe should have no special rules or syntax to it compared to ordinary fields = . One little subquestion - in the tabular inline, when I use only model = User django throws an error that there is no foreign key to it, but when I use the additional .is_admin_for_organization.through it works, but there is no through table and I though that this work just in that … -
initialize modelform fields with url parameters in cbv
I have a cbv create view that displays a modelform. I want to preselect a foreignkey field which is displayed as select choice field. My problem is that kwargs.get('building_id') in modelform returns None class VlanCreateForm(ModelForm): class Meta: model = Vlan fields = ['number','description','network','building'] def __init__(self, *args, **kwargs): building_id = kwargs.get('building_id') super().__init__(*args, **kwargs) self.fields['building'].initial = building_id building is a foreign key to buildings. If I put a constant like self.fields['building'].initial = 1 it is working class VlanCreateView(CreateView): model = Vlan form_class = VlanCreateForm and the url is vlan/building/<int:building_id>/create so I call it like vlan/building/1/create -
Django Serializers running slow to convert JSON
I have 5 different Foreign Key values in 1 model. There are 1800 records in total. Using AJAX it is necessary to convert the data to JSON format. I can do this with the Serializers library. I use use_natural_foreign_keys = True for Foreign Key values to return string values. use_natural_foreign_keys = True When i use it; 15 seconds of query When I am not using it; 0.5 second But I have to use it. Otherwise, I cannot get Foreing Key values when converted to JSON format. I leave the query here. How can I make queries faster? Thanks in advance. result=AbcModel.objects.all() if kapanan_talepler: jsons=serializers.serialize('json',result, use_natural_foreign_keys=True) -
Django Static Images Not Loading
I have images downloaded in the following path but they refuse to load for me. Any idea what I may have configured incorrectly that is forcing this? C:\Users\xxx\Python\Price Tracking\Django\mysite\polls\static\polls\images stl.jpg chicago.jpg nyc.jpg settings: INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_plotly_dash.apps.DjangoPlotlyDashConfig', ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_URL = '/static/' html: {% load static %} <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="{% static 'polls/chicago.jpg' %}" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="{% static 'polls/nyc.jpg' %}" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="{% static 'polls/stl.jpg' %}" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> -
Are you required to make an http request when trying to use Chart.js?
I followed a tutorial video that showed how to set up Chart.js with Django, using Jquery and API function calls to a page on my site. However, I don't need to make these function calls to get the data, as the data are associated with my objects themselves. When I get rid of the http function call and just write the code instead, my graphs don't show up. Is the http format required? A working version I have is: <script> var endpoint = ''/api/chart/data/''; fetch(endpoint, { method: "GET", }).then(response => response.json()) .then( data => { console.log('Success:', data); ... var ctx{{ forloop.counter }} = document.getElementById("myChart{{ forloop.counter }}"); var myChart = new Chart(ctx{{ forloop.counter }}, graph_data); }) .catch((error) => { console.log("Error:") console.log(error); }); </script> <div style="width: 60%; float:left;"> <canvas id= "myChart{{ forloop.counter }}" style = "padding-bottom: 9px;"></canvas> </div> Could this instead just be: console.log('Success:', data); ... var ctx{{ forloop.counter }} = document.getElementById("myChart{{ forloop.counter }}"); var myChart = new Chart(ctx{{ forloop.counter }}, graph_data); <div style="width: 60%; float:left;"> <canvas id= "myChart{{ forloop.counter }}" style = "padding-bottom: 9px;"></canvas> </div> The error I am getting is Chart.min.js:14 Uncaught TypeError: Cannot read property 'length' of null at Object.acquireContext (Chart.min.js:14) at new t.Controller (Chart.min.js:11) at new t (Chart.min.js:12) … -
Django-Haystack not finding any field
I am trying to write a little search engine with django-haystac and whoosh. I adapted their tutorial, I've created my index from and query it succesfully with QueryParser and now I'm trying to use their view. when I try to access the search url at: http://127.0.0.1:8000/my_search/ I get the error: The index 'BookIndex' must have one (and only one) SearchField with document=True. If I remove the search_indexes.py I can access the search page, but then of course it does not work as it doesn't have any index to search. By debugging it it seems it does not pickup any fields, but it does see the class. I tried several things but nothing worked my search_indexes.py: from haystack import indexes from my_search.models import Paper class BookIndex(indexes.SearchIndex, indexes.Indexable): """ This is a search index """ title = indexes.CharField(model_attr='title'), abstract = indexes.CharField(document=True, use_template=False, model_attr='abstract'), def get_model(self): return Paper def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects # .filter( pub_date__lte=datetime.datetime.now()) my models.py: from django.db import models class Paper(models.Model): paper_url = models.CharField(max_length=200), title = models.CharField(max_length=200), abstract = models.TextField() authors = models.CharField(max_length=200), date = models.DateTimeField(max_length=200), def __unicode__(self): return self.title thanks! -
Django Prepopulate ModelForm with Table Record
I am trying to create an Edit for that allows the user to scroll through a table and click a button existing in each row to edit the data within a modal. The issue that I am running into is when I try to prepopulate the form with the existing values. How would I convert the EditCommunicationsForm below to display the current values of the row that you selected edit for? forms.py class CommunicationsForm(forms.ModelForm): class Meta: model = Communications fields = "__all__" widgets = { 'project':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter your Project Name'}), 'title':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter a short Title'}), 'intent':forms.Textarea(attrs={'class': 'form-control','height':'50px','placeholder':'Describe the intent and desired outcome of the communication'}), 'date':forms.TextInput(attrs={'class': 'form-control','placeholder':'Select a Date'}), 'channel':forms.Select(attrs={'class': 'form-control'}), 'content_type':forms.Select(attrs={'class': 'form-control','placeholder':'Select a Content Type'}), 'audience':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter the Audience(s)'}), 'status':forms.Select(attrs={'class': 'form-control','placeholder':'Select the Status'}), } class EditCommunicationsForm(forms.ModelForm): class Meta: model = Communications fields = "__all__" widgets = { 'project':forms.TextInput(attrs={'class': 'form-control','initial':'Project 123'}), 'title':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter a short Title'}), 'intent':forms.Textarea(attrs={'class': 'form-control','height':'50px','placeholder':'Describe the intent and desired outcome of the communication'}), 'date':forms.TextInput(attrs={'class': 'form-control','placeholder':'Select a Date'}), 'channel':forms.Select(attrs={'class': 'form-control'}), 'content_type':forms.Select(attrs={'class': 'form-control','placeholder':'Select a Content Type'}), 'audience':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter the Audience(s)'}), 'status':forms.Select(attrs={'class': 'form-control','placeholder':'Select the Status'}), } views.py def communications(request): comms_list = Communications.objects.order_by('id') if request.method == "POST": new_form = CommunicationsForm(request.POST, request.FILES) edit_form = EditCommunicationsForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('http://127.0.0.1:7000/polls/communications/',{"new_form":new_form,"edit_form":edit_form,'comms_list':comms_list}) else: … -
Expire a token in 24 hours - django-rest-knox
I am using django-rest-knox for token authentication in my Django REST Framework app. What I want is to make the token expire only if 24 hours are passed. Is there any setting that it can make this thing happen. Thanks