Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update m2m,foreignkey field to model does not work in DRF
Update to the following News model does not work in DRF.( address is not updated) The creation works fine. class News (models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=20) text = models.TextField() group_address = models.ManyToManyField(Group, blank=True) user_address = models.ForeignKey(User, on_delete=models.CASCADE) class Group(models.Model): id = models.AutoField(primary_key=True) group_name = models.CharField(max_length=20) class User(models.Model): id = models.AutoField(primary_key=True) user_name = models.CharField(max_length=20) class NewsSerializerViewSet(viewsets.ModelViewSet): queryset = News.objects.all() serializer_class = NewsSerializer class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = '__all__' -
Autocomplete issue to html codes in django project in visual studio code
I have no problem with python codes in visual studio code even js codes autocomplete is working when im doing django project but when i try to type html codes in .html files,there is a autocomplete problem. Some codes autocompletes are working,the codes from django like {% block %} {% endblock %} but the pure html codes like etc. i cannot get any hint from the extensions.Btw i got many snippets which is related html js python django etc. only problem with the html codes. How can i solve the issue.. thanks in advance.. https://i.stack.imgur.com/9h3oc.png -
How can i send reminder message to customer before 2 hours in django/python
I am developing a web app for online ticket buying. I used telesign API to integrate sms system. Now i want a reminder system for my web app, it should send sms to customer before 2 hours of start time of movie. -
Django get data from form submission
I had something that I'm missing because I already worked with databases and forms.py, but when it comes to get the data from a simple form, it never work for me: I tried the below, and it's not printing anything when I'm searching - Thanks! Any recommendations for fixing it, or handling filtering in a better way will be appreciated. Urls.py app_name = 'adolim' urlpatterns = [ path('', views.home, name='home'), path('clients/', views.clients_view, name='clients'), path('clients/', views.clients_filter_view, name='filter_clients'), clients.html <form action="{% url 'adolim:filter_clients' %}" method="post" > {% csrf_token %} <div class="input-field col s3"> <input name="phone_number" id="phone_number" type="text" class="validate"> <label for="phone_number">לפי מספר טלפון</label> </div> <div class="input-field col s3"> <input name="first_name" id="first_name" type="text" class="validate"> <label for="first_name">לפי שם פרטי</label> </div> <div class="row left"> <button class="btn waves-effect waves-light blue" type="submit" name="action">חפש לקוח <i class="material-icons right">search</i> </button> </div> </form> Views.py def clients_filter_view(request): first_name = request.POST.get('first_name') phone_number = request.POST.get('phone_number') print(first_name, phone_number) return render(request, 'adolim/clients.html', data_to_render) -
How to deploy files to django application without affecting the cron function?
We have different cron functions that are being executed in various hours of the day. When it comes to any file deployment the cron function gets affected. Those cron functions affect certain functions in different files during deployment the cron is broken and fails. We are using AWS code deploy service. how to overcome this situation? -
Django role based form
I have two users a customer and an admin. And I have an update and a create form with a status field and other fields. The status filed displays whether the order is received, scheduled, or in manufacturing. I want only the admin to update that field and customer to only view it. Can anyone tell me how can I implement it? Thanks! -
Hosting Django+PostgreSQL to server
I am not familiar with databases, I tried connecting Django+PostgreSQL. During hosting the Django app to cloud, should I install PostgreSQL to server space ? I have experience in hosting Django with default SQLite, I did not have to think about database as its default with Django. I am using www.pythonanywhere.com as hosting provider and it support PostgreSQL. -
Django - How user authentication is different than session authentication
I am new to django trying to write some apis. Django has user based authentication request.user.is_authenticated() to check whether a valid user is logged in or not. There is also session authentication. 1. How session authentication is different than django user based authentication? 2. Which is more secure? I am trying to write rest apis that calls third party apis. 3.Is it posssible to use tastypie SessionAuthentication without using model? I didn't find any rest api example that has implemented tastypie without model. -
image embedded in email HTML template - Flask-mail ValueError: too many values to unpack (expected 2)
I tried to send a response email from HTML template that include an image on header. If I send HTML without image attachment there is not error but it is a text email like. I searched and test for couple of days, no success. Flask-email snippet is msg = Message(form.title.data, recipients=['emial@gmail.com']) msg.html = render_template('mail_temp/file.html') with open('/home/daniel/PycharmProjects/Sitio/blue/static/pictures/ribbon.jpg', 'rb') as fp: msg.attach('ribbon.jpg', 'image/jpg', fp.read(), 'inline', headers={'Content-ID': 'ribbon'}) mail.send(msg) HTML template include image in: <td> <img src="cid:ribbon"/> </td> The issue seems happen in the parameter for Message.Attach method. I found a similar question and response but 2 years old, maybe the method changes it. Thanks in advance. File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/daniel/PycharmProjects/Sitio/blue/site/routes.py", line 220, in contactme mail.send(msg) File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 492, in send message.send(connection) File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 427, in send connection.send(self) File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 190, in send message.as_bytes() if PY3 else message.as_string(), File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 385, in as_bytes return self._message().as_bytes() File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 371, in _message for key, value in attachment.headers: ValueError: too many values to unpack (expected 2) `` -
Assigning a group of models to another model
I'm creating a task completion app where a user can create a project, then users can create tickets for that specific project. The problem is that when I create a foreignkey object, it requires a default value. There are no projects right now to set as default. Here are my models class Projects(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=140) class Post(models.Model): LOW = 1 NORMAL = 2 HIGH = 3 STATUS_CHOICES = [ (LOW , 'Low'), (NORMAL, 'Normal'), (HIGH, 'High'), ] TYPE_CHOICES = [ ('Features', 'Feature Request'), ('Bug/Error', 'Bug/Error'), ('Design', 'Design'), ] PROGRESS_STATUS = [ ('Open', 'Open'), ('InProgress', 'In Progress'), ('AddInfo', 'Additional Info Required'), ('Completed', 'Completed'), ] #all_users = Profile.objects.all() #all_user_choices = ((x.user, x.user) for x in all_users) title = models.CharField(max_length=50) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) priority = models.IntegerField( choices=STATUS_CHOICES) status = models.CharField(choices=PROGRESS_STATUS, default='Open', max_length=25) ticket_type = models.CharField(choices=TYPE_CHOICES, default ='Features', max_length=25) project = models.ForeignKey(Projects, on_delete=models.CASCADE) #assigned_developer = models.CharField(choices=all_user_choices, default=author, max_length=50) Thanks! -
JavaScript preventing form submission
I'm working on a Django project and one of the forms won't submit. I figured out that the culprit is some JavaScript that formats the currency input (when I remove the JS or remove the input type="currency", it submits) This is my simplified form: <form action="{% url 'create_goal' %}" method="post"> {% csrf_token %} <h4 class="mb-3" id="create">Create a Savings Goal</h4> <input type="text" class="form-control" id="goalName" name="goalName" value="" required> <input type="currency" min="0" pattern="^\d*(\.\d{0,2})?$" class="form-control" id="goal" name="goal" required> <button type="submit" class="btn btn-secondary btn-block">Add Goal</button> </form> {% load static %} <script src="{% static 'starling/currency.js' %}"></script> This is the JavaScript (I got it from here: html5 input for money/currency): var currencyInput = document.querySelector('input[type="currency"]') var currency = 'GBP' // format inital value onBlur({target:currencyInput}) // bind event listeners currencyInput.addEventListener('focus', onFocus) currencyInput.addEventListener('blur', onBlur) function localStringToNumber( s ){ return Number(String(s).replace(/[^0-9.-]+/g,"")) } function onFocus(e){ var value = e.target.value; e.target.value = value ? localStringToNumber(value) : '' } function onBlur(e){ var value = e.target.value var options = { maximumFractionDigits : 2, currency : currency, style : "currency", currencyDisplay : "symbol" } e.target.value = value ? localStringToNumber(value).toLocaleString(undefined, options) : '' } -
How to use inlineformset_factory when multiple Foreign key
I have four models of the shop, customer, product, an order. I am showing the relation of models shop user = models.OneToOneField(User, null=True, related_name='shop', blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=70, null=True, default='shop', ) address = models.CharField(max_length=70, null=True) Shop_category = models.CharField(max_length=200, null=True, ) customer user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, default='customer') Phone = models.PositiveIntegerField(blank=True, null=True) product shop = models.ForeignKey(Shop, models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, blank=True) Brand = models.CharField(max_length=200, blank=True) description = models.TextField(null=True, blank=True) order shop = models.ForeignKey(Shop, models.CASCADE, null=True) customer = models.ForeignKey(Customer, models.CASCADE, null=True) product = models.ForeignKey(Product, models.CASCADE, null=True) quantity = models.CharField(max_length=30) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=200, choices=STATUS, default='Pending') note = models.CharField(max_length=1000, null=True) when customers login then the shop will print on the screen and a button on shop to show the products by the shop in the form card. On the product card, there is an order button that adds the product in order after submitting the selected product will print with the remaining filled of order that show in the image how I can create an order so that the customer in order is the instance and the shop in order is that shop which is selected to show the products, and products which are … -
Can I create an AbstractBaseUser like this?
class Staff(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=60, unique=True) date_joined = models.DateTimeField(verbose_name="Date Joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="Last Login", auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) position = models.CharField(max_length=45) department_fk = models.ForeignKey( Department, models.CASCADE, db_column='department_fk') <----- This is what im worried about I dont know if it will accept a foreign key in django. Can anyone give me an advice how to properly do this? -
AWS deployment of django application
I have a django application which has been deployed in aws. The URL in ec2 instance is loading fine too. My application has a modal where I should enter my team name and username. Whenever I try in [ec2instanceurl]:8000/ (when i start gunicorn)iam not facing any alert error. But when i start the nginx and access the url without port(8000) the page is loading and whenever i enter the details in modal and click confirm button it shows an alert says '[ec2instanceurl] says error' I will attach the error snap here I want to know whether it is my django app error or any aws settings error. The thing is that its working fine in local,and in gunicorn port. Though Iam new to aws deployment iam expecting advices.. Thanks in advance -
OperationalError at /admin/products/product/add/ no such table: main.auth_user__old
I was editing a project on Django, so I deleted my pychache, migrations, and db.sqlite3 and created a new superuser to log into the admin page. After I created a product and pressed 'Save' on the admin page an error saying "OperationalError at /admin/products/product/add/ no such table: main.auth_user__old" appeared. I have tried solving this issue with solutions such as doing makemigrations and migrate again, but none of the solutions I have tried have worked so far. Does anyone know of a possible solution to this? -
Django datetime format changes
I have datetime stored in sql database. When Django renders the page along with data, on html the date is displayed as June 11, 2020, 5:56 p.m. This is render directly from the django backend. But when I retrieve data using jquery ajax, the data is displayed with format 2020-06-11T17:57:12.188 How do I convert to the other type? -
How to change the host in next key in a paginated URL in django rest framework?
I have a ModelSerializer in Django Rest Framework with paginated responses. So I have deployed it with gunicorn in a docker container. gunicorn -c gunicorn_config.py app.wsgi --bind 0.0.0.0:5000 Now the problem is in the paginated responses. The next key is something like. next: "http://0.0.0.0:5000/admin/users/?page=2&per_page=10" In my client-side where I am consuming these APIs, I just check the next key and fetch the next response. But since the next key has the host as 0.0.0.0:5000 hence it will cause API call failure. And the purpose is not served for the next key. So at the moment, my API server is running in a separate docker container. Which is set up via the reverse proxy in nginx. -
How to get entries of two related models in a single view?
Basically I am working on an inventory management system. The models "Purchase_Bill" and "Purchase_Item" are the ones I wish to get entry for. Here is a snippet of them, class Purchase_Bill(models.Model): status_choices = ( ('Paid','Paid'), ('Unpaid','Unpaid'), ) category_choices = ( ('Product','Product'), ('Packaging','Packaging'), ) Bill_Num = models.CharField(max_length=30,null=True,blank=True) Supplier = models.ForeignKey(Supplier,on_delete=models.CASCADE) Cheque_No = models.IntegerField(null=True,blank=True) Cheque_due = models.DateField(default=date.today,null=True,blank=True) Status = models.CharField(max_length=10,choices=status_choices,default="Update") Bill_Date = models.DateField(default=date.today,blank=True,null=True) Category = models.CharField(max_length=20,choices=category_choices,default="Update") def __str__(self): return self.Bill_Num class Purchase_Item(models.Model): purchase_bill = models.ForeignKey(Purchase_Bill,null=True,on_delete=models.SET_NULL,verbose_name = "Bill ID") product = models.ForeignKey(Product,null=True,on_delete=models.SET_NULL,verbose_name = "Product") #batch yet to be created with an other model called Inventory #expiry yet to be created with an other model called Inventory p_qty = models.IntegerField(verbose_name = "QTY") p_cost = models.IntegerField(verbose_name = "Cost") p_gst = models.IntegerField(verbose_name = "GST") def __str__(self): return self.purchase_bill.__str__() Our system requires the entry of Purchase_Bill Attributes at first, and then we gotta add the products (ForeignKey attribute from the model Purchase containing the list of products and their details) in the Purchase_Item model one by one. (1 or more entries for the Purchase_Item with the same "purchase_bill" (points to Bill_Number in the parent model) Such that, Bill_Number is automatically set to instance of the Purchase_Bill which they have just entered (inline formsets). How to get the … -
Aparecendo a Time_Zone (DJANGO)
Boa noite. Meu código está exibindo a time zone completamente errada e confesso que não faço ideia de como fazer ela desaparecer ou ficar em horário normal. Estou usando Charts.js No views: def notaEntradaList(request): nota_entrada = NotasEntradas.objects.all().order_by('criado') template_name = 'notaEntradaList.html' listagem_produto=[] listagem_quantidade=[] listagem_data=[] listagem_valor_total=[] for produto in nota_entrada: listagem_produto.append(produto.produto) listagem_quantidade.append(produto.quantidade) listagem_data.append(str(produto.criado)) listagem_valor_total.append(float(produto.precoQuantidade())) print(listagem_produto, listagem_quantidade, listagem_data) context = { 'nota_entrada': nota_entrada, 'listagem_produto': listagem_produto, 'listagem_quantidade': listagem_quantidade, 'listagem_data':listagem_data, 'listagem_valor_total':listagem_valor_total, } return render(request, template_name, context) No notaEntradaList: <canvas id="myChart" width="400" height="100"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: {{listagem_data |safe }}, datasets: [{ label: 'Acrescentados', data: {{listagem_quantidade|safe }}, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } }, }); </script> Como eu poderia solucionar isso exibindo a data certinha com a hora, se possívelmente? -
The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256 with Django Angular
I am using Django as backend to return API's at front end Angular side. I used AWS S3 for media storage. URL is generating using the s3 url and able to upload the files on S3 bucket. Problem is on web the Image content getting the 400 Bad Request. following is my code: AWS_ACCESS_KEY_ID = "XXXXXXXXXXXXXXXXXX" AWS_SECRET_ACCESS_KEY = "XXXXXXXXXXXXXXXXXXX" AWS_STORAGE_BUCKET_NAME = "app" AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #AWS_QUERYSTRING_AUTH=False when I am uncommenting the #AWS_QUERYSTRING_AUTH=False and making all the s3 Images as public then able to access the image on web, need to make image explicitly public, which I don't want this. after commention getting the url like - https://famesta-app.s3.ap-south-1.amazonaws.com/user_30/profile/download.png?AWSAccessKeyId=XXXXXXXXXXXXXXXX&Signature=XXXXXXXXXXXXXXXXXXXx%3D&Expires=1592369615 Error: <Error> <Code>InvalidRequest</Code> <Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message> <RequestId>20DF944878611</RequestId> <HostId>sZPyWKvGHSRt7ANyDlOUh71/xUV14H0avAjaERfkoQxiq0=</HostId> </Error> My region is Asia Pacific (Mumbai) AWS Configuration- CORS Configuration <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> And In S3 Permission I have allow the Public access. If I will make whole bucket as public and AWS_QUERYSTRING_AUTH=False then able to upload image get access on web everything that I wanted, but I don't think so it is safe to make bucket itself public. … -
Django Simple History - Tracking M2M field changes (with "through")
I am using django-simple-history to track changes to my fields, and from what I see, it seems like django-simple-history does not track changes to M2M fields. I tried introducing an intermediate model for the M2M fields, and then attaching a HistoricalRecords() field within that intermediate model, but it seems like there is no use for that, unless I am using the django-simple-history wrongly. It seems like whenever I add a new relation in the M2M field (with "through"), a new instance is created within the intermediate model referencing foreign key relations to the two models with M2M relations, and whenever a relation is removed, that corresponding instance in the intermediate model would be deleted. If that is the case, how can I track the changes of the M2M fields through the intermediate model? Since the instance would be deleted whenever it is removed as a relation, which would lead to the tracking to not exist, since that instance no longer exists. I am new to django-simple-history, so do guide me along if I missed out or misunderstood anything, thanks all! Here is my code: models.py class CustomerInformation(models.Model): customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100) history = HistoricalRecords() class SalesProject(models.Model): sales_project_id = … -
How to remove change password link from django admin site?
I am using active directory login authentication for my django web application. So there is no need of change password link in admin site. I have searched lot of article, but I haven't found any thing to hide change password link. So what is the way of hiding change password link from admin? -
Unable to use ShowInLegend Property along with drawTable in highcharts Piechart
I was successful in rendering a dataTable within the pie chart div for my Django application. It can be found here: http://jsfiddle.net/6vqzLo7h/ $(function () { Highcharts.setOptions({ colors: [ '#1cc88a', '#008a59', '#6adfb6' ] }); Highcharts.drawTable = function() { // user options var tableTop = 200, colWidth = 60, tableLeft = 50, rowHeight = 20, cellPadding = 2.5, valueDecimals = 1, valueSuffix = ''; // internal variables var chart = this, series = chart.series, renderer = chart.renderer, cellLeft = tableLeft; // draw category labels $.each(series, function(serie_index, serie) { renderer.text( serie.name, cellLeft + cellPadding, tableTop + (serie_index + 1) * rowHeight - cellPadding ) .css({ fontWeight: 'bold' }) .add(); }); $.each(series[0].data, function(i) { renderer.text( series[0].data[i].name, cellLeft + colWidth - cellPadding, tableTop + (i + 2) * rowHeight - cellPadding ) .attr({ align: 'right' }) .add(); }); $.each(series[0].data, function(i) { renderer.text( Highcharts.numberFormat(series[0].data[i].y, valueDecimals) + valueSuffix, 150, tableTop + (i + 2) * rowHeight - cellPadding ) .attr({ align: 'left' }) .add(); }); } $('#container').highcharts({ chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false, events: { load: Highcharts.drawTable }, height: 600, width: 800, marginBottom: 250 }, title: { text: undefined }, credits: { enabled: false }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { … -
Admin can view all orders
@login_required(login_url='/') def order_list(request): order = Order.objects.filter(user=request.user) context = { 'order': order } return render(request, "order_list.html", context) So this is my view function, right now a logged-in user can only view his/her own order. I have two users an admin and a customer. I want the customers to view their own orders which is working fine, but I want the admin to view all the orders created by customers. -
Django doesn't accept image submission, method and enctype included in form tag but browser console claims it is missing
I'm following along with a tutorial to build a Django project. Part of the project is being able to upload an image to the test cdn directory. This is what my form looks like currently: <form method='POST' action="." enctype='multipart/form-data'> {% csrf_token %} {{ form.as_p }} <button type="submit">Send</button> </form> The method and enctype are very clearly defined. I've also set up my settings.py STATIC_URL = '/static/' LOCAL_STATIC_CDN_PATH = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn_test') STATIC_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles') ] MEDIA_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'media') MEDIA_URL = '/media/' set up the files to be received in the view: form = BlogPostModelForm(request.POST or None, request.FILES or None) set up the model use ImageField: image = models.ImageField(upload_to='image/', blank=True, null=True) and the url patterns: if settings.DEBUG: # test mode from django.conf.urls.static import static # display images/files saved in the test cdn urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But even with all this, the console informs me: Form contains a file input, but is missing method=POST and enctype=multipart/form-data on the form. The file will not be sent. This is the tutorial in case it helps https://www.youtube.com/watch?v=-oQvMHpKkms&list=PLM39hJgCef42hVok8ZRRE4LpLD-5bOxBh&index=20&t=13385s the part in question starts at 3:48:00.