Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my pagination not working? (Django)
I've been working with Django-Listviews and I used paginate_py in a class to get some pagination going. But it'll just show all the items. This is the class: class PostListView(ListView): model = publicaciones template_name = 'store/search.html' context_object_name = 'queryset' ordering = ['Promocionado'] paginate_by = 2 def get_queryset(self): qs = self.model.objects.all().order_by('id') search = self.request.GET.get('q') if search: qs = qs.filter(Título__icontains=search) return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) MyFilter = PubFilters(self.request.GET, queryset=self.get_queryset()) context['filter'] = MyFilter context['filtered_items'] = MyFilter.qs context['count'] = self.get_queryset().count() context['búsqueda'] = self.request.GET.get('q') return context Please tell me if I need to post anything else, like filters.py and so on. Thanks in advance! -
FILE PATH can't open with TOKEN in MOD HEADER - UNABLE TO OPEN S3 BUCKET FILE [DJANGO REST]
I've created a REST API app in Django REST. Through it you can upload files to a server, tag them etc. I have connected an S3 AWS bucket as the storage system. The problem is. The app has a token authentication set up. So you get to upload files only if authenticated. BUT when you want to open the file (click on the json link in the displayed data), you have to turn off your mod header with the authentication token, because otherwise it messes up with the opening and tries to input the token in constantly. And this is the better option, for it to at least open like that I had to make the bucket completely public. So the reality is, you post files, with the token authentication on. You can access the api only with the auth token on. But whenever you would want to open a file, you have to turn off the mod header which results in you checking and unchecking the mod header token constantly like an idiot if you want to browse api + open files. Plus because the bucket is public, anybody could see your files... not ideal REST API Serialized data … -
Django: How can I add an aggregated field to a queryset based on data from the row and data from another Model?
I have a Django App with the following models: CURRENCY_CHOICES = (('USD', 'US Dollars'), ('EUR', 'Euro')) class ExchangeRate(models.Model): currency = models.CharField(max_length=3, default='USD', choices=CURRENCY_CHOICES) rate = models.FloatField() date = models.DateField() class Donation(models.Model): date = models.DateField() donor = models.CharField(max_length=250) amount = models.FloatField() currency = models.CharField(max_length=3, default='USD', choices=CURRENCY_CHOICES) I also have a form I use to filter donations based on some criteria: class DonationFilterForm(forms.Form) min_amount = models.FloatField(required=False) max_amount = models.FloatField(required=False) The min_amount and max_amount fields will always represent values in US Dollars. I need to be able to filter a queryset based on min_amount and max_amount, but for that all the amounts must be in USD. To convert the donation amount to USD I need to multiply by the ExchangeRate of the donation currency and date. The only way I found of doing this so far is by iterating the dict(queryset) and adding a new value called usd_amount, but that may offer very poor performance in the future. Reading Django documentation, it seems the same thing can be done using aggregation, but so far I haven't been able to create the right logic that would give me same result. -
When running Django tests using Travis CI, my tests are running and completing locally, but are not running (or being found) remotely
As per the question, I have two tests which I am running successfully on my local machine. Running "python manage.py test" in the command line produces the following output: Creating test database for alias 'default'... System check identified no issues (0 silenced). .. ---------------------------------------------------------------------- Ran 2 tests in 0.495s OK Destroying test database for alias 'default'... These tests are part of a project which is currently residing in a GitHub repository. This repository is linked to Travis CI, and as such, a travis.yml file can be found in the repository's root directory. The contents of the file are as follows: language: python install: - python -m pip install -r requirements.txt before_script: - cd TNI_Project script: - python manage.py test For reference, the "TNI_Project" directory is the one which contains the "manage.py" file, and the "requirements.txt" file contains the output of pip freeze. However, once the build is launched on Travis CI, the build exits with 0, but none of the tests are run. The exact output can be found below: $ python -m pip install -r requirements.txt before_script 0.00s$ cd TNI_Project 0.41s$ python manage.py test System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK The … -
Django models many to many relation adds automatically
I have a model class like this. When I create a student, the django automatically adds all courses to student. class Course(models.Model): course_name = models.CharField(max_length=25) is_open = models.BooleanField(default=True) def __str__(self): return self.course_name class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) EXP = ( ('1', 'Unexperienced LA'), ('2', 'Experienced LA'), ('3', 'Unexperienced TA'), ('4', 'Experienced TA'), ('5', 'DEFAULT'), ) courses = models.ManyToManyField(Course,null=True) exp = models.CharField(max_length=1, choices=EXP) -
Elasticsearch_dsl in django - unable to use password
I want my Django application to use a password for connecting to the elasticsearch container. Therefor I set a connection string in my settings.py which was working fine until I setup password authentication for elasticsearch. Currently I get the following error from Django: elasticsearch.exceptions.AuthenticationException: AuthenticationException(401, '') Using curl like this is working fine inside the container: curl -u "${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD}" "${ELASTICSEARCH_HOST}:${ELASTICSEARCH_PORT" But if I set the same env. vars. for the ELASTICSEARCH_DSL config at my settings.py, I simply fail and cannot establish a connection to elasticsearch due to the auth. failure mentioned above: ELASTICSEARCH_DSL = { 'default': { 'hosts': env.str('ELASTICSEARCH_USERNAME') + str(':') + env.str('ELASTICSEARCH_PASSWORD') + str('@') + env.str('ELASTICSEARCH_HOST') + str(':') + env.str('ELASTICSEARCH_PORT') }, } Is the syntax here maybe wrong for : or @ at the connection string? I already searched the docs and web on this but was not able to find a solution till now. -
nginx configuration with multiple location blocks + React +Nginx
I'm trying to configure nginx for 2 different location. i here is my scenario. www.example.com location : /var/www/example.com example.com/panel location : /var/www/example.com/panel -
How would you get RDKIT to load into an Apache Wampserver for Windows when conventional methods are not working?
RDKIT is the only package not loading into our production server. We successfully set up a Wampserver too run Apache and host our Django project . . .but have to comment out all the code associated with rdkit for it to work. This inhibits many required features. There were no issues using rdkit in Django's test server. Primary wsgi error: from .rdBase import rdkitVersion as __version__\r, referer: http://localhost/APP/ ImportError: DLL load failed: The specified module could not be found.\r, referer: http://localhost/APP/ Relevant packages and version details: Windows 10 Django 2.2 Python 3.7 conda 4.8.2 rdkit 2019.09.3 conda-forge Wampserver 3.2 Apache 2.4.41 mod-wsgi 4.7.1 The methods in this blog describe how we setup the production server. With one minor change, we did not alter the httpd_vhosts.conf file and only setup the standard localhost. The error is reproducible by trying to import rdkit(or one of its methods) into any file needed to host a web application in the described environment. We found this 2016 thread on the rdkit sourceforge and it sounds like someone else was having a similar problem on a Linux system. This is our first time setting up a server and we have not been successful at translating the … -
Multiple Headers in a Python CSV File
I am trying to append rows into columns that I have created using different csv writers and it works well until I try to send it as an email. for school_area in school_areas: sarea = [sar for sar in SchoolArea.objects.filter(school__contains=school_area.city)] csvio = StringIO() header = ['Name', 'Age', 'School', 'Marks', '', 'Name', 'Age', 'Rank'] writer = csv.writer(csvio) writer.writerow(header) csvblank = StringIO() blankheader = [''] blankwriter = csv.writer(csvblank) blankwriter.writerow(blankheader) csvioo = StringIO() headerr = [ '','Total','Average','Median','', 'Total in Class', 'Average in Class', 'Median in Class'] writerr = csv.writer(csvioo) writerr.writerow(headerr) csvioheader = StringIO() header2 = ['Name', 'Age', 'School', 'Marks', '', 'Name', 'Age', 'Rank'] headerwriter = csv.writer(csvioheader) headerwriter.writerow(header2) alert = False alert_list = [] sum_dif_school, sum_dif_uni, classtot, unitot = 0, 0, 0, 0 for school in sarea: data = school_helper() datafill = school_name() row = [] brow=[] drow = [] if data['reports'] > 0.01 or data['reportsuni'] > .01 : row.append(school.name) row.append(round(data['reports'],1)) row.append(round(data['reportsuni'], 1)) row.append('') #blank column if data['reports_school'] > .01 or data['reports_uni'] > .01: row.append(round(data['reports_school'], 1)) row.append(round(data['reports_uni'], 1)) if dif_d > .5 or dif > .5 or dif_d < -.5 or dif < -.5: alert = True alert_list.append(school.name) if data['school'] > 0.01 : brow.append('') brow.append(round(data['total_marks'], 1)) brow.append('') brow.append(round(data['total_reports'], 1)) if data['school'] > 0.01 : … -
Why won't the runserver command in the terminal run? I am (a complete beginner) working on building a web app (learning log) with Django
So I've already created and activated a virtual environment, created a project, and an app (but the app shouldn't really matter at this point). I'm trying to view my project and ran the server command but it won't run. To clarify, I had already made more progress with the web app: created a model and migrated it so i could use it in the app, viewed the project as an admin to see the model working but when i created the second model, i had trouble migrating it. so i took a few steps back to the point where I could just view the empty project and that also didn't work so i'm confused. I could just delete and start over but I'd like to know what's wrong at this point. Below is what the terminal shows when I tried to run 'runserver' command so I could view the project on my local server. C:\Users\acer>cd Desktop/programming/learning_log C:\Users\acer\Desktop\programming\learning_log>ll_env\Scripts\activate (ll_env) C:\Users\acer\Desktop\programming\learning_log>python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line … -
What is Django equivilant to Rails initializers folder?
I have a script for a discord bot that I need to use in a Django App so I can reference the DB and Models from it. The goal is to dynamically output messages to discord based on records. In Rails with the discord gem: https://github.com/discordrb/discordrb I am able to add my script to the initializers folder. This way it starts up and it's always listening. When something like a message or command comes through, I can dynamically update the output message based on the information from the command or message from Discord. Here is my app\config\initializers\discord_bot.rb file: require 'discordrb' bot = Discordrb::Bot.new token: '<>' bot.message(with_text: 'Ping!') do |event| task = Task.find(1) event.respond "Pong! #{task.title}" end bot.run I can access the models from here. This is a quick example but if I wanted, I can check against the discord information I receive to dynamically respond with the bot information from the database records. How am I able to do something similar to this in Django? -
Views/ Django How to read file and show on the page information from file cvs
Please help me to write code to show some values from the cvs file on site. This is my views.py in Django project. On the site views working and show all information from the file.But I need show info by searching for some value and show me line with this value. views.py from django.http import HttpResponse def index(response): with open('news_rss/data.csv', 'r+', encoding='windows-1251') as file: response = HttpResponse(file.readlines()) for line in file: word = 'Contract' if word in line != -1: return (line) return response Somebody can help me to understand how to write correctly this.Thanks a lot -
Passing non form data from Django Template to view
I am working for the contacts app in Django Framework. It sends Otp using Twilio API. Now to send an OTP the view send_message will be called. This view will generate OTP through a random process. Now it will render an HTML template to show that this OTP is going to be sent. If the user clicks to send a new view send_otp will be called that will send the OTP to the recipient. Now My question is how would I get the same value of OTP in the second view that is passed from the first view to the template. Since in the second template I need to send the OTP. Views.py #first view def send_message(request, id): with open('contacts/contact_data.json', 'r') as f: contact_list = json.load(f) for contact in contact_list: if (contact['id'] == id): otp = generate_random_otp() context = { 'otp':otp 'message':text_message, 'id':id } return render(request, 'send_message.html', context) return render(request, 'send_meassage.html', {}) #second view def send_otp(request, id): #I need to pass OTP to this function send date = send(id, otp) return render(request, 'about.html') def send(id,otp): client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) with open('contacts/contact_data.json', 'r') as f: contact_list = json.load(f) for contact in contact_list: if (contact['id'] == id): message = client.messages \ .create( … -
docker-compose up: path does not exist
I use Windows 7 Just follow my Django-project readme, but all I get is: -
Django REST Framework with viewset-router queryset filter
I want to do data filtering in a api response. Ie make such addresses /api/v1//CoinCost/full?coin_id=coin_name&dateStart=2020-02-06T00:00:00&dateEnd=2020-02-08T00:00:00 now i have this url /api/v1/CoinCost/ And no filtering. My code: views.py class CoinCostViewSet(viewsets.ViewSet): def list(self, request): queryset = Coins.objects.all() serializer = CoinSerializer(queryset, many=True) return Response(serializer.data) urls.py router = DefaultRouter() router.register('coins2', CoinCostViewSet, basename='Coins') urlpatterns = [ path('', include(router.urls)), ] serializers.py class CoinCostsSerializer(serializers.ModelSerializer): class Meta: fields = ('coin_id', 'crr', 'volume', 'reserve', 'price', 'timestamp') model = CoinCost models.py class CoinCost(models.Model): coin_id = models.ForeignKey(Coins, on_delete=models.CASCADE) crr = models.CharField(max_length=3) volume = models.DecimalField(max_digits=19, decimal_places=4) reserve = models.DecimalField(max_digits=19, decimal_places=4) price = models.DecimalField(max_digits=19, decimal_places=4) timestamp = models.DateTimeField(auto_now_add=True, blank=True) Please help make the necessary filtering. To get filtering url. I’ve been sitting for two days, I don’t understand.I studied a lot of documentation and tried different methods for a week now. But didn’t help . Thanks! -
Is it possible to have an abstract model inside another abstract model in Django/Djongo?
I'm trying to add a model class with abstract=True in meta to another abstract class. But the data is not being saved in the DB. I use MongoDB as the backend. MongoDB does support this. Is this not allowed in Django? or Djongo? -
DJango user-profile - Each time that I modify a user's profile a new profile is created
This is likely a basic question, but I'm new to django . . . I'm building a quiz app that allows users to answer questions in order. For example, users can only answer question 2 after they have successfully answered question one. I'm using django.contrib.auth for user authentication, and have added a Profile model for extended User info, including keeping track of all of the questions each user has answered. Here are my models: class Question(models.Model): question_text = models.CharField(max_length=400) answer1 = models.CharField(max_length=200) times_solved = models.IntegerField(default=0) number = models.IntegerField(default=1, unique=True) def __str__(self): return self.question_text class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) real_name = models.CharField(max_length=100) questions_answered = models.ManyToManyField(Question, blank=True, null=True) last_wrong_answer_made_on = models.DateTimeField('last wrong answer date', null=True, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I also have an index view that lists all of the users along with the number of the last question that they have answered: class IndexView(generic.ListView): template_name = 'piratehunt/index.html' context_object_name = 'user_list' def get_queryset(self): return Profile.objects.all().order_by('-questions_answered__number') And my index.html: {% if user_list %} <ul> {% for user in user_list %} <li><a href="{% url 'piratehunt:user_detail' user.id %}">{{ team.user.username }} - {{ user.questions_answered.last.number }}</a></li> {% endfor … -
Representing the arc of a circumference in Django
So, my goal here, is to calculate the measurement of the arc, and here goes my question. How do I represent that in HTML using Django? def PartOfCircumference(angle): radius = 5 circumference = math.pi * radius * 2 part_of_circumference = angle / 360 measurement = float(circumference * part_of_circumference) return measurement -
Cannot import name 'smart_unicode'
I am deploying my application on production server, it all works fine in local. However on production I ma getting cannot import name 'smart_unicode' whenever I try to access myip/admin The app was written in django 1.8, and I migrated it to django 2.2 usr/local/lib/python3.6/dist-packages/cache_utils/utils.py in , line 2 Issue is it crashes in a library, then to know where in my code. -
I am getting error when deploying django app on heroku
app[web.1]: usage: gunicorn [OPTIONS] [APP_MODULE] app[web.1]: gunicorn: error: argument --error-logfile/--log-file: expected one argument here is my procfile web: gunicorn data_list.wsgi --log-file how can I handle this problem? -
UserVote matching query does not exist
So, I'm working on matching two users if they vote yes to each other, and then storing them in a database based on if they match, and then displaying them. If I manually add the users through admin, that works fine. But I am having trouble getting the users to match. I'm a django newbie and I feel like I made a mistake building my own user model as it's much more of a headache when dealing with the models. I am getting error and I can't figure out what's going on here: error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 144, in nice return create_vote(request, profile_id, True) File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 159, in create_vote vote=vote File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get self.model._meta.object_name dating_app.models.UserVote.DoesNotExist: UserVote matching query does not exist views.py def create_vote(request, profile_id, vote): profile = Profile.objects.get(pk=profile_id) UserVote.objects.create( user = profile, voter = request.user, vote = vote ) return redirect('dating_app:mingle') def nice(request, profile_id): return create_vote(request, profile_id, True) def nope(request, … -
Pagination Error in Django: object of type 'Custom Filter' has no len()
I am having a few issues with Django pagination. I keep getting object of type 'Custom Filter' has no len()` error. I don't know why I keep getting this error. Although I have the premonition that the error may have been triggered due to my use of filter.qs. Anyone with a suggestion on how this can be resolved? views.py def crm(request): #filtering the customer queryset customers_list = ProspectiveCustomer.objects.all() customers = CustomerFilter(request.GET, queryset=customers_list) has_filter = any(field in request.GET for field in set(customers.get_fields())) #pagination paginator = Paginator(customers_list, 10) # Show 10 customers per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) try: customers_list = paginator.page(page_number) except PageNotAnInteger: customers_list = paginator.page(1) except EmptyPage: customers_list = paginator.page(paginator.num_pages) return render(request, 'crm/crm.html', { ... 'page_obj': page_obj, 'filter': customers, 'has_filter': has_filter, }) template <!--Filter customers--> <div class="container search-container"> <form method="get"> <div class="form-row"> <div class="form-group col-md-4"> {{ filter.form.customer_name|as_crispy_field}} </div> <div class="form-group col-md-4 filter-col"> {{ filter.form.email|as_crispy_field}} </div> <div class="form-group col-md-4 filter-col"> {{ filter.form.city|as_crispy_field}} </div> </div> <button class="btn btn-warning" type="submit"><i class="fa fa-search"></i> Search</button> {% if has_filter %} <a class="btn btn-secondary" href="{% url 'crm' %}" type="submit"> <i class="fas fa-times"></i> Clear filter </a> {% endif %} </form> </div> <div class="container customer-container"> <h5 class="page-header">Prospective Customers</h5> <table class="table table-striped table-hover" id="prospective-customer-table"> <thead class="thead-dark"> <tr> <th>#</th> … -
Using a background image in Django using static and variable
I've seen a lot of these types of questions but none are using a {{ variable_name }} in the html using background. For context, I'm trying to insert a unique photo as a background image for every page. <heading id="background-image" style="background-image: url({% static 'img/pattern.jpg' %});"> This will work for a specific background image, "pattern", but I want it to be dependent on a variable for that specific page. The following code will import the correct image on the page, but it needs to be turned to a background image (so that I may put text in front) <img src="{% static 'img/' %}{{ item.name }}.jpg" alt="item picture"> -
Is nginx server called a forward proxy when used with react
Just trying to clarify some terminology here. When I use nginx to serve a Django API, the nginx server is called a reverse proxy. When I use nginx to serve a React application, is the nginx server called a forward proxy, or is it called something different? -
Python3 and django3 Google Business API Error
I have the following code in python 3 and django 3. I have all previous google api steps done documented in the API, when I run my server I can finish the process and obtain a credential access_token, But when I try to use it it fails when I try to execute a request to business API methods. from django.http import HttpResponseRedirect, from googleapiclient.discovery import build from google.oauth2.credentials import Credentials import google_auth_oauthlib.flow from django.views.decorators.clickjacking import xframe_options_exempt from .models import GoogleCredentialsModel CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') SCOPES = ['https://www.googleapis.com/auth/business.manage',] @xframe_options_exempt def auth_request(request): user = User.objects.get(id=request.user.id) # request.user flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS, SCOPES, ) flow.redirect_uri = settings.GOOGLE_BUSINESS_CALLBACK authoritation_url, state = flow.authorization_url( # # Enable offline access so that you can refresh an access token without # # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # # Enable incremental authorization. Recommended as a best practice. include_granted_scopes='true', # # ask always if consent prompt='consent' ) return HttpResponseRedirect(authoritation_url) @xframe_options_exempt def auth_return(request): state = request.GET["state"] code = request.GET["code"] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS, SCOPES, state=state) flow.redirect_uri = settings.GOOGLE_BUSINESS_CALLBACK try: flow.fetch_token(code=code) user = request.user user = TSMUser.objects.get(id=user.id) if GoogleCredentialModel.objects.filter(user=user).exists(): gcred = GoogleCredentialModel.objects.get(user=user) gcred.set_data(Credentials(**flow.credentials)) else: GoogleCredentialModel.objects.create(user=user, credential=Credentials(**flow.credentials)) service = build('business', 'v4', discoveryServiceUrl='https://developers.google.com/my-business/samples/mybusiness_google_rest_v4p5.json', credentials=flow.credentials) list = service.accounts().list().execute() …