Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
deploying angular 9 with django drf with docker - requests gets rejected
Disclaimer: sorry for my bad english and I am new to angular, django and production. I am trying to push the first draft of what I've made into a local production server I own running CentOS 7. Up until now i was working in dev mode with proxy.config.json to bind between the Django and Angular so far so good. { "/api": { "target": "example.me", "secure": false, "logLevel": "debug", "changeOrigin": true } } when I wanted to push to production however i failed to bind the container frontend with backend. these are the setup i made Containerizing angular and putting the compiled files in an NGINX container -- port 3108 Containerizing Django and running gunicorn -- port 80 Postgres image DockerFiles and Docker-compose Django Dockerfile FROM python:3.8 # USER app ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ Angular Dockerfile FROM node:12.16.2 AS build LABEL version="0.0.1" WORKDIR /app COPY ["package.json","npm-shrinkwrap.json*","./"] RUN npm install -g @angular/cli RUN npm install --silent COPY . . RUN ng build --prod FROM nginx:latest RUN rm -rf /usr/share/nginx/html/* COPY ./nginx/nginx.conf /etc/nginx/conf.d/default.conf COPY --from=build /app/dist/frontend /usr/share/nginx/html EXPOSE "3108" Docker-compose version: '3' services: db: image: postgres environment: - … -
How can a Django web app in a centos Docker container send emails via a Windows 10 host?
I have a Django web app running in a Unix (Centos 8) Docker container, and this app is supposed to send emails. Currently I am running the app, including other Docker containers, on my Windows 10 laptop for development and manual testing. But eventually it will run in an AWS EC2 instance. I suspect that in AWS I can just use Amazon's SES ("Simple Email Service"). But I would like to be able to email in Development mode too. I set up an SMTP relay Docker container, with port 25 mapped to host port 25, and running an emailer called Postfix (a successor to Sendmail), and tried to configure it. But, although the SMTP relay mode configuration of Postfix is supposed to be pretty simple I wasn't able to get the perishing thing to work. I'm not sure if this is because my Postfix config is defective somehow or because Windows 10 is not playing ball. Any ideas? P.S. I case it helps, the following are the Postfix environment variable values I defined. If anyone faced with the same problem finds this page, please don't rely on these values, as some or all may well be nonsense! ENV RELAY_MYDOMAIN=jrsurveys.com ENV … -
how to access a model inside the app template
Trying to access if affiliate exists in the template HTML, but it doesn't instantiate the object in HTML I try to access the affiliates with {% if affiliates %} or {% if objects %}, but code goes to else part instead, this has to check if an affiliate already exists in the model. {% block affiliate_content %} {% if affiliates %} <h3>{% trans "Your code" %}</h3> <table class="table table-bordered"> <thead> <tr> <td>{% trans "Title" %}</td> <td>{% trans "Code" %}</td> <td>{% trans "Example" %}</td> </tr> </thead> <tr> <td>{% trans "Affiliate code" %}</td> <td>{{ affiliate.aid }}</td> <td></td> </tr> <tr> <td>{% trans "Affiliate link" %}</td> <td>{{ affiliate_link }}</td> <td></td> </tr> <tr> <td>{% trans "Affiliate link for website" %}</td> <td>{{ '<a href="'|force_escape }}{{ affiliate_link }}{{'">'|force_escape }}{% trans "Partner link" %}{{'</a>'|force_escape }}</td> <td><a href="{{ affiliate_link }}">{% trans 'Partner link' %}</a></td> </tr> </table> {% else %} {% trans "Currently you don't have affiliate program. Please, enable it first." %} {% endif %} {% endblock %} Views.py class AffiliateBaseView(generic.CreateView): model = Affiliates form_class=AffiliateForm template_name = "affiliates/affiliate.html" def get_form_kwargs(self, *args, **kwargs): kwargs = super(AffiliateBaseView, self).get_form_kwargs(*args, **kwargs) kwargs['user'] = self.request.user return kwargs def get_initial(self, *args, **kwargs): initial = super(AffiliateBaseView, self).get_initial(**kwargs) return initial def form_valid(self, form): form.instance.user = self.request.user return … -
How can I override the save function for serializers? (Django Rest Framework)
I'm using Django REST Framework and using the .save() method I'm getting an error saying that I have to override the .create() method. I'm using multiple nested objects. I have no idea how to override that function, thanks in advance!! This is my models.py file from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Pizzas(models.Model): # DB model to keep info about pizza name = models.CharField(max_length=200) description = models.TextField() # Ingredients n stuff photo = models.ImageField(upload_to='main/img', default='main/img/pizza.jpg') price = models.IntegerField(default=15) class Meta: verbose_name_plural = "Pizzas" def __str__(self): return self.name class Orders(models.Model): # Orders table user = models.ForeignKey(User, on_delete=models.CASCADE) # who has ordered the pizza/pizzas price = models.IntegerField(default=0) # Price of the orde (make a function or something to calculate this) address = models.CharField(max_length=300) # User gives it content = models.ManyToManyField(Pizzas) # Self explainatory date = models.DateTimeField("Date Ordered", default=timezone.now()) class Meta: verbose_name_plural = "Orders" def __str__(self): return f"{self.user} - {self.price}" My serializers.py file from rest_framework import serializers from main.models import Orders, Pizzas from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id'] class PizzasSerializer(serializers.ModelSerializer): class Meta: model = Pizzas fields = ['name'] class OrdersSerializer(serializers.ModelSerializer): user = UserSerializer(many=True, read_only=True) content = PizzasSerializer(many=True, read_only=True) class … -
Django Profile Project
I have a typical scenario that i want to create a Registration form where anyone can insert First Name, Last Name, Email Id, Username, Password(which can be stored in User table provided by Django) , Bio and Profile Picture(which can't be stored in User table provided by Django) and after registration when user tries to login with Username and Password then he can view his detail and also update them. i have completed the registration part with the help of OneToOne relationship with User table but having a lot of Trouble in viewing and updating them help me with Django Code. Models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) work = models.CharField(max_length=120,null=True) bio = models.TextField(null=True) profile_picture = models.ImageField(upload_to="Profile Pictures",null=True) def __str__(self): return self.user.username login.html <form action="" method="POST"> {% csrf_token %} <div class="modal-body"> <div class="md-form form-sm mb-5"> <i class="fas fa-user prefix fb-text "></i> <input type="text" name="username" class="form-control form-control-sm validate" required> <label data-error="wrong" data-success="right" for="username">Your Username</label> </div> <div class="md-form form-sm mb-5"> <i class="fas fa-envelope prefix fb-text"></i> <input type="email" name="email" class="form-control form-control-sm validate" required> <label data-error="wrong" data-success="right" for="email">Your email</label> </div> <div class="md-form form-sm mb-5"> <i class="fas fa-envelope prefix fb-text"></i> <input type="text" name="work" class="form-control form-control-sm validate" required> <label … -
Django | Field 'id' expected a number but got OrderedDict()
I have a create endpoint in restframework that works fine. views is as follows class ItemAddAPIView(CreateAPIView): serializer_class = ItemSerializer parser_classes = [MultiPartParser] def create(self, request, *args, **kwargs): try: serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) item_obj = Item.objects.create(title=serializer.data['title'], discount=serializer.data['discount'], rate_per_kg=serializer.data['rate_per_kg']) return Response(serializer.data, status=HTTP_201_CREATED) except Exception as e: print("error :: ",e) serializer is given below: class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields='__all__' This works fine. But when I add a SerializerMethodField() to the Serializer it gives the error : Field 'id' expected a number but got OrderedDict([('title', 'erwre'), ('rate_per_kg', 53.0), ('discount', 5.0)]). class ItemSerializer(serializers.ModelSerializer): images = serializers.SerializerMethodField(method_name='get_image_list') class Meta: model = Item fields='__all__' def get_image_list(self,obj): image_list=[] item_images = ItemImage.objects.filter(item=obj) request = self.context.get('request') for each in item_images: image_list.append(request.build_absolute_uri(each.image.url)) return image_list -
Django Web Form - Update YAML File Variables
Is it possible to update YAML file variables from a Django web form? I ask because I need to update a YAML file based on user input without giving them access to the YAML file itself. I was thinking that a Django web form would be suitable for this task in my brief reading of it, but I'm not sure if this is possible or not and if it's worth researching any further. -
When will Django officially support one nosql database?
When will Django officially support one at least nosql database? -
Asked to install Pillow when requirement is already satisfied
I'm trying to run a Django Project I had running before formatting my PC (Windows 10). Now I tried to do: pip install -r requirements.txt And everything install ok, no errors. But when trying to run my Django app with: python manage.py runserver I get: ERRORS: shop.Category.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". shop.Pack.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". shop.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". shop.Profile.photo: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". shop.Sample.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". shop.UnitaryProduct.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". System check identified 6 issues (0 silenced). Then when I try to do: pip --no-cache-dir install Pillow It appears to have installed it but still cannot run my … -
Django CustomUser Signup attribute error: 'str' object has no attribute 'META'
I have the following error when I try to signup to my application: AttributeError at /signup/: 'str' object has no attribute 'META' Whatever I did, I couldn't resolve the error. This is the SignUp view (I redirect to a "redirect" view after successful signup, this is here only for being placeholder, printing the logged in users email in a template) views.py def redirect(request): return render(request, 'accounts/redirect.html') def signup(request): if request.method == 'POST': form = SignUpForm(data=request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('accounts:redirect') else: form = SignUpForm() return render(request, 'accounts/signup.html', {'form': form}) I have a CustomUser object as my Authentication User model in my Django application. I use CustomUserCreationForm, and SignUpForm which inherits this CustomUserCreation Form (You can see below the CustomUser model, CustomManager as well as the CustomForms.) models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email adress', unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_exhibitor = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Meta: verbose_name = 'user' managers.py class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User … -
django filter on multiple GET parameters
I have a search field and two extra search parameters (category and platform) on the side of the results on my search page. my queryset looks like this on the list view: def get_queryset(self): query = self.request.GET.get('q') category = self.request.GET.get('category') platform = self.request.GET.get('platform') text_query = ( Q(name__icontains=query) | Q(category__name__icontains=query) | Q(tags__name__icontains=query) ) object_list = Results.objects.all() if query: object_list = object_list.filter( text_query ) if category: object_list = object_list.filter(Q(category__name=category)) if platform: if platform == "windows": object_list = object_list.select_related('versions').latest().filter(windows=True) elif platform == "linux": object_list = object_list.select_related('versions').latest().filter(linux=True) elif platform == "mac": object_list = object_list.select_related('versions').latest().filter(mac=True) return object_list I know the last part can be one line with exec, but this does not work because you cant filter the result of a filter (object_list). What is the best way to filter based on multiple GET parameters? -
user.is_authorised returns false in particular django template
username is showing up in all templates except one template. What is missing there? user.is_authorised returns false in one particular template. -
Galler images very big in size using html
Is there a way to make these images smaller? and fit into a box? I followed according to a tutorial and images are bigger.This is zoomed out to 25% view. I'm looking for a way to resize the images to fit into the gallery like view, in the tutorial, the person ended up with a perfect gallery type output unlike me xd .This is for a django project and thanks in advance :) This is normal zoomed out view html code: {% extends 'portofolio/base.html' %} {% load static %} {% block content %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.8.2/css/lightbox.min.css"> <link rel="stylesheet" href="{% static "portofolio/css/photogallery.css" %}"> <body> <h1 style="margin-top: 70px;">Image Gallery</h1> <div id="jLightroom" class="jlr"> <a href="{% static "portofolio/images/1.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/1.jpg" %}"> </a> <a href="{% static "portofolio/images/2.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/2.jpg" %}"> </a> <a href="{% static "portofolio/images/3.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/3.jpg" %}"> </a> <a href="{% static "portofolio/images/4.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/4.jpg" %}"> </a> <a href="{% static "portofolio/images/5.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/5.jpg" %}"> </a> <a href="{% static "portofolio/images/6.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/6.jpg" %}"> </a> <a href="{% static "portofolio/images/7.jpg" %}" data-lightbox="lb1" class="jlr_item"> … -
Implementing pageviews in Django
I am working on a small a small website and I want to display the total views of every object in the detail view. But sincerely, I don't know how to actualise this. Let me post my models.py and views.py Models.py class Music(models.Model): artist = models.CharField(max_length=300) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(default='', blank=True, unique=True) thumbnail = models.ImageField(blank=False) audio_file = models.FileField(default='') uploaded_date = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-uploaded_date'] def save(self): self.uploaded_date = timezone.now() self.slug = slugify(self.title) super(Music, self).save() def __str__(self): return self.title + ' by ' + self.artist def get_absolute_url(self): return reverse('music:detail', kwargs={'slug': self.slug}) Views.py return Music.objects.order_by('-uploaded_date') def detail(request, slug): latest_posts = Music.objects.order_by('-uploaded_date')[:5] song = get_object_or_404(Music, slug=slug) comments = Comment.objects.filter(post=song) if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = song comment.save() return HttpResponseRedirect(song.get_absolute_url()) else: comment_form = CommentForm() context = { 'latest_posts': latest_posts, 'song': song, 'comments': comments, 'comment_form': comment_form, } return render(request, 'music/detail.html', context) -
Does 'list_editable' work with files in the django admin?
I'm trying to get a way to rename my uploaded files in the django admin using list_editable. I tried it but it doesn't seem to be working, since it only shows a 'Save' button below, but nowhere where I can edit my files names. Is this even possible or does it now work with FileFields? I looked on forums but nothing seemed to be similar to what I was trying to do. Thanks in advance! -
Django how to query a nested object
I have a Index model that saves all object IDs/PKs of all my diffrent post models: collectable_post_models = models.Q(app_label='App', model='post_model1') | models.Q(app_label='App', model='post_model2') | models.Q(app_label='App', model='post_model3') class PostCollection(models.Model): id = models.AutoField(primary_key=True, editable=False) content_type = models.ForeignKey(ContentType, limit_choices_to=collectable_post_models, related_name='collections', related_query_name='collection', on_delete=models.CASCADE, null=True, blank=False) object_id = models.CharField(max_length=36, blank=False) content_object = GenericForeignKey('content_type', 'object_id') date_added = models.DateTimeField(auto_now_add=True, blank=False) class Meta: unique_together = ('content_type', 'object_id') verbose_name = "Post Collection - HELPER TABLE" verbose_name_plural = "Post Collections - HELPER TABLE" ordering = ['-date_added'] Each of my post models looking very similar e.g.: class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Title", max_length=40) collection = GenericRelation(PostCollection, related_query_name='post') Now I have a view that should generate a list of proposals the user may also like to see: def post_proposals(): post_elements = sorted( chain( PostCollection.objects.values_list('id', flat=True), ) ) post_elements_list = list(post_elements) post_proposals = random.sample(post_elements_list, 1) # 1 is the number of elemets that should get returned return post_proposals At my template I currently just get back the ID value of the PostCollection object but actually I want to get the title of the post element behind the Index object. How do I do that? This is what I do at my template e.g.: {% for … -
Django: cannot connect to web with domain name (but fine with IP address)
for the life of me I cannot figure what is going on with this deployment. I am using EC2, route 53 domain(freshly acquired a domain), nginx and gunicorn with supervisor. similarly to this post How do I deploy Django app to (AWS) domain name?, I can acess the app in the web with the IP address but not with the domain name. it gives the error : 'this site refuse to connect'. But when I ping the website with nmap on the port and IP address and also with the domain name i get a positive response. Here are my ALLOWED_HOSTS in settings.py ALLOWED_HOSTS = ['xx.xxx.xx.xx', 'mysite.net', 'www.mysite.net'] nginx django.conf server { listen 80; server_name xx.xxx.xx.xx mysite.net www.mysite.net; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/exostocksaas/app.sock; } location /static { autoindex on; alias /home/ubuntu/exostocksaas/inventory4/collected_static/; } } Really I cannot figure out what is going, could it be that the domain has not propagated yet, but why would it give me such error then? I hope that someone has a clue, I am looking everywhere and I feel like I might up accidently breaking my setup! -
Cannot use pipenv to install django. PermissionError: [Errno 13] Permission denied: 'Pipfile'
Currently trying to install django 2.1 in my command prompt through pipenv command. However there's an error where it says Pipfile access denied. C:\windows\system32>pipenv install django==2.1 Traceback (most recent call last): File "c:\users\lenovo\appdata\local\programs\python\python38-32\lib\runpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\lenovo\appdata\local\programs\python\python38-32\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Scripts\pipenv .exe\__main__.py", line 9, in <module> File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\core.py", line 764, in __call__ return self.main(*args, **kwargs) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\core.py", line 717, in main rv = self.invoke(ctx) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\core.py", line 956, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\decorators.py", line 64, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "c:\users\lenovo\appdata\local\programs\python\python38-32\lib\site-packa ges\pipenv\cli\command.py", line 235, in install retcode = do_install( File "c:\users\lenovo\appdata\local\programs\python\python38-32\lib\site-packa ges\pipenv\core.py", line 1734, in do_install ensure_project( File "c:\users\lenovo\appdata\local\programs\python\python38-32\lib\site-packa ges\pipenv\core.py", line 567, in ensure_project project.touch_pipfile() File "c:\users\lenovo\appdata\local\programs\python\python38-32\lib\site-packa ges\pipenv\project.py", line 677, in touch_pipfile with open("Pipfile", "a"): PermissionError: [Errno 13] Permission denied: 'Pipfile' I'm new. I'm in the process of learning on how to build a website. -
How to return a 404 in case of a queryset is true for Django DetailView
Having a field inside my model class myModel(models.Model): published = models.BooleanField( default=False, help_text="Whether this is visible." ) I'm looking for a way to render a 404-error on corrosponding django.views.generic.DetailView in case of the boolean is False. How can this be achieved? -
3d models path in django using three js
Hi anyone knows about what is the correct way of giving 3d model path in django. Like in which folder i have to put my 3d model. Btw i am using three js. Error Failed to load resource: the server responded with a status of 404 (Not Found) {% load static %} <!DOCTYPE html> <html> <head> <title> 3D Model </title> <link rel="stylesheet" type="text/css" href="{% static 'css/cona.css' %}"> </head> <body> <canvas id="cona"> </canvas> <script src="{% static 'js/three.min.js' %}"></script> <script src="{% static 'js/OrbitControls.js' %}"></script> <script src="{% static 'js/GLTFLoader.js'%}"></script> <script src="{% static 'js/donutCopy.js' %}"></script> <script > var icing="{% static 'INO.glb'%}" </script> </body> </html> </pre> -
Site cannot be reached error while accessing admin page page in Django
I have tried running my Django code it's working fine for all pages except the admin page it takes a long time to run and at last displays message that site cannot be reached. Please help me with this. Note: All other pages like index, about, welcome, home all are working fine. Even sometime admin page comes but most of the time it doesn't -
Range of dates and go through each date at a certain hour
I am trying to iterate through a date range (8/1/19-3/31/20) and go through each date and print a count for hours 4 AM, 5 AM, and 6 AM. However, I'm having some general trouble getting the required dates and iterating. I keep getting various datetime and datetime.timedelta errors. Here is the code: start = datetime.timedelta(2019, 8, 1) end = datetime.timedelta(2020, 3, 31) days = (end - start).days + 1 for i in (start + end for n in range(days)): for j in range(4, 7): print "Hour: ", i print ("Residents: ", Checkin.objects.filter(desk__name="Desk", datetime__hour=i.hour(j)).count()) print("Guests: ", Guest.objects.filter(desk="Desk", datetime__hour=i.hour(j)).count()) I am just hoping for the best way to do this, as I am trying to gather this data for someone. The error I'm getting currently from this code is timedelta doesn't have an hour attribute. I'm just hoping for help getting this code functional. I am filtering Checkin and Guest by their datetime field, which is: datetime = models.DateTimeField(auto_now_add=True) -
Django how to put togheter form, crispy and ajax call
I have an interesting question for you. I have the following form created with a simple html structure: <form id="addUser" action=""> <div class="form-group"> <input class="form-control" type="text" name="name" placeholder="Name" required> </div> <div class="form-group"> <input class="form-control" type="text" name="address" placeholder="Address" required> </div> <div class="form-group"> <input class="form-control" type="number" name="age" min="10" max="100" placeholder="Age" required> </div> <button class="btn btn-primary form-control" type="submit">SUBMIT</button> </form> And now I introduce you my javascript code to send the data from front-end to back-end using an ajax call. {% block javascript %} <script> // Create Django Ajax Call $("form#addUser").submit(function() { var nameInput = $('input[name="name"]').val().trim(); var addressInput = $('input[name="address"]').val().trim(); var ageInput = $('input[name="age"]').val().trim(); if (nameInput && addressInput && ageInput) { // Create Ajax Call $.ajax({ url: '{% url "crud_ajax_create" %}', data: { 'name': nameInput, 'address': addressInput, 'age': ageInput }, dataType: 'json', success: function (data) { if (data.user) { appendToUsrTable(data.user); } } }); } else { alert("All fields must have a valid value."); } $('form#addUser').trigger("reset"); return false; }); It works perfectly, But now I want to implement it. I want to insert the form not with html code, but with crispy_forms. How can I do it? I tried but the ajax does not work. Could you help me? -
Project structure Django/Plotly/Websocke - display data from DB with Plotly
I'm just getting started with Django, Plotly and SQL so this question is relatively general, but I'm struggling to get my head around the general structure of a project i'm working on. I've set myself a learning task of setting up a page that displays charts of asset prices (Apple stock, Bitcoin etc). I will then build this out to have user accounts and various other functionality. This leads me to a few questions: 1) Should I store the price data etc in the same database as Django is using for the rest of the page or is it best practice to separate these out. I currently have 'default' set to a local postgres db, should i set up a new db for all the asset price data? 2) I currently plan to connect a websocket stream to receive the live price data. Each time a message is received I then write that data to the database. My plotly charts would then update. Is that the most efficient way to do this or is there away to connect the ws directly to the database without the connector? This database will be written to at potentially the same time the page … -
Django dumpdata into docker
I have a docker container where is running a django app. I'm trying to backup my database using cron. The django app is located in /usr/src/app. This is my crontab file:*/1 * * * * cd /usr/src/app && python manage.py dumpdata>dump.json The issue is that the dump.json file is created but nothing is in it. I tried to run directly python manage.py dumpdata>dump.json bash in my container and it actually works (dump.json is filled with my db content). Could you help me please. Thank you.