Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Rest-Framework File Upload
I am using Django Rest Framework to upload a file My view file looks like this: class FileViewSet(viewsets.ModelViewSet): queryset = Files.objects.all() serializer_class = FilesSerializer #+++++++++++++++++++++++++++++++++++++ parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): serializer = FilesSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) else: return Response(serializer.error, status=HTTP_400_BAD_REQUEST) My view works well with file upload even if there is no bottom part of the comment. So why should I use the code under the comment? I used the translator. Please understand if there is a mistake. -
Django subquery annotation - Set default value if no result
Is it possible to set the default value on a subquery if no result is returned? for example in the below query I would like the annotation to say 'Down' as a string if there is no record. active_circuit = Subquery( DeviceCircuitSubnets.objects.filter(device__site_id=OuterRef('id'), \ active_link=True, \ circuit__decommissioned=False ).values('circuit__name')[:1]) site_data = Site.objects.all().annotate(active_circuit=active_circuit) the above could return, where down is actually a annotation that did not have a record site | active_circuit --------------------------- London | Fibre Manchester | 4G Edinburgh | Down -
Auto added primary key trying to insert the value of NULL
I have a Django site, and am using windows auth for it. When I try to logon as a new user it gives the error Cannot insert the value NULL into column 'id', table 'table.auth_user'; column does not allow nulls. INSERT fails. One other thing to mention is that that I have a separate db for my Auth (but the AuthDB is the default one). models.py class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.BooleanField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.BooleanField() is_active = models.BooleanField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' def __str__(self): return self.username In settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'AuthDB', 'HOST': 'MyHost', 'USER': '', 'PASSWORD': '', 'OPTIONS': { 'driver':"ODBC Driver 13 for SQL Server", }, 'CONN_MAX_AGE': 60, }, I am not sure why django is trying to insert the value of NULL into the the auto added primary key id. Maybe I am missing something? Does anyone have any idea why? Thanks for the help! -
Loading image with blob and arraybuffer on django doesn't work
Now I have to load images on html with some headers, so I used blob and arraybuffer method to load it instead of simply linking with img src. But it doesn't seem to work well because: On blob method, Request status is 0 and ready status is not always DONE. On arraybuffer method, onload is not called in any browser. I'm sure that link is not broken, because I tested it with python with same url and headers. This is the code: <script type="text/javascript"> function getimg(linksrc,imgid){//using arraybuffer var oReq = new XMLHttpRequest(); oReq.open("GET", linksrc, true); oReq.setRequestHeader('User-Agent',"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"); oReq.setRequestHeader('Referer',"https://dccon.dcinside.com/"); oReq.setRequestHeader('Sec-Fetch-Mode',"no-cors"); // use multiple setRequestHeader calls to set multiple values oReq.responseType = "arraybuffer"; oReq.onload = function (oEvent) { var arrayBuffer = oReq.response; // Note: not oReq.responseText if (arrayBuffer) { var u8 = new Uint8Array(arrayBuffer); var b64encoded = btoa(String.fromCharCode.apply(null, u8)); var mimetype="image/png"; // or whatever your image mime type is document.getElementById(imgid).src="data:"+mimetype+";base64,"+b64encoded; } }; alert("aa") oReq.send(null); } function getimg2(linksrc,imgid){ var xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; //so you can access the response like a normal URL xhr.onreadystatechange = function () { if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) { alert("inin"); var … -
Django: Model Queryset to Pandas to Django Rest Framework
I am trying to accomplish the following workflow in my Django project: Query my database Convert the returned queryset to a pandas dataframe in order to perform some calculations & filtering Pass the final dataframe to Django REST API Framework if I understand correctly, I have to use django-pandas for Step 2. and Django REST Pandas for Step 3. I installed both and read the documentaton, but I have no clue how to make it work. What I have achieved to far is to set up my model, views, serializes and urls to have the original queryset rendered via the Django Rest Framework. If anyone could give me a hint on how to integrate pandas in this workflow, it would be highly appreciated. my models.py file from django.db import models class Fund(models.Model): name = models.CharField(max_length=100) commitment_size = models.IntegerField(blank=True, null=True) commitment_date = models.DateField(blank=True, null=True) def __str__(self): return self.name my views.py file from rest_framework import generics from rest_framework.views import APIView from pages.models import Fund from .serializers import FundSerializer class FundAPIView(generics.ListAPIView): queryset = Fund.objects.all() serializer_class = FundSerializer my serializers.oy file from rest_framework import serializers from pages.models import Fund class FundSerializer(serializers.ModelSerializer): class Meta: model = Fund fields = ('name', 'commitment_size', 'commitment_date') -
django-rest-framework auto generate html id / css
I'm trying to assign css styling to html generated by the django-rest-framework. Rendering a form in django generates html where the html controls have an id based on the form field name. The documentation that describes that is in the "Form rendering options" section of the documentation: https://docs.djangoproject.com/en/2.2/topics/forms/ I'm using the id to assign css styling to html controls. Is there similar functionality in django-rest-frammework ? I am rendering an object using a template (code below) but the html does not have any id tags. ''' @api_view(('GET',)) @renderer_classes([TemplateHTMLRenderer, JSONRenderer]) def snippet_detail (request, pk, format=None): snippet = django.shortcuts.get_object_or_404 (Snippet, pk=pk) if request.accepted_renderer.format == 'html': return Response({'serializer':SnippetSerializer (snippet), 'snippet':snippet}, template_name='company.html') serializer = SnippetSerializer (instance = snippet) return Response (serializer.data) ''' Is there another way to assign css to the html generated by django-rest-framework? Thanks. -
How to activate a virtual environment using Python
I am struggling to activate my virtual environment located here C:\Users\HP\project1_env. I have tried the following commands - Microsoft Windows [Version 10.0.17134.165] (c) 2018 Microsoft Corporation. All rights reserved. C:\Users\HP>project1_env\scripts\activate C:\Users\HP>project1_env\scripts\activate.bat C:\Users\HP>cd project1_env\scripts\activate The directory name is invalid. C:\Users\HP>cd C:\Users\HP\project1_env\Scripts C:\Users\HP\project1_env\Scripts>activate C:\Users\HP\project1_env\Scripts>cd C:\Users\HP\project1_env\Scripts\activate The directory name is invalid. C:\Users\HP\project1_env\Scripts>C:\Users\HP\project1_env\Scripts\activate.bat Does anyone have any other suggestions? -
Django cache data for answers?
I have the following problem: I made a crud with django rest framework, and everything works great, but there are times (most of the time) that I make POST requests to save data and django replies that the data was saved and everything That's right, but when I try to make a GET request to get the data back and see if they exist, I DON'T SHOW THEM. My solution in development mode was to stop my process (python3 manage.py runserver) and turn it on again so that now it can show me the data. The problem got bigger when I already launched my application to production and the same thing happens on my server (in Digitalocean) and I can't turn off and on every moment the server. I have my urls configured as the documentation shows. In the same way I have my viewsets and serializers but I still don't understand what is happening ... Is it some kind of cache on the server? Is there a way to correct it? What am I doing wrong? Thank you -
django admin site: Is it possible that i can display two models here?
How to I display another listview here? or it is impossible? -
Django - How can I render User's name after they enter their ID #?
This is more of a guidance question. I have an app in which a user can enter their ID # and a few other fields to submit. What I'm trying to achieve is that, once the user types their 6 digit number and tabs/clicks out of the field, it displays the User's name (a field already existing in the db, connected to their ID #). How can I go about rendering this in real time, and also requesting this information from the database? -
invalid literal for int() with base 10: '' in Django on Postgres, but not SQLite
I have been running a Django app for a couple of years and it has suddenly started to throw errors when I am updating the Postgres database used to drive the live site. When I am testing using the SQLite database there are no issues. Whenever I try to make any changes to the database objects I get a invalid literal for int() with base 10: '' error. This is the traceback I am getting: Traceback: File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File ".\Indicators\views.py" in edit_indicator 227. indicator_to_be_edited.save() File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\base.py" in save 806. force_update=force_update, update_fields=update_fields) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\base.py" in save_base 836. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\base.py" in _save_table 903. forced_update) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\base.py" in _do_update 953. return filtered._update(values) > 0 File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\query.py" in _update 664. return query.get_compiler(self.db).execute_sql(CURSOR) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql 1191. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql 863. sql, params = self.as_sql() File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\sql\compiler.py" in as_sql 1157. val = field.get_db_prep_save(val, connection=self.connection) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\fields\__init__.py" in get_db_prep_save 770. prepared=False) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\fields\__init__.py" in get_db_prep_value 762. value = self.get_prep_value(value) File "C:\ProgramData\Anaconda34\envs\py34\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value 1853. return int(value) Exception … -
Django. Sentry. How can I pass user agent info into using sentry sdk?
I use this code to setup sentry sdk sentry_sdk.init( sentry_dsn, environment=sentry_env, release=release, send_default_pii=True, integrations=[ LoggingIntegration(event_level=WARNING), DjangoIntegration(), CeleryIntegration(), ], ) Usage of send_default_pii=True helped me to send user info, but browser still unknown (img with that view) request.header contains the User-Agent param -
Best practice for accessing submitted form data in django for use before saving to database
I am developing an app in Django where I am suppose to save user Invoice details to database. One of the inputs from the user is a selection of payment type. I am supposed to pick this selection value and retrieve amount from database before I save to invoice. This what I have done so far. It is working well, but I am really doubting if this is the right way to do it. Models.py class Invoice(models.Model): invoice_status_choices = [ ('1', 'Pending'), ('2', 'Paid'), ('3', 'Cancelled') ] invoice_number = models.CharField(max_length = 500, default = increment_invoice_number, null = True, blank = True) description = models.CharField(max_length=100, blank=True) customer = models.ForeignKey(User, on_delete=models.CASCADE) payment_date = models.DateTimeField(blank=True, null=True) paid_amount = models.DecimalField(max_digits=15, decimal_places=2, default=0) invoice_status = models.IntegerField(choices=invoice_status_choices, default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.invoice_number) class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) listing = models.ForeignKey('listings.Listing', on_delete=models.CASCADE) payment_type = models.ForeignKey('SubscriptionType', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.IntegerField(default=1) def __str__(self): return f'{self.invoice.invoice_number} Items' class SubscriptionType(models.Model): subscription_type = models.CharField(max_length=20) frequency = models.PositiveIntegerField() period = models.ForeignKey(PeriodNames, on_delete=models.CASCADE) rate = models.DecimalField(max_digits=6, decimal_places=2, default=0) created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subscription_type Here is the view that I need help with. The point … -
Django ImportError: No module named 'webapp_credentials'
I am running this code: https://github.com/cndreisbach/call-for-service/blob/master/docs/src/development.md When im running this part of code in my Vagrant shell : python3 ./cfs/manage.py migrate --settings=cfs.settings.local It's returning me that there is no "ImportError: No module named 'webapp_credentials'" This is the error : Traceback (most recent call last): File "./cfs/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 351, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 303, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 697, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/vagrant/cfs/cfs/settings/local.py", line 1, in <module> from .base import * File "/vagrant/cfs/cfs/settings/base.py", line 15, in <module> from webapp_credentials import creds ImportError: No module named 'webapp_credentials' Is webapp_credentials supposed to be a module of Django how do i fix this? -
Django REST Framework - Limit for Nested Serializer
I have the following models.py: class Category(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=False) class Movie(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=False) category = models.ForeignKey(Category,related_name='movies', on_delete=models.CASCADE, blank=True, null=True) As you can see, there is a ForeignKey relationship between the two classes. A Category can have multiple movies, but a Movie belongs to only one Category. My serializers.py looks like the following: class CategorySerializer(serializers.HyperlinkedModelSerializer): movies = MoviesSerializer(many=True, read_only=True) class Meta: model = Category fields = ('url','id','created','name', 'movies') class MovieSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Movie fields = ('url','id','created','name', 'category') So, I have nested serializers. When I deserialize the content of the categories, then it shows me also the nested movies in the JSON output as I expected. But it shows me ALL movies belonging to a particular category in the JSON output. How can I limit this number ? I tried this solution but it did not worked for me because I use serializers.HyperlinkedModelSerializer. In that provided solution they used serializers.ModelSerializer. I got this error when I tried that solution: AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. -
Use Vue for loop with Django Variable
I use vue together with django. To simplify code, I like to iterate over vue data and use the data as variable for a getattr on a python object. What I tried is the following. <div v-for="field in fields" class="col-md-3"> {% lookup myobject <%field.name%> %} </div> But this doesn't work as django tells me: Could not parse the remainder: '<%field.name%>' from '<%field.name%>' my delimiters are "<%","%>" -
Django models filter by foreignkey?
I want to make a big request. In this query, a field is taken from one table passing through 2 tables. How can I make a filter? paymentsss = Transaction.objects.select_related('currency', 'payment_source__payment_type', 'deal__service', 'deal__service__contractor').filter( payment_date__range=[date1, date2], payment_source__deal__service__contractor__name=contractor) .order_by('-id') As you can see, I'm trying to access the table contractor through deal, service and contractor. How can I make a filter? -
How to send HttpResponse Object
I am trying to call the view for my homepage but throw error when i click on the link to access the page I had tried several things code are given class Dashboard(LoginRequiredMixin, TemplateView): template_name='dashboard.html' # model=models.Account # context_object_name='account' login_url='login' def get(self,request): transaction=models.Transaction.objects.all() for trans in transaction: if trans.from_account == None: trans.delete() return render(request, 'dashboard.html', context = { 'selected_accounts':selected_accounts, }) ValueError at /account/dashboard/ The view accounts.views.Dashboard didn't return an HttpResponse object. It returned None instead. -
How can I populate a manytomanyfield , using view, without django pré-built forms?
I'm building a storage web system using django, I'm very newbie on the framework, so the problem is that, there is a bussiness rule, wich demands, two kinds of products, the inside products, and the finished ones. And the finished ones, always are composed by one or more inside products, I have the idea of using the manytomanyfields, but now, I don't really know how to extract this data , that should be a multiple choice, from the form and save in the database, does anyone has any tips or better ideas? Models.py class Produto(models.Model): codigo = models.CharField(max_length=254, null=True) produto_desc = models.CharField(max_length=200, null=False) tipo = models.CharField(max_length=2) qtd = models.IntegerField(null=True, default=0) created = models.DateTimeField(default=timezone.now, editable=False) last_updated = models.DateTimeField(default=timezone.now, editable=False) #Relationship Fields estrutura = models.ManyToManyField( 'storage.Produto', related_name="produto" ) def __str__(self): return self.produto_desc Views.py def CadastroProd(request): temp = 0 lista_produto = Produto.objects.order_by('id')[:20] for i in lista_produto: temp += 1 if request.method == 'POST': form = NovoProduto(request.POST) if form.is_valid(): obj = Produto() obj.save(commit=False) obj.codigo = form.cleaned_data['codigo'] obj.produto_desc = form.cleaned_data['produto_desc'] obj.tipo = form.cleaned_data['tipo'] # obj.estrutura = form.cleaned_data['estrutura'] obj.save() return HttpResponseRedirect('/storage/produtos') lista_produto = Produto.objects.order_by('id')[:20] lista_pi = Produto.objects.filter(tipo='PI') lista_pa = Produto.objects.filter(tipo='PA') context = {'lista_produto': lista_produto, 'temp': temp, 'lista_pi': lista_pi, 'lista_pa': lista_pa, } return render(request, 'storage/cadproduto/cadproduto.html', context) forms.py … -
Create number of fields based from choices
*I'm trying to figure out how to populate fields in my model based on previous field selection. For example, if FIELD_CHOICES = 3 Create 3x TextField() class Post(models.Model): STATUS_CHOICES = (('published','Published'), ('draft','Draft ')) FIELD_CHOICES = (('1','1 Title and body field'), ('2','2 Title and body fields'), ('3','3 Title and body fields'), ('4', '4 Title and body fields'), ('5', '5 Title and body fields')) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post') title = models.CharField(max_length=100) sub_title = models.TextField(max_length=50,default="") title_and_body_fields = models.IntegerField(choices=FIELD_CHOICES, default=1) **/// create number of title and body Textfields based on what was /// selected in title_and_body_fields** created = models.DateField() publish = models.DateTimeField(default=timezone.now) slug = models.SlugField(max_length=250, unique_for_date='created') status = models.CharField(max_length=250, choices=STATUS_CHOICES, default='draft') object = models.Manager() postManager = PostManager() class Meta(): ordering = ('publish',) def __strd__(self): return self.title def get_absolute_url(self): return reverse('my_blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) For example if FIELD_CHOICES = 3 create 3x TextFields() -
Django sign up view how to get the user from the user form to assign profile to the user
I have this sign up form where I am taking values from the user about his username and password and also his proile. I have separately created two forms UserForm and ProfileForm. When the user is signing up for his account how do I connect profile to the user. This is what I have forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, label='Email', error_messages={'exists': 'Oops'}) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(SignUpForm, self).save(commit=False) user.email = self.cleaned_data["email"] # user.status = self.cleaned_data["status"] if commit: user.save() return user class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['contact', 'whatsapp', 'gender', 'avatar'] models.py class Profile(models.Model): STATUS_CHOICES = ( (1, ("Permanent")), (2, ("Temporary")), (3, ("Contractor")), (4, ("Intern")) ) GENDER_CHOICES = ( (1, ("Male")), (2, ("Female")), (3, ("Not Specified")) ) PAY_CHOICES = ( (1, ("Fixed")), (2, ("Performance Based")), (3, ("Not Assigned")), ) user = models.OneToOneField(User, on_delete=models.CASCADE) emp_type = models.IntegerField(choices=STATUS_CHOICES, default=1) start_date = models.DateField(default=timezone.now) end_date = models.DateField(null=True, blank=True) user_active = models.BooleanField(default=True) contact = models.CharField(max_length=13, blank=True) whatsapp = models.CharField(max_length=13, blank=True) gender = models.IntegerField(choices=GENDER_CHOICES, default=3) pay_type = models.IntegerField(choices=PAY_CHOICES, default=3) pay = models.IntegerField(default=0) avatar = models.ImageField(upload_to='users/images', default='users/images/default.jpg') title = models.CharField(max_length=25, unique=False) #manager_username = models.ForeignKey(User, blank=True, null=True, to_field='username',related_name='manager_username', on_delete=models.DO_NOTHING) def __str__(self): return self.user.username … -
Error coming on the Local Server while logging in the Python and Django Application
I want my login.html page to hit first as a landing page in my Python and Django application. But an error is showing in urls.py file of the project on the server as soon as I am hitting the enter button after filling the username and password. Kindly help to solve the issue!! URLS.py File of the Project: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('tabs_app.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')) ] VIEWS.py file of the app in the project where index.html file is located: from django.shortcuts import render # Create your views here. def login(request): return render(request, 'login.html') URLS.py file of the app in the project where index.html file is located: from django.urls import path from . import views urlpatterns = [ path('', views.login, name='login') ] VIEWS.py file of the app in which LOGIN code is written: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User, auth # Create your views here. def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request, user) return redirect('/') else: messages.info(request, 'invalid credentials') return redirect('login') … -
Heroku upload static folder not found
I was trying to reproduce the tutorial Django app and uploading it to Heroku server, but I can't resolve problems with static files. Here is a link to all files on github: https://github.com/Rufus90/poll.git When I try to run heroku run python manage.py collectstatic --noinput I get this error: Running python manage.py collectstatic --noinput on ⬢ hidden-plains-30510... up, run.1265 (Free) Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/finders.py", line 131, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/files/storage.py", line 315, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/app/static' After completing the tutorial I have copied the whole repo, renamed it and changed the paths where I think it was needed. I was playing with my old project from … -
Caching table in django models
There is a remote database which is not always available and I need to store some of it's information in my app's model. I decided to use apscheduler to run a scheduled job which will try to connect to that database and update my model accordingly. The information is not changing very often so running a job, let's say, once a day would be enough. At the moment I decided to proceed like this: try to get new records from remote database get existing records from my local app's model compare these sets and define entities which are to be created, to be updated and to be deleted (based on specific_entity_id's value) perform bulk_create on those entities which are to be created perform bulk_update on those entities which are to be updated mark those entities which are to be deleted as to_be_deleted as there may be some foreign key constraints which I will handle later My model looks like this: class MyModel(models.Model): specific_entity_id = models.IntegerField() to_be_deleted = models.BooleanField() The table from remote database has some extra fields that I am not interested in. The number of records is not that great. I feel like there should be a better approach … -
How to display values from fields already chosen by user in UpdateView
So I've got a model and form: class CartItem(models.Model): user = models.ForeignKey('accounts.CustomUser', related_name='carts', on_delete=models.CASCADE, verbose_name='User') product = models.ForeignKey('pizza.Product', related_name='carts', on_delete=models.CASCADE, verbose_name=_('Product')) quantity = models.SmallIntegerField(verbose_name=_('Quantity')) def __str__(self): return f'{self.quantity} of {self.product}' class CartItemForm(forms.ModelForm): product_types = forms.ModelChoiceField(queryset=ProductType.objects.none(), required=False) product_sizes = forms.ModelChoiceField(queryset=Size.objects.none(), required=False) product_names = forms.ChoiceField(choices=[('', '---------')]) class Meta: model = CartItem fields = ['product_types', 'product_names', 'product_sizes', 'quantity'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) self.product_type = kwargs.pop('product_type', None) self.product_names_query = Product.objects.filter(type__name__contains=self.product_type).values_list( 'name', flat=True).distinct() self.product_names_choices = [('', '---------')] + [(name, name) for name in self.product_names_query] super().__init__(*args, **kwargs) def save(self, commit=True): product = Product.objects.get(name=self.cleaned_data.get('product_names'), type=self.cleaned_data.get( 'product_types'), size=self.cleaned_data.get('product_sizes')) user_product = CartItem.objects.create(user_id=self.request.user.id, `product=product, quantity=self.cleaned_data.get('quantity'))` My HTML form looks like this: > <form method="POST" action="{% url 'pizza_order' %}"> > {% csrf_token %} > <div> > <label for="id_product_types"><b>Choose pizza type:</b></label> > {{ form.product_types }} > </div> > <div> > <label for="id_product_names"><b>Choose amount of toppings:</b></label> > {{ form.product_names }} > </div> > <div id="toppings__checkboxes"> > <label for="id_toppings" id="toppings__label"></label><br> > {% for checkbox in form.toppings %} > <span class="toppings--checkbox">{{ checkbox.tag }} {{ checkbox.choice_label }}</span> > {% endfor %} > </div> > <div> > <label for="id_product_sizes"><b>Choose size:</b></label> > {{ form.product_sizes }} > </div> > <div> > <label for="id_quantity"><b>Quantity:</b></label> > {{ form.quantity }} > </div> > <div class="price"></div> > <div><input type="submit" …