Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
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 -
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 … -
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() … -
How to mock private method from parent class in python
I'm trying to mock 'private' method from parrent class. I would like to make the private method raise a custom exception (or return True in other case). Here is my code: class Machine: def __init__(self, some_param): self.some_param = some_param def __private_method(self, input): ... class ChildMachine(Machine): def __init__(self): super().__init__(param) def public_method(self, input): return self.__private_method(input) And here are my tests: from django.test import TransactionTestCase from mock import patch import pytest import custom_lib @pytest.mark.django_db class TestClass(TransactionTestCase): @patch('custom_lib.Machine._Machine__private_method') def test_public_method(self, mock_private): mock_private.side_effect = exceptions.CustomException() machine = custom_lib.ChildMachine('TEST') with self.assertRaises(exceptions.CustomException): machine.public_method('TEST') However this raises an exception: AttributeError: <class 'custom_lib.Machine'> does not have the attribute '_Machine__private_method' Thanks in advance. -
ERROR: lxml-4.5.0-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform
I am trying to install some packages required for weasyprint that is Pango and Cairo for my Django project. I have downloaded both packages to the file system. The file names are as follows: 1.lxml-4.5.0-cp36-cp36m-win_amd64.whl 2.pycairo-1.19.1-cp38-cp38-win_amd64.whl 3.pygtk-2.22.0-cp27-none-win_amd64.whl I am on 64 bit windows 10 system,I have a 32-bit python 3.7.3 installed on the machine.I am also working on Django 3.0.But whenever I try installing the packages using pip i.e pip install lxml-4.5.0-cp36-cp36m-win_amd64.whl, it throws the errors below. ERROR: lxml-4.5.0-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform. ERROR: pycairo-1.19.1-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. -
Django: How to let user decide with checkboxes what categories of images they want to see?
I want to create some kind of gallery. My Image model has two choice-fields: cat1 = models.CharField(max_length=250, choices=(('g1',"Game1"), ("g2", "Game2"), ("g3", "Game3"), ("g4", "Game4"))) cat2 = models.CharField(max_length=250, choices=(('type1',"Drawn"), ("type2", "Computer graphic"), ("type3", "Pixelart"))) I want to let the user click on checkboxes "Game1, Pixelart", then on "Show!" button and the whole page then reloads to show images having both of those categories (so only Pixelarts from Game1). How should the view and template look like? -
How to use extends tag in django templates?
Hi I am stuck at extending template in django. I have a base file called auth_layout.html which contains: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Question Time</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Lora&display=swap" rel="stylesheet"> {% block style %} {% endblock %} </head> <body> {% block content %} {% endblock %} </body> </html> and there is another template called login.html which contains: {% extends 'auth_layout.html' %} {% load crispy_forms_tags %} {% block auth %} <h1> Question Time </h1> <p class ="lead text-muted"> Share Your Knowledge! </p> <div class="login-form-container"> <form method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-sm btn-outline-primary">Login</button> </form> </div> {% endblock %} My project directory is something like this: QuestionTime QuestionTime templates users (app) manage.py and here is my template settings in settings.py:- 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', ], }, }, ] The problem is that it is not extending my auth_layout.html file. Whenever i hit the login endpoint it shows an empty page. On commenting the extend statement, html content of login.html is shown. How can I fix this? -
How to implement WishList on Django
I'm trying to implement a couple of this on my website but don't know how to go about it. First of all i'm trying to add a wishlist for my product and ratings, if you know how to implement any of this could you please help me thank you. class Category(models.Model): name = models.TextField() slug = models.SlugField(null=True, unique=True) products = models.ManyToManyField('Product') image = models.ImageField(upload_to='imagess/', blank=True) def get_products(self): return Product.objects.filter(category=self) def __str__(self): return self.name def get_absolute_url(self): return reverse('product_list_by_category', args=self.slug) class Product(models.Model): name = models.TextField() slug = models.SlugField(null=True, unique=True) description = models.TextField() stock = models.SmallIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='images/', blank=True) image2 = models.ImageField(upload_to='images/', blank=True) image3 = models.ImageField(upload_to='images/', blank=True) image4 = models.ImageField(upload_to='images/', blank=True) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('single',args=[self.id, self.slug]) -
How to see what an object contains in Django
I am working in Django with PyCharm and I have a simple model that look like so: class Test(models.Model): description = models.CharField(max_length=255, null=True, blank=True, verbose_name=_("description")) start_date = models.DateTimeField(null=True, blank=True, verbose_name=_("start date")) end_date = models.DateTimeField(null=True, blank=True, verbose_name=_("end date")) And a simple form that look like so: import datetime from django import forms from . import models from django.utils.safestring import mark_safe class TestForm(forms.ModelForm): class Meta: model = models.Test def clean(self): cleaned_data = super().clean() if cleaned_data.get("start_date"): starting_date = cleaned_data["start_date"] print(starting_date) t = datetime.date.today() print(t) g = datetime.datetime.combine(t, datetime.time.min) print(g) if starting_date < g: raise forms.ValidationError(mark_safe(_("The starting date is before today's date."))) When I am trying to debug my code, I would like to see the content of different objects (cleaned_data, t, g ect) so I can understand why my code is not working. How do I do that ? -
How to solve a string to data conversion problem on a Django template
I have a string to data conversion problem on a Django template. I'm trying to take a string (of a date) and calculate the days since that date; so it says something like "1 month, 2 weeks (since all time high date)". The string to date conversion is working fine, the problem is on the Django template. The template currently shows only the last date from the json data request for each item in returned in the for loop. Obviously I need the date for each specific record converted and displayed. I've formatted the string from the json data request into date object. Currently only the last item in the list is being sent as the days_since_ath_formatted variable. Here's the Django view def: coin_list_url = f"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page={per_page_limit}&page=1&sparkline=false" request_coin_list = requests.get(coin_list_url) results_coin_list = request_coin_list.json() crypto_data_geckco = [] #string to date conversion def to_string(time): return time.strftime('%Y %M %d') def from_string(date, formatting): dt = datetime.datetime.strptime(date, formatting) return dt #for loop for currency_gecko in results_coin_list: days_since_ath = currency_gecko['ath_date'] days_since_ath_formatted = from_string(days_since_ath[:-14], "%Y-%m-%d") print('days since ath formatted', days_since_ath_formatted) crypto_data_geckco.append(currency_gecko) print("crypto_data_geckco", crypto_data_geckco) return render(request, 'crypto/latest.html', { 'crypto_data_geckco': crypto_data_geckco, 'days_since_ath_formatted': days_since_ath_formatted} ) and then on the Django template: {% for currency in crypto_data_geckco %} All-Time Percentage: {{ currency.ath_change_percentage|intword … -
How to make condition inside mutation to restrict mutation if hero dupliacates in the same draft?
I`m not able to understand how to make statement so if I make draft 1 and I have two heroes with same ID (or name, for example 'Spectre') it will restrict mutation with an error: 'You can have same hero in the draft' Bolded text inside user_draft.py is unused because I dont know were or how to make condition. Inside mutate before I save it or? user_draft.py import graphene from graphene_django import DjangoObjectType from user_draft.models import UserDrafts from users.schema import UserType from heroes.schema import HeroType from users.models import User from heroes.models import Hero class UserDraftType(DjangoObjectType): class Meta: model = UserDrafts class Query(graphene.AbstractType): all_drafts = graphene.Field(lambda: graphene.List(UserDraftType)) def resolve_all_drafts(self, info): return UserDrafts.objects.all() class CreateDraft(graphene.Mutation): message = graphene.String() user = graphene.Field(UserType) hero = graphene.Field(HeroType) class Arguments: draft = graphene.Int() hero = graphene.ID() user = graphene.ID() @staticmethod def mutate(self, info, draft, user, hero): hero_id = Hero.objects.get(id=hero) user_id = User.objects.get(id=user) **error_message = 'You cant duplicate heroes' draft_error = 'You can only pick 1, 2 or 3.'** draft_data = UserDrafts.objects.create( draft=draft, hero=hero_id, user=user_id, ) draft_data.save() return CreateDraft( message='You created ur hero pool successfully' ) class Mutation(graphene.ObjectType): create_draft = CreateDraft.Field() So inside my CreateDraft mutation I want to be able to restrict user not to have … -
Heroku Django error: SSL certificate has expired
How do I make my free Heroku site work? I did not change it from the time it was working to when it stopped working. site code When I opened my site, I got an "Application Error" page. I followed its instructions. I ran the Heroku CLI command "heroku logs --tail" and got an error. I then ran "heroku logs --tail --app moresomervillehappinessapp". Here are the last logs: 2020-04-06T20:49:47.204222+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/urllib/request.py", line 1320, in do_open 2020-04-06T20:49:47.204222+00:00 app[web.1]: raise URLError(err) 2020-04-06T20:49:47.204228+00:00 app[web.1]: urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108)> According to Heroku, I can use the "*.herokuapp.com" certificate for SSL. Should I try to get rid of the SSL certificate? I care a little bit about SEO, but not the security of user data. Software I used: Django 3.0.2, Python 3.8 -
How to add custom query / queryset to Django Admin?
I'm building a Django project and have a model called Animal. Something like: class Animal(models.Model): type = models.CharField() In the django admin interface I can easily see all animals which is awesome. However I would like to add 2 additional views to the admin so that I can see all animals of a certain type: For example if my Admin view could look like this: Animals -> Shows all animals (default) Animals (type == dog) -> Shows only dogs Animals (type == cat) -> Shows only cats Any advice or best practices on how to do this? Thanks. -
Can't log into heroku using bash command line for Django
I'm trying to deploy my first django app on heroku but i am not being able to do so. I have done pip install django-heroku and also done a pip freeze to requirements.txt . I also installed guincorn and psycopg2 according to a tutorial. All the installations are in a virtual env. I am currently using bash command line from windows (on vscode). When i do heroku login it shows bash: heroku: command not found. What should I do?