Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i build my react front end and django backend application for a 32 bit system?
I am working on an application for a 32 bit PC. i have almost completed the front end and backend. now i want to build executable for my application (if that's even possible in case of react and django). I want to run the application on a 32 bit PC. I myself have a 64 bit machine. Please guide me how do i do that. For django application i can create a virtual environment? but would that require me to install python on the system i want to install the app. and in case of react how can i build it from my PC to work on 32 bit PC. Thanks in advance. -
how to combine quires in django
i am creating a website where user will download videos , now i want to query the artist and it's videos, i already have one to many field but i have no idea how to do in views.py this is my models from django.db import models from embed_video.fields import EmbedVideoField # Create your models here. class Video(models.Model): video_author = models.CharField(default='Bongo Media', max_length=20) video_title = models.CharField(max_length=100) video_file = models.FileField(blank=True) video_image = models.ImageField(default='image.png') video_embed_link = EmbedVideoField(blank=True) video_descriptions = models.TextField(max_length=100, blank=True) video_pubdate = models.DateTimeField(auto_now=True) is_recommended = models.BooleanField(default=False) def __str__(self): return self.video_title class Artist(models.Model): artist_picture = models.ImageField(upload_to='media') artist_name = models.CharField(max_length=100) artist_songs = models.ForeignKey(Video, on_delete=models.CASCADE) def __str__(self): return self.artist_name and this is my views.py from django.shortcuts import render, get_object_or_404 from .models import Video, Artist # Create your views here. def home(request): artist = Artist.objects.all() videos = Video.objects.all().order_by('-video_pubdate') context = { 'videos': videos, 'artist': artist } return render(request, 'index.html', context) def detail(request, pk): video_detail = get_object_or_404(Video, pk=pk) context = { 'video_detail': video_detail } return render(request, 'detail.html', context) -
Adding django auth token to ajax call for external api
I have a django app (called Client) that makes an API call to another django app api (Master) and I'm logging in the users using OpenID Connect (via django-keycloak). My question is how to securely add the users access token to the header of an ajax call on the Client site to the Master site. The obvious solution is to have in my template something like:: "beforeSend": function (xhr) { xhr.setRequestHeader('Authorization', "Bearer {{ user.token }}"); }, But exposing the token seems like a bad idea. I could also create an api in the Client system that called the API in the Master system and added the token behind the scenes, but this is going to double the time for each round trip and also seems a bad idea. What is the best solution to this problem? -
How to unit test a file upload in Django?
I want to test a view that accepts .zip file as request. So far, I tried this: def test_upload_zip(self): with open('zip_file.zip', 'rb') as file: response = self.client.post(reverse(self.url), {'zip_file': file}, format='multipart') The data I am getting at the view when I do print(request.data) is: <QueryDict: {'zip_file': [<InMemoryUploadedFile: zip_file.zip (application/zip)>]}> But, for my actual request I want data in multipart like this: <QueryDict: {'zip_file': ['data:application/zip;base64,UEsDBBQAAAAIAK1xmF................AAAA=']}> In real request, I am not sending any content-type from my frontend. When I tried to put content_type='multipart/form-data in my test like this: def test_upload_zip(self): with open('zip_file.zip', 'rb') as file: response = self.client.post( reverse(self.url), {'zip_file': file}, content_type='multipart/form-data' ) I got this error: django.http.multipartparser.MultiPartParserError: Invalid boundary in multipart: None What am I doing wrong, and how can I get the desired data in my request.data? -
How do i load css file into html in Django
I'm trying to create a Django app and i have made all the static settings like Settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR,'CricketTeamManagement/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' URLS.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('Management.urls')) ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) I have also created a static folder in Main project folder and ran python manage.py collectstatic it created a new static folder outside and it has admin folder in it and sub folders like js,css,font,images and collectstatic collects the images and stores in this folder. I see static files are clearly working. All the models.py imagefields are uploaded to media folders and even that works. The Problem comes here My css files are not taking its styles and not altering my html elements. If I have the below code in html file the styling works and if i separate it to a css folder and create a css file by removing style tag it is not working. <style> body { background-color: powderblue; } h1 { color: blue; } p { color: red; } </style> when i saw the css file Not Found … -
Obtaining user's timezone
I'm making a website and need to know the user's timezone. I know I could simply ask them for it, but think some users may not know their timezone and feel there must be a more user-friendly kinda way to get it (rather that having users Google their timezone or something if they dont know it). Maybe there is a way to grab their timezone without having to specifically ask them? Or maybe there is a Django widget which displays a list of citys which the user can select theirs from and that will give me their timezone? Or maybe there's simply no user-friendlier way than simply asking them for it. Thank you. -
Django Choice Field rename first option
Django 3 Enum like field generates an addition option like <option value="" selected="">---------</option> How to Rename this like <option value="" selected="">Select an option</option> class Student(models.Model): class YearInSchool(models.IntegerChoices): FRESHMAN = 1, 'Freshman' SOPHOMORE = 2, 'Sophomore' year_in_school = models.IntegerField( choices=YearInSchool.choices, default=YearInSchool.FRESHMAN, ) -
while filtering datatable server side Cannot resolve keyword 'priority' into field. Choices are: eventname, id, key, timestamp
I'm using django-rest-framework-datatables to filtering/pagination/sorting datatable when using rest-framework, it's working correctly with all fields except one, it's show error "Cannot resolve keyword 'priority' into field. Choices are: eventname, id, key" i think that the problem is: this field not appear in database table model class CachedEvent(models.Model): key = models.CharField(max_length=255) timestamp = models.DateTimeField() eventname = models.CharField(max_length=255) @property def priority(self): eventtype, created = EventType.objects.get_or_create( eventname=self.eventname ) return eventtype.priority viewSet: class EventViewSet(viewsets.ReadOnlyModelViewSet): queryset = CachedEvent.objects.all() serializer_class = CachedEventSerializer serializer: class CachedEventSerializer(serializers.ModelSerializer): id = serializers.CharField(source='original_id') class Meta: model = CachedEvent fields = ['key', 'timestamp', 'id', 'eventname', 'priority'] can help me please -
Import statements not being recognized in Django [closed]
I am using Django = 2.1 Python = 3.6 Pycharm Community Edition Import statements in one of my apps are not being recognized but the same import statements in other apps are working properly. Image of apps import staements not being recognized Image of import statements being recognized in other app of same project I have tried deleting .idea and I have also made sure that I have init.py in my apps and I have also deleted and reinstalled pycharm. -
Django monthly sums for a specific filter
I have the following models structure: Conto | Sottocategoria | Price | Quantity | Total* | Date of purchase Conto 1 | Product_a | 10 | 1 | 10 | 1/01/2020 Conto 1 | Product_a | 15 | 1 | 15 | 1/01/2020 Conto 2 | Product_b | 10 | 2 | 20 | 1/02/2020 I want to have the monthly sum for each "conto". Something like this: Conto | Gen | Feb | Mar | Apr | May | Jun | .... Conto 1 | 25 | 0 | 0 | 0 | 0 | 0 | .... Conto 2 | 0 | 20 | 0 | 0 | 0 | 0 | .... This one my models.py: class Tipologia(models.Model): nome= models.CharField('Categoria', max_length=30) class Sottocategoria(models.Model): tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE) name = models.CharField() class Conto(models.Model): nome=models.CharField() class Materiale(models.Model): conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True) tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE, null=True) sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True) quantita=models.DecimalField() prezzo=models.DecimalField() data=models.DateField(default="GG/MM/YYYY") -
How to implement alive and readyness with django-health-check
We are using kuberntes and need two different endpoints one for health and one for alive. For some reasons we chosse https://github.com/KristianOellegaard/django-health-check. Its easy to implement a second view for alive which is loaded, but - this view is empty - I do not understand how I could configure the plugings which should be used for the view. class AliveCheck(MainView): # template_name = 'myapp/health_check_dashboard.html' # customize the used templates def __init__(self): self.plugins.clear() self.plugins.append(DiskUsage()) def get(self, request, *args, **kwargs): errors = super(MainView, self).run_check() return super(MainView, self).get(request, args, kwargs) Any ideas? -
Django - Correct Use of Mixins with CBVs
I just started to shift from function-based views to class-based views, as I realize more and more the benefits of the latter, especially regarding the modularity that you can achieve via mixins. However, as CBVs and Mixins are still quite new to me, I wanted to check, if I understand the basic concepts correctly: Example: class ReportingMixin1(object): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['reportingmixin1_context'] = 'test1' return context class ReportingMixin2(object): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['reportingmixin2_context'] = 'test2' return context class MyTemplateView(ReportingMixin1, ReportingMixin2, TemplateView): template_name = 'test4.html' My questions are the following: With function based views I would do context = {'reportingmixin1': 'test1} but I see that with class based views this is always done via context['reportingmixin1'] = 'test1 . Why is this the case? I assume one reason is that when combining multiple mixins in a TemplateView (as in the code in my example) but with context = {'reportingmixin1': 'test1} and context = {'reportingmixin2': 'test2} I would initiate or redefine the context dictionary in each mixin, so you would have only access to the context keys I defined in my mixin that is called last? What is context = super().get_context_data(**kwargs) doing exactly? I read that it is "calling … -
How to solve "Blocked:CSP" error Passit (Django)
I'm not sure if this is the right stack exchange but i think this one fits my question the most. I was searching for an Free Opensource web based password manager to manage passwords for me and our team and found Passit (passit.io). I wanted to test this tool so installed an ubuntu 18 server with docker, postgreSQL and nginx and followed the installation instructions to run passit docker: https://passit.io/install/ I configured Passit via the web based installation wizard and now i can see the passit web interface. When i try to create an account the application does not respond. When i check the Google dev-tools i see that the http://passit.axx/account/register request gets an blocked:CSP response. During an attempt to solve this issue, i found that i can "enable" the Django admin interface by logging in into the container and set the ENABLE_DJANGO_ADMIN setting in the passit>settings.py to True. I tried to login here with just some random credentials and got this error: Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being … -
Django - how to change email field error measge
I have a django email field when email is entered wrongly it shows custom error message please include an @ in email address how can i change the error message class confirmmail(forms.Form): emailid = forms.EmailField(max_length=100,widget=forms.TextInput(attrs={'class': 'form-control user_name_textbox_style', 'placeholder':'Email Address', 'type':'email','required':'true','ng-model': 'email_from_forgotpassword'})) -
trying to createsuperuser on heroku but it throws me a typeError
i tried this command to createsuperuser using this command "heroku run python manage.py createsuperuser" but it always throws me this error Running python manage.py createsuperuser on ⬢ django-blog-web-app... up, run.4727 (Free)enter code here Username (leave blank to use 'u10279'): ###################### Email address: ####################### Password: Password (again): '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.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/models.py", line 158, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/models.py", line 141, in _create_user user.save(using=self._db) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/models/base.py", line 745, in save self.save_base(using=using, force_insert=force_insert, File "/app/.heroku/python/lib/python3.8/site-packages/django/db/models/base.py", line 793, in save_base post_save.send( File "/app/.heroku/python/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 173, in send return [ File "/app/.heroku/python/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 174, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/app/Users/signals.py", line 10, in create_profile Profile.objects.create(user=instance) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/models/query.py", line 433, in create obj.save(force_insert=True, using=self.db) TypeError: save() got … -
TemplateDoesNotExist error due to a comment
I'm in the process of making a website with Django and have yet to create order_snippet.html. When I add {% include "order_snippet.html" %} I expect a TemplateDoesNotExist error, but I put this in the payment.html and commented it out like this: <!-- {% include "order_snippet.html" %} --> yet I still have a TemplateDoesNotExist error. I thought comments weren't read by html? How come this raises an error? -
using python & django for new huge human resources system... which is better react js or angular?
using python & django for new huge human resources system... which is better react js or angular? we are developing new human resources system with huge data... we will use python as a back end... which is better to use as a front end reactjs or angular? we need fast & stable system... and which is better to serve single page request? class HelloMessage extends React.Component { render() { return ( <div> Hello {this.props.name} </div> ); } } ReactDOM.render( <HelloMessage name="Taylor" />, document.getElementById('hello-example') ); -
my pipenv doesnt create a pipfile and pipfile.lock in any of my projects folders anymore
It used to automatically create these files in the folder I was working in, in the command line. If I were to say install django... C:\Users\Admin\Desktop\Djangoproj>pipenv install django Installing django… Adding django to Pipfile's [packages]… Installation Succeeded Installing dependencies from Pipfile.lock (536933)… ================================ 9/9 - 00:00:02 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. This is what I get. I have an empty folder. I dont get the pipfile or pipfile.lock like I am supposed to. Has anyone encountered this before? Is there a solution to this? I have already uninstalled pipenv and reinstalled the package a few times already. Same thing goes for installing requests package. C:\Users\Admin\Desktop\Djangoproj>pipenv install requests Installing requests… Adding requests to Pipfile's [packages]… Installation Succeeded Installing dependencies from Pipfile.lock (536933)… ================================ 9/9 - 00:00:02 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. C:\Users\Admin\Desktop\Djangoproj>ls 'ls' is not recognized as an internal or external command, operable program or batch file. C:\Users\Admin\Desktop\Djangoproj> -
how to make icons <i class="fas fa-minus mr-2"></i> display in template
I am trying to add some icons to my project template. I think i am putting them in the right place but they are not displaying when i look at the template. I have even tried placing the icons in other places but it still doesn't display. here is the place where the icons are on the template <td> <i class="fas fa-minus mr-2"></i> {{ equipment_order_item.quantity }} <i class="fas fa-plus ml-2"></i> </td> -
Web Development Learning Guidance [closed]
Can anyone acqauint me with basic Web Development if I'm a complete beginner? And guide me as to how to learn it? I know C++ and Python but want to start to learn web dev. What courses do you suggest? (Prefarably Free) Please endow me with all the knowledge you have! -
How to apply ManyToManyField to non primary key field?
I have a model A which has name and server_permission attributes. I would like to use both of these fields in my model B, but so far with no luck. Could you please help me? class A(models.Model): name = models.CharField(primary_key=True, max_length=50, unique=True) server_permission = ArrayField(models.CharField(max_length=10, blank=True),size=8) class B(models.Model): zuya_server = models.ForeignKey(A, on_delete=models.CASCADE, default='None',related_name='zuya_server') account_permission = models.ManyToManyField(A,db_column="server_permission",related_name='account_permission') -
Displaying foreign key values
My models.py looks like that: class Order(models.Model): items = models.ManyToManyField(OrderItem) class OrderItem(models.Model): (item in the cart) item = models.ForeignKey(Item, on_delete=models.CASCADE) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) brand = models.ManyToManyField(Brand) size = models.ManyToManyField(Size, blank=True) class Accessory(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) brand_accessory = models.ManyToManyField(BrandAccessory) So currently the field item in my OrderItem model displays the title and quantity of the item in Item model: def __str__(self): return f"{self.quantity} of {self.item.title}" Item is connected with OneToOneField with Bike and Accessory. Is it possible to display the brand and size of the Bike if its added to OrderItem and brand_accessory if Accessory is added to the OrderItem? It would look like {quantity} {item.title} (if bike)> {bike.brand} {bike.size} (if accessory)> {accessory.brand_accessory} -
How to fix trouble with urls better django
I have a section residential interiors on the site, so the typical url looks like this https://caparolcenterspb.ru/decision/livingrooms/kitchen/provans/ (room and style) However different rooms may have the same styles and when searching for styles in views.py it may output several styles and an error views.py selected_room = Room.objects.get(slug=rmslg) style = Style.objects.get(slug=stslg) When you try to replace slug with different styles depending on the room(for example, provans_kitchen), an error occurs in the template(just put provans by default will not work) residentialInteriors.html {% for room in all_rooms %} <li class="menu__item menu__item_interiors"><a href="{% url 'decision:style' rmslg=room.slug stslg='provans' %}">{{ room.name }}</a></li> {% endfor %} I have 2 solution ideas(preferably 2): either change stslg in template by default to 'provans_' + str(room. slug), but this line does not work(especially not the fact that provans will be everywhere) either search for style in views.py not only for stslg, but also for rmslg, but for this in the style model, you need to create a room field inherited from the room model, which also does not work for me, since Room is declared further than Style models.py class Style(models.Model): name = models.CharField(max_length=30) full_name = models.CharField(max_length=50) slug = models.SlugField() img = models.ImageField(upload_to='img/') walls = models.TextField() floor = models.TextField() roof … -
Exception Value: Invalid HTTP_HOST header: 'products_web:8001'. The domain name provided is not valid according to RFC 1034/1035
Here docker creates containers :- products, orders, email, nginx and postgres. enter image description here I have to get product details from orders service, for that i used requests pipe link response = requests.get("http://products_web:8001/products/fetch/?prod_id=%s" % product).json() when i execute, getting response in html format defining error as Exception Value: Invalid HTTP_HOST header: 'products_web:8001'. The domain name provided is not valid according to RFC 1034/1035. following is the docker-compose.yaml version: '2' services: products_web: build: ./products command: bash -c "python3 ./products/manage.py makemigrations && python3 ./products/manage.py migrate && python3 ./products/manage.py runserver 0.0.0.0:8001" volumes: - .:/code ports: - "8001:8001" restart: always depends_on: - datab links: - datab emails_web: build: ./emails command: bash -c "python3 ./emails/manage.py makemigrations && python3 ./emails/manage.py migrate && python3 ./emails/manage.py runserver 0.0.0.0:8002" volumes: - .:/code ports: - "8002:8002" restart: always depends_on: - datab links: - datab orders_web: build: ./orders command: bash -c "python3 ./orders/manage.py makemigrations && python3 ./orders/manage.py migrate && python3 ./orders/manage.py runserver 0.0.0.0:8003" volumes: - .:/code ports: - "8003:8003" restart: always depends_on: - datab links: - datab stdin_open: true tty: true datab: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres nginx: image: nginx:latest build: ./web ports: - "8084:80" links: - products_web - orders_web - emails_web depends_on: - products_web - … -
Django. SQLite. How to improve query speed/code and sorting speed within a list
I wrote a piece of a very ineffective, but working code, which is running approx. 24 hours to complete the task. I have a list choices = ["qwert", ... "ABCDE", ...], length of the list is 2...1000. I am making changes in the SQLite table as follows: first bad code: def update_records_in_bigtable(uid_br_next, choices): for k in choices: q = BigTable.objects.all().filter(Q(field1__exact=k) | Q(field1__exac2=k) | Q(field3__exact=k) & Q(field3=0) ).update(uid_nr=uid_nr_next) second bad code: def add_records_to_crossreftable(choices, obj): for k in choices: try: x = CrossRefTable.objects.create(field1=k, uid_nr_foreign=obj) except: x = DuplicatesTable.objects.create(field1=k) third bad code: def get_next_list(k): choices=list(BigTable.objects.all().filter(Q(field1__exact=k) | Q(field2__exact=k) ).values_list('field1', 'field2', 'field3', ) ) choice=[] for ch in choices: ch=set(ch) # remove same members if "" in ch: ch.remove("") # remove empty members if "ABC" in ch: ch.remove("ABC") # remove special member choice=choice + list(ch) choice=set(choice) return list(choice) Please help to improve. Thank you