Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
touch: cannot touch 'Dockerfile': Permission denied
I am using the latest version of docker toolbox on windows 10 home and I am getting this problem everytime I run this command I get this error $ touch Dockerfile touch: cannot touch 'Dockerfile': Permission denied -
Execute Django command within Django variable
I would like to read a string from an excel-file with both HTML- and Django-Tags (e.g. "Your current < b > account balance </ b > is: {{ current_balance }}"). I then pass the variable from the python-file to the Django-template (name e.g. balance). When I try to call the variable in the Django-template using {{ balance }}, I get the displayed the whole variable as a string. If I use {{ balance | safe }} the HTML-tags are executed. Is there a way such that the Django tags get executed as well? -
django-allauth works fine on localhost but not on a server
i implemented all the steps for django-allauth to provide facebook login on my website. things went well and everything works fine,so i uploaded my website into pythonanywhere for testing, and after clicking on the login with facebook button, nothing happens! i did not get any errors or loading pages or any message back from facebook, even the new window for login with facebook did not pop up as usual! i did tried some methods that i could find like setting the app on live mode and adding the domain url, and none of this worked for me. this is my website: https://yahyastihi18.pythonanywhere.com/ is there any more steps that i don't know about? or any solution for this problem? -
Embed not working jupyter-notebook with django application
I am trying to embed Jupyter notebook to my react application. But when loading it is saying this site can't be reached and getting that error in jupyter shell I am running jupyetr inside djangi using python manage.py shell_plus --notebook Jupyter notebook shell: [I 15:07:36.235 NotebookApp] 302 GET /tree (127.0.0.1) 0.77ms [W 15:07:36.291 NotebookApp] Forbidden [W 15:07:36.292 NotebookApp] 403 POST /api/security/csp-report (127.0.0.1) 2.12ms referer=None Html code : <iframe width = "700" height=" 600" src="http://127.0.0.1:8888/tree"> </iframe> -
Where to put favicons in Django project?
I made a fav icon and ran it through a website to give me the different sizes and icons for different platforms. In my base.html file I have: <link rel="apple-touch-icon" sizes="180x180" href="{% static "apple-touch-icon.png" %}"> <link rel="icon" type="image/png" sizes="32x32" href="{% static "favicon-32x32.png" %}"> <link rel="icon" type="image/png" sizes="16x16" href="{% static "favicon-16x16.png" %}"> <link rel="manifest" href="{% static "site.webmanifest" %}"> <link rel="mask-icon" href="{% static "safari-pinned-tab.svg" %}" color="#5bbad5"> <meta name="msapplication-TileColor" content="#da532c"> <meta name="theme-color" content="#ffffff"> And at the top of the base.html page I have {% load static %} Rendering the page and pressing "view source" shows the links are good: <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-touch-icon.png"> All the icons are in myapp/myapp/static/myapp but it's giving me 404 errors. The static files in all my other apps work, but this being the coreapp did not previously have a /static/myapp directory. My settings.py file located in myapp/myapp/ has this in: STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' I've obviously missed something in setting up the coreapp static files, or I'm placing them in the wrong directory, I dunno. Any ideas? -
Django - Grouping instances in queryset by date not working
I have a queryset of instances, and I am trying to group the instances with the same date together, so that I can do some annotation (to ultimately sum the 'revenues' of those with the same date). However, it seems like even though the dates are the same for the instances, it is not grouping together, and is displayed as separate objects within the queryset after annotating the dates. Is there something that I am doing wrong? Below is the code. class RevenueForecast(models.Model): forecast_id = models.AutoField(primary_key=True) quantity = models.IntegerField() block = models.ForeignKey('BudgetBlock', related_name='forecasts', on_delete=models.CASCADE, null=True, blank=True) buy_price = MoneyField(max_digits=10, decimal_places=2) sell_price = MoneyField(max_digits=10, decimal_places=2) month = models.DateField(null=True, blank=True) project = models.ForeignKey('SalesProject', related_name='forecasts', on_delete=models.CASCADE) serializers.py (im using serializermethodfield) def get_revenue(self, obj): qs = RevenueForecast.objects.filter(project=obj).annotate(date=TruncMonth('month')).values('date') print(qs) qs = qs.annotate(rev=ExpressionWrapper(F('quantity') * (F('sell_price')), output_field=FloatField())) qs = qs.annotate(rev_sum=Sum('rev')) output from print(qs) <QuerySet [{'date': datetime.date(2020, 7, 1)}, {'date': datetime.date(2020, 7, 1)}, {'date': datetime.date(2020, 8, 1)}, {'date': datetime.date(2020, 7, 1)}, {'date': datetime.date(2020, 8, 1)}]> Is there any reason why it does not group those with the same dates together? Do guide me along, if I am doing anything wrong, or if there is a simpler way to achieve what I want to achieve. Thanks all! -
allow modifying django model fields to certain users
I am building a marketplace REST Api on DRF where there are Creators and Brands. Creators can publish their projects and brands can make offers. I have an AbstractUser class and class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=32, unique=True) first_name = models.CharField(max_length=32, blank=True) last_name = models.CharField(max_length=64, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) location = models.CharField(max_length=120, blank=True) bio = models.TextField(blank=True) is_creator = models.BooleanField(default=False) is_brand = models.BooleanField(default=False) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class Creator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Brand(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=64) projects-related models look like follows: class Project(models.Model): title = models.CharField(max_length=128, ) description = models.TextField() created_on = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=2, choices=CATEGORY_CHOICES) author = models.ForeignKey(Creator, on_delete=models.CASCADE) class ProjectOffer(models.Model): PENDING, NEGOTIATIONS, APPROVED, DECLINED = range(4) STATUS = ( (PENDING, 'Pending'), (NEGOTIATIONS, 'Negotiations'), (APPROVED, 'Approved'), (DECLINED, 'Declined'), ) title = models.CharField(max_length=128) description = models.TextField() author = models.ForeignKey(Brand, related_name='project_offers', on_delete=models.CASCADE) project = models.ForeignKey(Project, related_name='project_offers', on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) status = models.PositiveSmallIntegerField(choices=STATUS, default=PENDING) The issue is the following. The project offer is made by the brand. It is linked to a project. The brand should have the opportunity to update its offer, say title … -
How to setup gunicorn with nginx while using aws elastic beanstalk for a django app
I have searched through many resources but I haven't found a well-detailed way to set up a Django app on elastic beanstalk using Gunicorn and Nginx with RDS as a database. There are resources available for using it on ec2 machines directly but not through elastic beanstalk. What steps do I need to follow to make it happen Also some of the questions I have, Do we need Nginx when using Django with beanstalk? as beanstalk comes with its own load balancers I know Django comes with an admin panel which is not a part of Angular. If I were to serve an Angular app through s3 and CloudFront do we still need Nginx to serve static assets? how big of a role does nginx play here? How many processes/workers and threads are idle for a micro ec2 machine that comes with aws free tier? thank you in advance -
How to add a Snippet Description in Wagtail
I have been searching in the wagtail documentation and stack overflow to find the answer to my question to no avail. I am currently creating vehicle models using wagtail snippets but in the documentation they have a screenshot that shows their snippets have descriptions next to their titles. Does anyone know how to add descriptions to the snippets? I assume it goes in the Meta class in the model however I cant find the value I need to set the description to. Any advice would be greatly appreciated. -
how to get float from F() / F() in Django
qureyset = M.objects.annotate(count1=Count(...), count2=Count(...), rat=F('count1') / F('count2')) I find the rat is integer, not float. I need 'count1' / 'count2' is float. I do blow: -- 1. not work M.objects.annotate(count1=Count(..., output_field=FloatField()), count2=Count(..., output_field=FloatField()), rat=F('count1') / F('count2')) -- 2. not work M.objects.annotate(count1=Count(...), count2=Count(...), rat=Func(F('count1'), 2, function='round') / F('count2')) -- 3. not work in template {% withratio count1 count2 1 %} {% withratio count1|floatformat:2 count2 1 %} -- 4. not wrok again M.objects.annotate(count1=Count(..., output_field=FloatField()), count2=Count(..., output_field=FloatField()), rat=F('count1') * 1.0001 / F('count2')) -- 5. wrong M.objects.annotate(count1=Count(..., output_field=FloatField()), count2=Count(..., output_field=FloatField()), rat=float(F('count1')) / F('count2')) How should i do? -
Uvicorn ValueError if i try to reach the site
everyone. Uvicorn start throw such error after i try to open website, any idea how to fix? Thanks Jul 30 14:18:06 development gunicorn[16064]: 2020-07-30 14:18:06,810 asyncio ERROR Exception in callback UVTransport._call_connection_made Jul 30 14:18:06 development gunicorn[16064]: handle: <Handle UVTransport._call_connection_made> Jul 30 14:18:06 development gunicorn[16064]: Traceback (most recent call last): Jul 30 14:18:06 development gunicorn[16064]: File "uvloop/cbhandles.pyx", line 73, in uvloop.loop.Handle._run Jul 30 14:18:06 development gunicorn[16064]: File "uvloop/handles/basetransport.pyx", line 134, in uvloop.loop.UVBaseTransport._call_connection_made Jul 30 14:18:06 development gunicorn[16064]: File "uvloop/handles/basetransport.pyx", line 131, in uvloop.loop.UVBaseTransport._call_connection_made Jul 30 14:18:06 development gunicorn[16064]: File "/usr/local/lib/python3.6/dist-packages/uvicorn/protocols/http/httptools_impl.py", line 132, in connection_made Jul 30 14:18:06 development gunicorn[16064]: self.server = get_local_addr(transport) Jul 30 14:18:06 development gunicorn[16064]: File "/usr/local/lib/python3.6/dist-packages/uvicorn/protocols/utils.py", line 39, in get_local_addr Jul 30 14:18:06 development gunicorn[16064]: return (str(info[0]), int(info[1])) Jul 30 14:18:06 development gunicorn[16064]: ValueError: invalid literal for int() with base 10: 'r' -
Validate DateField data that depends on another DateField data in Django Form
I have recently starting to learn about Django. I am trying to make a SearchForm that takes as inputs: location number of person arrival_date departure_date I am hardly trying to make validations so that the arrival_date cannot be anterior to datetime.date.today() and the departure_date cannot be anterior to arrival_date. I managed to find this in the Django Doc but I don't understand it properly. I tried both ways in the doc, but I must missing something because I get a RunTimeError, super(): __class__ cell not found. It works fine to check the arrival date but I'm not sure it is the proper way. Can someone please explain to me how I can use the resource linked here to make my form validations work as expected? My POST requests: location 'Paris' nb_visitors '1' arrival_date '2020-07-30' departure_date '2020-07-29' My Form (forms.py): from django import forms from django.core.validators import MaxValueValidator, MinValueValidator from .validators import * import datetime class SearchForm(forms.Form): location = forms.CharField( label='Destination', min_length=3, max_length=40, widget=forms.TextInput(attrs={'placeholder': 'Paris'}) ) nb_visitors = forms.IntegerField( label='Nombres de Visiteurs', validators=[ MinValueValidator(0, 'Le nombre de visiteurs ne peut être inférieur à 0.'), MaxValueValidator(15, 'Pour une visite agréable, un groupe peut être composé de 15 personnes maximum.') ], widget=forms.NumberInput(attrs={'placeholder': '1'}) … -
I am getting JsonDecoderError raise JSONDecodeError("Expecting value", s, err.value) from None while making a wen application in Djnago
This is the code in my html for csrftoken: <script type="text/javascript"> var user='{{request.user}}' function getToken(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getToken('csrftoken'); </script> This is my html code for the button: <button data-product={{product.id}} data-action="add" class="btn btn-outline-info update-cart">Add to Cart</button> This is my cart.js(linked to html) var updateBtns = document.getElementsByClassName('update-cart') for (i=0;i<updateBtns.length;i++){ updateBtns[i].addEventListener('click',function(){ var productId=this.dataset.product var action=this.dataset.action console.log('productId:',productId,'Action:',action) console.log('user:',user) updateUserOrder(productId, action) }) } function updateUserOrder(productId,action){ console.log('User is logged In , sending data....') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, bode:JSON.stringify({'productId':productId,'action':action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:',data) }) } and this is my views.py from django.http import JsonResponse import json def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:',action) print('Product:',productId) return JsonResponse('Item was added',safe=False) I am making a webapp for the first time and I am using this json for first time … -
How to use add(), set() and clear() methods of ManyRelatedManager in Django ManyToManyField with a through class?
I have models as follows, Class Bank(models.Model): customers = models.ManyToManyField(Customer,'banks', through='bank_customer') Class Customer(models.Model): name = models.CharField(max_length=50) Class Bank_customer(models.Model): customer = models.ForeignKey(Customer,on_delete=models.CASCADE) bank = models.ForeignKey(Bank,on_delete=models.CASCADE) city = models.ForeignKey(City,on_delete=models.CASCADE) Class City(models.Model): name = models.CharField(max_length=100) How do I add Customer objects to Bank? The following does not work bank.customers.add(customer) Here bank and customer are saved instances of their classes. Doing this violates not_null constraint for city ForeignKey in Bank_customer table. -
displaying the output on chart.js using Django and HTML
I have data that i need to pass to HTML file to ctreate chart using chart.js heres the view.py [![enter image description here][1]][1] the commented code is to print only the data in text form on the HTML file heres the HTML file that i want to use on it the chart.js [![enter image description here][2]][2] can you give me an idea of how can I pass the data to work with chart.js do I need to conver it ? or can you suggest another way to visualize the data with stylish bar chart the data in form of dict heres sample of it {'values': [3, 1, 1], 'data_labels': [' data 1 ', ' data 2', ' data 3']} .. if have any details questions tell me please [1]: https://i.stack.imgur.com/crLZP.png [2]: https://i.stack.imgur.com/xlre5.png -
Django: form validation - date not past and date for user unique
I have a problem with defining form in Django (python 3.7, django 3.0.8) I create a model. This model has two very important fields: date and user_id. Requirement: date and user_id are unique. I create a form model to associated with the model. The logged in user completes the form and it is important that the defined date cannot be from the past and cannot appear in the database. My problems: My validation associated with date from the past work correct, but but if a past date is given, no error message is displayed. The second thing is that I have no idea how to prevent definition data, what it exist in database. Code: models.py class MyModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField() ...(other fields) class Meta: unique_together = [['user', 'date']] Code: forms.py class AddMyModel(forms.Form): date = forms.DateField(widget=DateInput(attrs={'type': 'date'}), ) def clean_date(self): date = self.cleaned_data['date'] if date < timezone.now().date(): raise ValidationError(self.error_messages['Date cannot be in the past'], code='Date cannot be in the past') return date Do you have any idea how to design the form to display the error "date cannot be from the past" and error "the given date is already defined"? -
Django: How to pass python variable value to javascript file?
I've a function in views.py which returns latitude and longitude: return render(request, 'map.html', {'lat_lng':lat_lng}) and I am able to access it in html file as {{ lat_lng }} but when I try to use lat_lng in separate js file then I'm not able to access it. I tried all below stack answers but none worked for me: Django Template Variables and Javascript Passing django variables to javascript How to use Django variable in JavaScript file? Passing Python Data to JavaScript via Django -
Django: What is the best way to do a datafix operation?
I have an application where agents create some users in the application. Think of the following scenario; class Customer(model.Model): field_1 = models.CharField(max_length=20) field_2 = models.CharField(max_length=10, null=True, blank=True) field_3 = models.CharField(max_length=50, null=True) field_4 = models.CharField(max_length=50) field_5 = models.CharField(max_length=10, null=True) field_6 = models.CharField(max_length=10, null=True) field_7 = models.CharField(max_length=50, null=True) So, these agents doesn't really care what information they are filling in, we have some validation in place on some fields but that's not helping. After every few weeks we receive a request from Data quality office to improve the data so they can generate reports accordingly. These requests can be of different types like capitalise all the words in field_1, or if there's no value in field_2 then field_3 must always be empty. And these request can involve thousands of records. Right now, we write a management command to do the bulk update or update in database based on the logic and run it. But now the team is looking for more structured and standard way of doing these kind of datafixes as if something goes wrong it will impact a lot. -
no ReserveMatch found for seemingly correct path converter
I have the following anchor in my HTML template <a href = "{% url 'app:pages:experiments_tables_foreign_key' data.0 col.1 col.2 col.3 %}"> {{col.1}} </a> and the following line within urls.py path('experiments/<str:table_name>/<uuid:foreign_key>/<str:foreign_attribute>/str:foreign_table_name>/', ExpViews.show_foreign_key, name='experiments_tables_foreign_key') show_foreign_key exists in views.py and is a function that I'd like to use for a view. It accepts 4 parameters. I have the correct namespace done aswell. I get the following error: Reverse for 'experiments_tables_foreign_key' with arguments '('test_2', UUID('7a4c1cb5-6a7c-4fd3-8eea-8e9bef41802d'), 'ID', 'test_1')' not found -
change datetime format using tempus_dominus DateTimePicker
I installed and imported DateTimePicker and used it as a widget to a Django DateTime Field When clicking on the field it shows me the date and time in format 07/30/2020 4:33 PM. However, the model is not accepting the input because it needs to be in format : 2020/07/30 16:33. Any ideea how to manipulate de Model form widget to show this format? forms.py: from django import forms from .models import BlogPost from tempus_dominus.widgets import DatePicker, TimePicker, DateTimePicker class BlogPostModelForm(forms.ModelForm): publish_date = forms.DateTimeField( widget=DateTimePicker( options={ 'useCurrent': True, 'collapse': False, # Calendar and time widget formatting 'time': 'fa fa-clock-o', 'date': 'fa fa-calendar', 'up': 'fa fa-arrow-up', 'down': 'fa fa-arrow-down', 'previous': 'fa fa-chevron-left', 'next': 'fa fa-chevron-right', 'today': 'fa fa-calendar-check-o', 'clear': 'fa fa-delete', 'close': 'fa fa-times' }, attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, } ) ) class Meta: model = BlogPost fields = ['title','image', 'slug', 'content', 'publish_date'] def clean_title(self, *args, **kwargs): instance = self.instance print('instance is: ',instance) title = self.cleaned_data.get('title') qs = BlogPost.objects.filter(title__iexact=title) if instance is not None: qs = qs.exclude(pk=instance.pk) # id=instance.id if qs.exists(): raise forms.ValidationError("This title has already been used. Please try again.") return title forms.html: <!doctype html> {% extends "blog/base.html" %} {% load static %} {% load crispy_forms_tags %} {% … -
Getting data from a Django model inside a datetime range
What if I want to get the orders from 10:30 pm of DAY-1 to 9:30 of DAY? Where DAY is the chosen day. time_purchased = models.DateTimeField(default=datetime.datetime.now) -
how i can display the data in django app as soon scraper gets it
guys I want to build a site that uses the eCommerce website's search engine (like: amazon.ca and newegg.ca ) to get product based on what user searched and show it on a single page. So I want to display the data as soon it gets. So far I have created a 'search' app and in utils.py I have my classes (amazon and NewEgg) and a forms.py that has single Charfield. so when I make the request it took to much time because in the background scrapers are getting data which is bad because sometimes requests got a timeout. sorry for bad English thanks in advance. -
File "manage.py", line 16 ) from exc (( SOLVED ))
IF enter image description here In case of anyone having the same trouble as me with ur dajngo stop working, i found out: it was because i install NodeJS recently, and it installed a python 2.7 and changed the python path. So, if run a "python manage.py runserver" it will first look at 2.7 path. (if i run "python --version" it shows 2.7) To solve it, first go to your "C:\Users(your username)\AppData\Local\Programs\Python\Python38-32(or latest)" copy it, go to ur System Properties -> Environment variables -> PATH -> add(python path) or move it up to be the first one. Open CMD, run "python --version", it should now shows the latest version. Done! -
504 Gateway Time-out GraphQL django in development side error
I'm trying to build a graphql API using django. As it exists on the documentation, I added the following line to <project>/urls: from graphene_django.views import GraphQLView urlpatterns = [ ... path('graphql', GraphQLView.as_view(graphiql=True)), ] It worked well for a while, but after a short period of time I faced to 504 Gateway Time-out. PS I also have insomnia app and it works fine. but I don't know what is the problem with this one? -
Table first row becomes huge when few rows to display
I'm creating a bootstrap table (or just a regular table, I stripped all bootstrap classes and still have the same issue). The Problem In one set of data, where I pass 16 elements the sizing is fine. It expands when the screen height increases which I'm not a huge fan of but figured I'd mention incase it helps find a solution. But in the other case where I pass 8 elements to the table, the first row becomes absolutely massive see this link https://imgur.com/a/o3jR9IB. What I've tried I've tried clearing every class and every style within the table and its elements yet the problem persists. I've tried nesting the td's within div's that have a set height, overflow hidden, and white-space nowrap, and the problem persists. Same thing if I just put raw text into the td's. I've tried to clear all margins and padding within the table and the problem persists. Setting the style on my table to 'table-layout: fixed;' also did nothing. Code example (latest try; includes Django templates) <div class='mx-5'> <div class='table-responsive'> <table class="table table-striped table-dark shadow"> <thead class='text-center'> <tr> <th class='p-0 m-0' scope='col'>Rank</th> {% for header in headers %} <th class='p-0 m-0' scope='col'>{{header}}</th> {% endfor %} …