Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'WSGIRequest' object has no attribute 'profileaccount'
I am getting the following error and I want to return a model profileaccounts.id but it is not within WSGIRequest. Is there a way to find all the objects with WSGIRequest? ERROR LOG AttributeError at /2/detail/ 'WSGIRequest' object has no attribute 'profileaccount' Views.py class ProfileAccountDetailView(LoginRequiredMixin, DetailView): model = ProfileAccount fields = [ 'first_name', 'family_name', 'email', 'account_active', ] def get_success_url(self): return reverse( "profiles:detail", kwargs={'pk': self.request.profileaccount.id}, ) def get_object(self): return ProfileAccount.objects.get( pk=self.request.profileaccount.id ) -
Using Nibabel in Django
I am making a web app that converts .nii files to png(zip). I have implemented the main logic in python but am facing problems porting it to the web app. So I want to create a form that accepts a .nii file and outputs a zip file containing all the .png slices. So far I've written a simple view: Views.py from django.shortcuts import render from .forms import SharingForms from django.http import HttpResponse import imageio,nibabel,numpy from zipfile import ZipFile from .models import NII def index(request, **kwargs): if request.method == 'POST': form = SharingForms(request.POST,request.FILES) if form.is_valid(): for field in request.FILES.keys(): for formfile in request.FILES.getlist(field): file = NII(file = formfile) file.save() response = HttpResponse(content_type='application/zip') zip_file = ZipFile(response, 'w') image_array = nibabel.load(file).get_fdata() if len(image_array.shape) == 4: # set 4d array dimension values nx, ny, nz, nw = image_array.shape total_volumes = image_array.shape[3] total_slices = image_array.shape[2] for current_volume in range(0, total_volumes): slice_counter = 0 # iterate through slices for current_slice in range(0, total_slices): if (slice_counter % 1) == 0: # rotate or no rotate data = image_array[:, :, current_slice, current_volume] #alternate slices and save as png print('Saving image...') image_name = file[:-4] + "_t" + "{:0>3}".format(str(current_volume+1)) + "_z" + "{:0>3}".format(str(current_slice+1))+ ".png" imageio.imwrite(image_name, data) print('Saved.') zip_file.write(image_name) zip_file.close() response['Content-Disposition'] … -
Django Multi Tenant Schemas Media Files Path
I am using Django with Multi Tenant Schemas. Everything is working well on production, but I am having an issue with image media Path. My web server is an Apache2 installed on Ubuntu 18.04, in the site configuration file I have: ''' ServerName qibot.com.br ServerAlias tenant1.qibot.com.br tenant2.qibot.com.br tenant3.qibot.com.br ServerAdmin webmaster@localhost DocumentRoot /var/www/html Alias /static /var/www/qibot_system/static <Directory /var/www/qibot_system/static> Require all granted </Directory> Alias /media /var/www/qibot_system/media/ <Directory /var/www/qibot_system/media/> Require all granted </Directory> ... </VirtualHost> ''' In this way, if the media (image or video) file is requested, django looks for /var/www/qibot_system/media/ instead of /var/www/qibot_system/media/tenant1 or /var/www/qibot_system/media/tenant2 or /var/www/qibot_system/media/tenant3 My question is, there is a way to set the variable on the end of /var/www/qibot_system/media/XXXXXXXXX to provide right path to django? Best Regards -
Django Admin raw_id)fields pop-up selector outside Django admin
Is there a way to implement the pop-up selector of raw id fields outside of django admin? -
Dependent Dropdown form in Admin
I want to build a dependent dropdown form in Admin which has fileds Tag1, Tag2, Tag3, Title and Deadline. It should be such that the user selects some Tag1 and based on it he can select Tag 2. Also Tag3 depends on tag1 choice and the title choice depends on all the above tags in the form. The deadline value is based on the title selected. However if the selected title is "OTHER" he can add add a title manually and also the deadline manually. Here is an approach I tried: Created 4 different models, c1, c2, c3 and task(which saves title and deadline). Error 1: If i use c1's foreign key in c3, it does not run. Error 2: even if i set c3 dependent of C2 I dont get the list of objects in the dropdown for either of them. Error 3: Even after entering the values for new objects, I am unable to make it work. I am working on this since 4 days but I am unable to figure a way out. here's my Code models.py: class c1(models.Model): name = models.CharField(max_length=30, default="Other") def __str__(self): return self.name class c2(models.Model): '''c1_choice=(('Support Staff','Support Staff'), ('Consumables', 'Consumables'))''' c1 = models.ForeignKey(c1, … -
Django and highcharts , making querys
I have two models, here the first model have the prices and the second have the amount of the products. it is like model1 = contract , and model2 = invoice. Model 1 class Model1(models.Model): year = models.PositiveIntegerField(verbose_name="year") price_field1 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) price_field2 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) price_field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) price_field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) price_field4 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) def __str__(self): return str(self.id) Model 2 class Model2(models.Model): model1=models.ForeignKey(Model1,on_delete=models.CASCADE,verbose_name="Model1",related_name='Model1Objects') amount_field1 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) amount_field2 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) amount_field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) amount_field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) amount_field4 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) def __str__(self): return str(self.id) One Model1 ,can have a lot of model2 related to model1 , it is a relationship 1-N i want to do a statistics about model1 per year , so i want to sum all the objects model2 and multiply to the price in model1, something like this: ((sum all amount_field1 related to year 2019) * (price_field1 related to year 2019) + (sum all amount_field2 related to year 2019) * (price_field2 related to year 2019) + ....... ). after that put the result on highcharts. i already have the template , and the values pass to the template in view . VIEW def Estatisticas(request): values = [results here] context = {'values': values} return render(request, 'dashboard/index.html', context=context) When i put the … -
stick footer to bottom django template
Good day, I am trying to stick footer to bottom django template layout, flex box and grid doesn`t help. May be in Django template another way? -
User has no attribute profile
I am currently trying to create a user profile whenever they register and the user is created, the error message shows: RelatedObjectDoesNotExist User has no profile. signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def create_profile(sender, instance, **kwargs): instance.profile.save() views.py from django.shortcuts import render, redirect from .forms import UserRegisterForm from django.contrib.auth import login from django.contrib.auth.decorators import login_required def register(request): if request.method != 'POST': form = UserRegisterForm() else: form = UserRegisterForm(data=request.POST) if form.is_valid(): new_user = form.save() login(request, new_user) return redirect('blog:home') context = {'form': form} return render(request, 'user/register.html', context) @login_required def profile(request): return render(request, 'user/profile.html') models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return self.user.username -
Save relation between anonymous user and a file with user login with foreign key - Django
I am a beginner with programming and trying to make a web app that creates a video programmatically on button click in browser and displays it in the same browser for the user once it's created. I want it to be something like this but the button runs a moviepy script to create the video and upload it to a django model and pass it through a view. Now I am trying to create the relationship between person who clicks the button and the video that is created with foreign key. I want to do this without a login and I see a lot of tutorials about associating a user that is logged in but not so much about anonymous users. Is my approach the right one? I am trying like below and receive the error - video_upload_detail_page() missing 1 required positional argument: 'user_id' .html {% load static %} <html> <head> <title>Title of the document</title> </head> <body> <video width="320" height="240" controls> <source src= "{{ MEDIA_URL }}{{ object.videofile }}" type='video/mp4'> </video> <p></p> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <button id="myClickButton" type="button">Click</button> <div id="myOutput"></div> <input id="id_holder" type="hidden" value="{{ request.user.id }}"> <script> $("#myClickButton").click(function() { // catch and send user id to use in get request // in … -
Call pop up bootstrap modal from another html file
I want to pop up a delete alert message when a delete icon is pressed. The problem is delete pop up modal is in one html file and delete icon is in another html. As I am using django modelform I can not keep bothe of them in a signle html. That's why I have make two different html files. I am trying to connect both of them. But I dont know how to that. I followed an instruction but it is not showing as popup rather it is showing as a normal html. employee_list.html: {% extends "base.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> <div class=""> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-6"> <h2><b>Employees</b></h2> </div> <div class="col-sm-6"> <a href="{% url 'employee:employee-add' %}" data-target="exampleModal" class="btn btn-success" data-toggle="modal"> <span ></span> <i class="material-icons"></i> <span data-feather="plus"></span>Add New Employee </a> <!--<a href="#deleteEmployeeModal" class="btn btn-danger" data-toggle="modal"><i class="material-icons">&#xE15C;</i> <span>Delete</span></a>--> </div> </div> </div> <table class="table table-striped table-hover"> <thead> <tr> <th> <span class="custom-checkbox"> <input type="checkbox" id="selectAll"> <label for="selectAll"></label> </span> </th> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Address</th> <th>Phone</th> <th>Department</th> <th>Designation</th> <th>Actions</th> </tr> </thead> <tbody> <!-- Loop for showing employee list in a table--> {% for employee in object_list %} … -
No access to the Django server at http://127.0.0.1:8000/
I have installed Django to build apps and following the official documentation. Before installing it I have check my Python version (3.5), installed virtualenv and activate it. Everything ok but I can't access the developpement server at 127.0.0.1:8000 in my web browser despite of a successfull python manage.py runserver command. I read this post, but it's not better when I change my settings.py file. Am I missing something ? How can I access 127.0.0.1:8000 in my web browser ? Here is Django message in terminal : Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 15, 2020 - 12:27:55 Django version 2.2.13, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. -
convert MySQL query into Django
SELECT category, COUNT(*) FROM front_end_post_job WHERE post_type = 'job' GROUP BY category i have this query i want to use this in Django how to use this -
Django gets killed on redhat server (Out of memory)
I have a Django project running on a redhat 7.7 server which is a service for training spacy models.(-python v2.7.5 -spacy v2.0.18 -django v1.11.29 -djangorestframework v3.9.4 -django-apscheduler v0.3.0) Redhat kills the entire django process after 3-10 iterations during execution of the training job. The code: def train_spacy_model(model_id, storage_path, file_id, call_back_url): status = "fail" try: if os.path.isfile(os.path.join(storage_path, "spaCy_model_" + model_id + ".pkl")): pickle_file: BinaryIO = open(os.path.join(storage_path, "spaCy_model_" + model_id + ".pkl"), "rb") nlp = pickle.load(pickle_file) else: nlp = spacy.load("en_core_web_sm") pickle_file: BinaryIO = open(os.path.join(storage_path, "dataset_" + model_id + ".pkl"), "rb") training_data = pickle.load(pickle_file) pickle_file.close() ner = nlp.get_pipe('ner') for _, annotations in training_data: for ent in annotations.get('entities'): ner.add_label(ent[2]) other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner'] with nlp.disable_pipes(*other_pipes): optimizer = nlp.begin_training() for i in range(100): print("Starting iteration " + str(i)) print(sys.getrefcount(nlp)) losses = {} for text, annotations in training_data: nlp.update( [text], [annotations], drop=0.2, sgd=optimizer, losses=losses ) print(losses) fname = os.path.join(storage_path, "spaCy_model_" + model_id + ".pkl") with open(fname, "wb") as f: pickle.dump(nlp, f) status = "success" os.remove(os.path.join(storage_path, "dataset_" + model_id + ".pkl")) except Exception as e: print(e) train_call_back(model_id, file_id, call_back_url, status) The error code in redhat logs (/var/log/messages) is : Jun 15 11:12:26 AZSG-D-CTBT03 kernel: Out of memory: Kill process 20901 (python) score 618 or … -
How To Access Many Field In One-To-Many Relationship
I have two different user types, Teachers and Students. My students have a one-to-many relationship with a Teacher (a student can have one teacher / a teacher can have many students). I am able to access a student's Teacher in templates like this user.student.teacher, but I dont know how to access a list of a Teacher's Students? From a teacher's profile page id like to print a list of their students. # override default User model class User(AbstractUser): user_type = models.CharField(choices=USER_TYPES, max_length=255, default='student') class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, default=None, null=True) Thank you. -
y-a t-il un moyen de lier un champ d'un formulaire a un autre? [closed]
bonjour , je m'interesse à django depuis peu! et aujourdhui suis dans la creation de mon apps, et jaimerai avoir un formulaire dans lequel on pourra saisir par exemple l'username d'un membre et directement on obtient un deuxieme champ qui repete les données entrees. j'ai pu voir ce que notre collegue a fait et j'avoue que je comprend pas tres bien -
'BasicAuthentication' object has no attribute 'has_permission' Django
Good day. how do i solve this problem? 'BasicAuthentication' object has no attribute 'has_permission' views.py from rest_framework import routers, viewsets class EducationLevelViewSet(viewsets.ModelViewSet): model = EducationLevel field = ('Sequence', 'Description', 'Status') serializers.py class EducationLevelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = EducationLevel field = ('Sequence', 'Description', 'Status') urls.py router = routers.DefaultRouter() router.register(r'EducationLevel', views.EducationLevelViewSet, basename='MyModel') from Homepage.views import ArticleListView urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] error -
Multiple domains with Nginx, Varnish and Django all returns the same cached page
I am trying to configure a second domain for an existing project which was previously just using one. But Varnish always returns the cached page from the first domain. So when I visit the second domain I see the content of the first domain. I tried: Changed NGINX: proxy_set_header Host existingdomain.com; to proxy_set_header Host $host; Changed NGINX: 2 server configurations listing to port 8000 for both domains Changed VARNISH: 2 backend configurations for both domains Note: 99% of the configuration was already there I changed the domain names and removed some SLL configurations for this post to be more clear. Both domains use the same html page but slightly difference content. I am noob regarding nginx and varnish. What do I want: Eventually I want 2 different domains and several subdomains who all need its own varnish cache. NGINX server_tokens off; resolver 127.0.0.53 ipv6=off; upstream django_app_server { server unix:/home/test/run/gunicorn.sock fail_timeout=0; } #http redirect too https. server { listen 80 default_server; server_name _; return 301 https://$host$request_uri; } server { server_name existingdomain.com newdomain.com; listen 443 ssl default deferred; # match with actual application server client_max_body_size 10M; keepalive_timeout 60s; # proxy the request through varnish before sending it to gunicorn. location / { … -
Django Backward lookup from other apps
i have models in galery apps class Galery(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='galery') tour = models.ForeignKey('tour.Tour', on_delete=models.CASCADE, blank=True, null=True) # users_customuser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) users_customuser = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) judul = models.CharField(max_length=127, blank=True, null=True) fotografer = models.ForeignKey(Fotografer, on_delete=models.CASCADE) tanggal = models.DateField(blank=True, null=True) deskripsi = models.TextField(blank=True, null=True) foto_file = models.ImageField(upload_to='images/', null=True) and other models in tour app class TourManager(models.Manager): def home(self): last3 = super().get_queryset().order_by('-id').prefetch_related('plan', 'buget','galery.galery') tournew = last3 return tournew class Tour(models.Model): # users_customuser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) users_customuser = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) nama_tour = models.CharField(max_length=127, blank=True, null=True) deskripsi_tour = models.TextField(blank=True, null=True) tanggal_mulai = models.DateField(blank=True, null=True) hari = models.SmallIntegerField(blank=True, null=True) malam = models.SmallIntegerField(blank=True, null=True) TourList = TourManager() how i load Galery from Tour i have this error AttributeError at /tour/ Cannot find 'galery.galery' on Tour object, 'galery.galery' is an invalid parameter to prefetch_related() Request Method: GET Request URL: http://127.0.0.1:8000/tour/ Django Version: 3.0.7 Exception Type: AttributeError Exception Value: Cannot find 'galery.galery' on Tour object, 'galery.galery' is an invalid parameter to prefetch_related() Exception Location: D:_Project\TourGaleryProject.venv\lib\site-packages\django\db\models\query.py in prefetch_related_objects, line 1638 Python Executable: D:_Project\TourGaleryProject.venv\Scripts\python.exe Python Version: 3.8.3 -
Can we use multiple OneToOneFields in single User Model? Any performance issue happen?
I'm new to django, I'm working on a project. I have define User model with multiple parts. User --> default property like username, email, password, date_joined, is_staff, is_superadmin... UserProfile --> OneToOneField(User), first_name, last_name, gender, avatar, dob. UserPhoneAuth --> OneToOneField(User), otp_code, etc.. UserEmailAuth --> OneToOneField(User), secret_key, etc... UserCard --> OneToOneField(User), card_name, card_no, etc.. UserWallet --> OneToOneField(User), chips, tokens. Is this best practice to split multiple models?. Any one can please help me on this. Advanced Thanks. -
How to store the data files of a django project
I am developing a feature in which the user can download some specific files. I am using Django Rest Framework and I want to create some endpoints for downloading those files, and being able to modify them from the script. I don't want to store the files inside the repository as they are a bit heavy and contain a lot of rows (millions). Is there any way I can store the files outside my project and still being able to access/modify them from the script of my project? -
Getting current user in blocks class in Wagtail
Using Wagtail 2.9, I am trying to create a block that has a function that generates URL. To generate the URL I need the current logged in user. class Look(blocks.StructBlock): title = blocks.CharBlock(required=True, help_text='Add your look title') id = blocks.CharBlock(required=True, help_text='Enter the Id') class Meta: template = "looker/looker_block.html" value_class = LookStructValue the value class has the get_url() definition which looks like: class LookStructValue(blocks.StructValue): def url(self): id = self.get('id') user = User(15, first_name='This is where is need the current user First name', last_name='and last name', permissions=['some_permission'], models=['some_model'], group_ids=[2], external_group_id='awesome_engineers', user_attributes={"test": "test", "test_count": "1"}, access_filters={}) url_path = "/embed/looks/" + id url = URL(user,url_path, force_logout_login=True) return "https://" + url.to_string() Can i get the current user inside the LookStructValue class? -
field id expected a number but got 'ashu'
I keep getting the following error while trying to print the level: field id expected a number but got 'ashu' And here's my code: class User(models.Model): user_name=models.CharField(max_length=20) class Sport(models.Model): sport=models.CharField(max_length=20) class Intrest(models.Model): sport_name=models.ForeignKey(Sport,on_delete=models.CASCADE) user=models.ForeignKey(User,on_delete=models.CASCADE) LEVEL=(('1','Beginner'), ('2','Mediate'), ('3','Advance'), ) level=models.CharField(max_length=20,choices=LEVEL) # code sample A=Intrest.objects.get(user=uder.Host.user_name) print(a.level) -
"PermissionError: [Errno 13] Permission denied: '/dev/core' "
Get this error when building django container - PermissionError: [Errno 13] Permission denied: '/dev/core' I have seen similar questions here, but couldn't find the solution. Thanks in advance for help. This is traceback Traceback (most recent call last): django_1 | File "/app/manage.py", line 31, in <module> django_1 | execute_from_command_line(sys.argv) django_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line django_1 | utility.execute() django_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute django_1 | self.fetch_command(subcommand).run_from_argv(self.argv) django_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv django_1 | self.execute(*args, **cmd_options) django_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute django_1 | output = self.handle(*args, **options) django_1 | File "/usr/local/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle django_1 | collected = self.collect() django_1 | File "/usr/local/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 113, in collect django_1 | handler(path, prefixed_path, storage) django_1 | File "/usr/local/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 347, in copy_file django_1 | with source_storage.open(path) as source_file: django_1 | File "/usr/local/lib/python3.8/site-packages/django/core/files/storage.py", line 36, in open django_1 | return self._open(name, mode) django_1 | File "/usr/local/lib/python3.8/site-packages/django/core/files/storage.py", line 231, in _open django_1 | return File(open(self.path(name), mode)) django_1 | PermissionError: [Errno 13] Permission denied: '/dev/core' This is my Dockerfile FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED 1 RUN apt-get update \ && apt-get install -y build-essential \ && apt-get install -y libpq-dev \ && apt-get install -y … -
django print value of query set
simple problem (i think). I have following query: hostname = Host.objects.get(pk=(host_id)) env = Host.objects.filter(cfthostname=hostname).values('cftos') print(env) what i get from print is: <QuerySet [{'cftos': 'unix'}]> how to make it: unix -
Where to initialize a GraphQL Client inside Django App
I'm building an API with Django, I want to query the Github GraphQL API, and I found this GraphQL client for python that suits my needs. But now, I'm wondering, where is the proper place to initialize such a client inside my Django App? inside the request? in the apps.py? in views.py? any guidelines will be appreciated! here is my current Django Project folder structure: . ├── LICENSE ├── README.md ├── api │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py ├── portfolio │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── requirements.txt └── setup.py Thanks in advance!