Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload file to database with file link
I am working on a project whereby the user has to upload a document. I have successfully been able to upload a file to the database and serve the user the uploaded file. I however want to upload files to the database using the file link rather than just selecting file from your device. models.py class Books(models.Model): title = models.CharField(max_length=500, default="") author = models.CharField(max_length=500, default="") publication = models.CharField(max_length=500, default="") edition = models.IntegerField(default="") is_available = models.BooleanField() book = models.FileField( default="", upload_to="books", validators=[validate_book_extension], verbose_name="books", ) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default="") class Meta: verbose_name_plural = "Books" def __str__(self): return self.title views.py def books(request): genres_names = Genre.objects.all() if request.method == "POST": form = BookFile(request.POST, request.FILES) files = request.FILES.getlist("book") genres_name = request.POST.get("genres") try: if form.is_valid(): new_old_genre, created = Genre.objects.get_or_create( genres=genres_name.lower() ) genre = Genre.objects.filter(genres=genres_name) if files: for f in files: names = str(f) name = names.strip(".pdf") Books.objects.create( genre=new_old_genre, book_title=name, book=f ) return redirect(index) except IntegrityError: messages.error(request, "value exist in database") return redirect(books) else: form = BookFile() return render(request, "books.html", {"form": form, "genres_names": genres_names}) forms.py class BookInfo(forms.ModelForm): class Meta: model = Genre fields = [ "genres", ] widgets = {"genres": forms.TextInput(attrs={"list": "genres"})} class BookFile(BookInfo): book = forms.FileField(widget=forms.ClearableFileInput(attrs={"multiple": True})) class Meta(BookInfo.Meta): fields = BookInfo.Meta.fields + [ "book", … -
cannot import name 'FieldDoesNotExist'
I am trying to run command: python3 manage.py runserver 0:80 and I get the below error Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib64/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 423, in check databases=databases, File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 416, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.6/site-packages/django/utils/functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 602, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.6/site-packages/django/utils/functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 595, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib64/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/home/rc/qrd/qos-dashboard/config/urls.py", line 4, in from rest_framework_swagger.views import get_swagger_view File "/usr/local/lib/python3.6/site-packages/rest_framework_swagger/views.py", line 3, in from … -
Setup logging of Celery in Django correctly - how?
Setting up celery on our production server seems to be more complicated than it should be - and the problem is logging. Our setup is like this: Server is Ubuntu 20.04.5 LTS We run Django 3.2.8 in it's own user and group named "django" The Celery process also has it's own user and group named "celery". Celery is set up as a service and logs to /var/log/celery In celery.py we have set djangoConf pointing to the main settings.py On startup Celery tries to touch a django-logfile and - missing the permissions to do so - returns an error: Dec 16 10:57:27 h2989788 celery[128418]: Usage: celery [OPTIONS] COMMAND [ARGS]... Dec 16 10:57:27 h2989788 celery[128418]: Try 'celery --help' for help. Dec 16 10:57:27 h2989788 celery[128418]: Error: Invalid value for '-A' / '--app': Dec 16 10:57:27 h2989788 celery[128418]: Unable to load celery application. Dec 16 10:57:27 h2989788 celery[128418]: While trying to load the module theApp the following error occurred: Dec 16 10:57:27 h2989788 celery[128418]: Traceback (most recent call last): Dec 16 10:57:27 h2989788 celery[128418]: File "/usr/lib/python3.8/logging/config.py", line 563, in configure Dec 16 10:57:27 h2989788 celery[128418]: handler = self.configure_handler(handlers[name]) Dec 16 10:57:27 h2989788 celery[128418]: File "/usr/lib/python3.8/logging/config.py", line 744, in configure_handler Dec 16 10:57:27 h2989788 … -
Unable to install libapache2-mod-wsgi-py3
I am having some issues with wsgi and getting my django api up and running using apache. I think the issue is the mod_wsgi.so. I have already installed libapache2-mod-wsgi, but my venv is configured using python 3.6. Based on my research I think I need libapache2-mod-wsgi-py3. Trying to install with sudo yum install libapache2-mod-wsgi-py3 returns Loaded plugins: extras_suggestions, langpacks, priorities, update-motd amzn2-core | 3.7 kB 00:00:00 No package libapache2-mod-wsgi-py3 available. Error: Nothing to do Error log shows: Traceback (most recent call last): [Tue Dec 20 19:02:24.660246 2022] [:error] [pid 13266] File ".../project/project/wsgi.py", line 13, in <module> [Tue Dec 20 19:02:24.660275 2022] [:error] [pid 13266] from django.core.wsgi import get_wsgi_application [Tue Dec 20 19:02:24.660283 2022] [:error] [pid 13266] File ".../lib/python3.6/site-packages/django/__init__.py", line 1, in <module> [Tue Dec 20 19:02:24.660295 2022] [:error] [pid 13266] from django.utils.version import get_version [Tue Dec 20 19:02:24.660302 2022] [:error] [pid 13266] File ".../lib/python3.6/site-packages/django/utils/version.py", line 7, in <module> [Tue Dec 20 19:02:24.660313 2022] [:error] [pid 13266] from django.utils.regex_helper import _lazy_re_compile [Tue Dec 20 19:02:24.660319 2022] [:error] [pid 13266] File ".../lib/python3.6/site-packages/django/utils/regex_helper.py", line 10, in <module> [Tue Dec 20 19:02:24.660330 2022] [:error] [pid 13266] from django.utils.functional import SimpleLazyObject [Tue Dec 20 19:02:24.660336 2022] [:error] [pid 13266] File ".../lib/python3.6/site-packages/django/utils/functional.py", line 362, in <module> … -
Seeing a 500 internal server error with mod_wsgi, apache and django but nothing in the log file. Gunicorn runs without issue
We released some new code that depends on django-tree-queries and are now seeing an internal server error with mod_wsgi. There is nothing in the apache logs and nothing in the django logs. Normally when we have django erors we do see a stack trace in the logs and get an email. Here is our apache config: <VirtualHost IP_ADDR:443> ServerName our.url ErrorLog ${APACHE_LOG_DIR}/dev-ssl-error.log CustomLog ${APACHE_LOG_DIR}/dev-ssl-access.log combined LogLevel debug Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" SSLEngine on <Directory /var/www/django/app/config> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess apps-dev processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup apps-dev WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/www/django/app/config/wsgi.py RewriteEngine On RewriteCond %{REQUEST_METHOD} ^(OPTIONS|TRACE) RewriteRule .* - [F] </VirtualHost> Here is our wsgi.py file: activate_file = "/var/www/django/app/venv/bin/activate_this.py" exec(open(activate_file).read(), {"__file__": activate_file}) import os # noqa: E402 import sys # noqa: E402 from pathlib import Path # noqa: E402 from django.core.wsgi import get_wsgi_application # noqa: E402 ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent # This allows easy placement of apps within the interior # our_app directory. sys.path.append(str(ROOT_DIR / "our_app")) sys.path.append(str(ROOT_DIR)) # Explicitly set the settings module for this wsgi app os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.apps_dev" # Enable dot env file reading by default for this environment os.environ["DJANGO_READ_DOT_ENV_FILE"] = "True" # This application object is used by any WSGI server configured to … -
My django form is never valid. Why is this happening?
I have django application where I want user to be able to upload videos. My view looks like this: class CreateVideo(View): def post(self, request): videos = models.Video.objects.all().order_by('-created_on') form = forms.VideoUploadForm(request.POST) if form.is_valid(): print('form is valid') video = form.save(commit=False) video.save() print('video uploaded') else: print('form not valid') context = { 'video_list': videos, 'form': form, } return redirect('index') def get(self, request): videos = models.Video.objects.all().order_by('-created_on') form = forms.VideoUploadForm() context = { 'video_list': videos, 'form': form, } return render(request, 'videos/upload_video.html', context) My form: class VideoUploadForm(forms.ModelForm): class Meta: model = Video fields = ['title', 'description', 'file'] and model: class Video(models.Model): video_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True ) title = models.CharField(max_length=50, null=True) description = models.CharField(max_length=500, null=True) file = models.FileField(null=True) created_on = models.DateTimeField(default=timezone.now, null=True) at = models.ForeignKey(at, on_delete=models.CASCADE, null=True) and my template: <div> <form method="post"> {% csrf_token %} {{ form | crispy }} <button>Submit!</button> </form> </div> When I click submit button, I get: form not valid in terminal. I want form to be created, but form is just never valid. Where is the problem? -
How can I add a dyno for my deployed app in Heroku?
I deployed the app for Heroku successfully but when I check status with 'heroku ps' command I receive information that I have no dynos on the app. The app is created in Django. I tried to add a dyno for my app by browser on my account but there is not any option to do that. Is there a possibility that Procfile causes that issue? My Procfile (file without extension) command: web: gunicorn mywebsite.wsgi --log-file - I tried a lot of solutions from the internet and stackoverflow but my problem is still not solved. I would be grateful for any help. -
I don't know where to look
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I don't know where to look -
Django Sub Filter Brings Same Datas with Main Filter
I am making very simple business directory. I wanna display a list of firms that belong to a particular city and district, and belong to a certain category. But district filter and city filter brings same datas. How can i fix this? I filtered to district but again brings main city datas. Where is my fault? models.py class City(models.Model): city = models.CharField(max_length=50) slug = models.SlugField() def __str__(self): return str(self.city) class District(models.Model): district = models.CharField(max_length=50) slug = models.SlugField() city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return str(self.district) class FirmaCategory(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() class Meta: verbose_name_plural = 'Firma Kategorileri' def __str__(self): return str(self.title) class Firma(models.Model): category = models.ForeignKey(FirmaCategory, related_name="Firma", on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() adres = tinymce_models.HTMLField() tel = tinymce_models.HTMLField() website = tinymce_models.HTMLField() email = tinymce_models.HTMLField() intro = tinymce_models.HTMLField() body = tinymce_models.HTMLField() city = models.ForeignKey(City,related_name="FirmaCategory" ,on_delete=models.CASCADE) district = models.ForeignKey(District,related_name="FirmaCategory", on_delete=models.CASCADE) #url = models.CharField(max_length=255) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Firmalar' def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('firma-frontpage') views.py def firmaana(request): firmalar = Firma.objects.all() context = { 'firmalar': firmalar } return render(request, 'firma/firma-frontpage.html', context) def firmadetail(request, slug): firmax = Firma.objects.get(slug=slug) context = { 'firmax': firmax, } return render(request, 'firma/firma-detail.html', context) def firmacategory(request, slug): firmacategory = FirmaCategory.objects.get(slug=slug) context … -
Can't download working dxf file generated by ezdxf from django server
Generated dxf file (ezdxf) from django server using below code: bio = io.StringIO() document.write(bio) # save to memory stream length = bio.tell() bio.seek(0) # rewind the stream response = HttpResponse( bio.getvalue(), # use the stream's contents content_type="image/x-dxf", ) response["Content-Disposition"] = 'attachment; filename = {0}'.format(cab.split(' ')[1] + ".dxf") response["Content-Encoding"] = "UTF-8" response['Content-Length'] = length return response is missing the last few lines, including the EOF line. Compared to a dxf file obtained simply by document.save() What needs to be added to the code so that the downloaded dxf file is identical to the saved dxf file? -
WebSocket django channels doesn't work with postman
Django Channels Throw error with postman while working well with Html. I'm following Django Socket Tutorial "here's the error showing in Django". WebSocket HANDSHAKING /ws/chat/roomName/ [127.0.0.1:56504] WebSocket REJECT /ws/chat/roomName/ [127.0.0.1:56504] WebSocket DISCONNECT /ws/chat/roomName/ [127.0.0.1:56504] "Error showing in postman when connecting to ws://127.0.0.1:8000/ws/chat/roomName/" Sec-WebSocket-Version: 13 Sec-WebSocket-Key: fSSuMD2QozIrgywqTX38/A== Connection: Upgrade Upgrade: websocket Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits Host: 127.0.0.1:8000 My Code asgi.py django_asgi_app = get_asgi_application() import digital_signage.playlist_management.routing application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(digital_signage.playlist_management.routing.websocket_urlpatterns)) ), } ) consumer.py class ChatConsumer(WebsocketConsumer): def connect(self): print("self", self) self.accept() -
Switching from LDAP to AD LDAPS using Python Django
Converting authentication from LDAP to AD LDAPS Python + Django ============== Following Django Docs: https://django-auth-ldap.readthedocs.io/en/latest/authentication.html OLD: AUTH_LDAP_SERVER_URI = "ldap://ldap-example.test.com" NEW: AUTH_LDAP_SERVER_URI = "ldaps://ad.example.com" ============== I have worked with the AD administrator to set these values correctly. I changed the values themselves for obvious privacy reasons. AUTH_LDAP_BIND_DN = "cn=ex-test,cn=user,dc=test,dc=ad" AUTH_LDAP_BIND_PASSWORD = "{PASSWORD}" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=sites,dc=test,dc=ad",ldap.SCOPE_SUBTREE,"(uid=%(user)s)") AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS: 0} AUTH_LDAP_USER_DN_TEMPLATE = "cn=%(user)s,ou=sites,dc=test,dc=ad" AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_GROUP_SEARCH = LDAPSearch("cn=priv-ex,ou=due,ou=ldap,ou=shared,dc=test,dc=ad", ldap.SCOPE_SUBTREE) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn') AUTH_LDAP_USER_ATTR_MAP = { "first_name": "usersName", "last_name": "usersLastName", "email": "usersEmail" } AUTH_LDAP_REQUIRE_GROUP = "cn=DUE-MAIN,ou=DUE,ou=Applications,ou=Sharing,o=LDAP" ============== Problem It will not work for login. I do not know what I am doing wrong as I am following the docs precisely. Questions Q1: Is there anyway I can test the connection from a terminal or command line? Q2: I have seen the django-pyad package recommened with a settings.py that looks like # settings.py AUTHENTICATION_BACKENDS = [ 'django_pyad.backend.ADBackend', ] # AD configuration AD_LDAP_SERVER = "ad.example.com" AD_NT4_DOMAIN = "example" AD_SEARCH_DN = "OU=Users,DC=ad,DC=example,DC=com" Should I scrap what I did for the previous LDAP tree and go this route instead? Or can I re-use the previous LDAP connection code but change the values for AD like I am doing now? -
How to store data typed by user into input using Django
Im kinda new to django and i got stuck I want to get user input, and after that i want to display value which depend on it For example in djanog i have if statment which checking input from user, for exaple car model. So, when user type Ibiza i want to display "Seat", user type E92 i want to dispaly "BMW" etc I want to display car brands in list which can be cleard or dissapear after user close tab and re-open. Which solution is the best? Database in django? Cookies? Local storage in javascript? -
Mod_wsgi server will not start up
I am moving a currently working Django project to a new Red Hat server and upon moving the project, it's virtual env, and installing pip packages I started up the server how I always have and it worked fine. Going back to it a week later I enter in the web address of the django site and it times out. The mod_wsgi error log reads. [Tue Dec 20 17:55:49.282343 2022] [core:warn] [pid 831143:tid 139775964862784] AH00098: pid file /tmp/mod_wsgi-localhost:8080:21056/httpd.pid overwritten -- Unclean shutdown of previous Apache run? [Tue Dec 20 17:55:49.283800 2022] [mpm_event:notice] [pid 831143:tid 139775964862784] AH00489: Apache/2.4.37 (Red Hat Enterprise Linux) mod_wsgi/4.9.4 Python/3.6 configured -- resuming normal operations [Tue Dec 20 17:55:49.283823 2022] [core:notice] [pid 831143:tid 139775964862784] AH00094: Command line: 'httpd (mod_wsgi-express) -f /tmp/mod_wsgi-localhost:8080:21056/httpd.conf -D MOD_WSGI_KEEP_ALIVE -D MOD_WSGI_MPM_ENABLE_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_WORKER_MODULE -D MOD_WSGI_MPM_EXISTS_PREFORK_MODULE -D FOREGROUND' I can't figure out what this error indicates is happening. httpd.pid overwritten -- Unclean shutdown of previous Apache run? I've even restarted the apache server that runs on this server and it has done nothing. -
Getting data from another Foreign key - DRF
The relations of tables are shown in the picture. I have a main Table named Product. Two tables ProductImage , OrderedProduct have a Foreign key set to it. Now, I want to retrieve the image from OrderedProduct. How should I write the code for Serialization for it? Thanks Models.py Visualization This is my model.py file: class Product(models.Model): name = models.CharField(max_length=50) description = models.TextField() def __str__(self) -> str: return self.name class ProductImage(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='product_images') image = models.ImageField(upload_to="images/", null=True, blank=True) class OrderedProduct(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='ordered_products') quantity = models.IntegerField() Serializers.py class OrderedProductSerializer(serializers.ModelSerializer): product_name = serializers.CharField(source='product.name') product_price = serializers.FloatField(source='product.price') # product_img = >>> what should I do here? <<< class Meta: model = OrderedProduct fields = ('user', 'product', 'quantity', 'delivered', 'product_name', 'product_price', 'product_img') I've read the documentation, asked in some programming groups but couldn't find any good solution. I am expecting someone to give a reference that leads to the solution. -
How to upload an image to django from an html input file
I am developing a web service on django with frontend on react. I ran into a problem that I can't upload an image to django. Below is my component code where I'm trying to download it: export function ProviderRegistration(){ const[logoField, setLogoField] = useState() const token = useSelector((state) => state.user.token) const [cookie, setCookie] = useCookies(['auth']) const confirm = () => { axios.post(`/providers/?username=${cookie.auth.login}`, { photo : logoField }, { "headers" : { "Authorization" : "token " + token }}) .then(res => console.log(res)) .catch(err => console.log(err)) } return( <div className="registration-provider-container"> <div className="registration-title">Provider registration</div> <input type="file" className="registration-logo-add" onChange={(e) => setLogoField(e.target.value)}/> <button className="registration-confirm" onClick={() => confirm()}>Confirm</button> </div> )} And the endpoint processing this request class Providers(viewsets.ModelViewSet): filterset_class = ProvidersFilter queryset = Provider.objects.all() permission_classes = [IsAuthenticatedOrReadOnly, IsProviderPermission, IsOneToOneProviderPermission] def get_serializer_class(self): if self.action == 'list': return GetProviderSerializer else: return PutProviderSerializer def create(self, request): username = request.GET.get('username', '') user = User.objects.get(username=username).pk request.data.update({'user' : user}) print(request.data) return super().create(request) When I try to upload an image, django returns the following error: "The submitted data was not a file. Check the encoding type on the form." And I haven't found a way to correctly upload an image to django using Ajax. I also output what my browser sends to the server: … -
Using Model.objects.filter in Form prevents me from updating Model
I have a form setup like this where I use the values from TestModel to create a select field in a form. However if I want to update the TestModel to add a new column, Django gives me a psycopg2.errors.UndefinedColumn saying the new column is not found on the table and the stack trace points back to this form ModelChoiceField. Its not until I comment out this select that I am able to make the migration to the database. So my question is there a better way to setup this ModelChoiceField where I don't have to comment it out to update the underlying model on the database? I'm using Django 4.0 and python 3.8 for reference. class TestModelChoiceField(forms.ModelChoiceField): """ Overwriting model choice field attribute to use a different __str__ representation than the default model """ def label_from_instance(self, obj): return obj.test_field class TestForm(forms.Form): first_select = TestModelChoiceField( queryset=TestModel.objects.filter(model_attribute__isnull=False), initial=TestModel.objects.filter(model_attribute__isnull=False) .filter(test_field="Yes") .first() .team_id, label="Field One:", ) -
Creating a simple multiple users app in Django
So I've created 3 different users: admins, developers, and project managers. When I use the individual signup forms for each of these users and log out, it works, but then I when try to use the login form, it seems to me that it's acting like the signup form. Because when I input the same user details as the one I just created into the login form, it throws up the built-in error message, 'A user with that user name already exists' I'm not sure how to proceed from here. Here's what I have so far. models.py class CustomUser(AbstractUser): ACCOUNT_TYPE_CHOICES = ( ('admin', 'Admin'), ('developer', 'Developer'), ('project_manager', 'Project Manager') ) account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPE_CHOICES) login and signupviews class LoginView(View): def get(self, request): # Render the login form form = LoginForm() return render(request, 'users/login.html', {'form': form}) def post(self, request): # Get the form data from the request form = LoginForm(request.POST) # Validate the form data if form.is_valid(): # Get the username and password from the form username = form.cleaned_data['username'] password = form.cleaned_data['password'] # Authenticate the user user = authenticate(request, username=username, password=password) # If the user is authenticated, log them in and redirect to the homepage if user is not None: login(request, … -
How to show print diagloue box in browser in Django?
I am trying to get the print dialogue box in my Django app. Currently its downloading in my local computer. But when I am serving in apache server, its not working. my views.py def download(request,lothash): lot=lotnumber.objects.get(lot_hash=lothash) postdata = request.POST array = postdata.get("array", None).split(",") template=lot.template_type f = open(f"/home/username/public_html/nitin2/media/{template.template_file}", "r") txt=(f.read()) df=pd.read_excel("/home/username/public_html/nitin2/media/"+str(lot.file)) df = df.reset_index() n=1 k=0 for index, row in df.iterrows(): if n>len(array)+1: break if str(n) in array: txt = txt.replace("(As Provided by Bank)", str(row['RGN_A'])) txt = txt.replace("(Customer Name)", str(row['Applicant Name'])) txt = txt.replace("(Customer Address)", str(str(row['Address1']) + " " + str(row['Address2']) + " " + str(row['Address3']))) txt = txt.replace("(Product)", str(row['Product'])) txt = txt.replace("(LAN)", str(row['LAN'])) txt = txt.replace("(Notice Amount)", str(row['Notice Amount'])) # save FPDF() class into a # variable pdf pdf = FPDF() # Add a page pdf.add_page() # set style and size of font # that you want in the pdf pdf.set_font("Arial", size = 12) # insert the texts in pdf newtxt=splitlinesoftext(txt) for x in newtxt: pdf.multi_cell(0, 5, txt = x, align = 'L',border=0) downloads_path = str(Path('/home/username/public_html/nitin2/media/') / "Downloads/nitin").replace('\\','/') if not os.path.isdir(f"{downloads_path}/{str(row['Applicant Name'])}"): os.makedirs(f"{downloads_path}/{str(row['Applicant Name'])}") pdf.output(f"{downloads_path}/{str(row['Applicant Name'])}/document.pdf", 'I') #pdf.output(f'document.pdf', 'D') template=lot.template_type f = open(f"/home/username/public_html/nitin2/media/{template.template_file}", "r") txt=(f.read()) k=k+1 n=n+1 return JsonResponse({'context': "done"}) I want now to show download dialogue box. Currently if … -
Need help about redirecting views in Django
I a beginner in learning Django and have met with an issue that need everyone help. I'm working on a web application for reading novels. I met with an issue that is related to views redirecting in Django. It's about how I can open the chapter page that I clicked on and read it perfectly normal but when I want to return to the novel index page by clicking on the link, I'm met with a NoReverseMatch error. I'll post my code below: This is what I configured in the urls.py: Then I created and configured the urls.py like this: And this is my views.py: The part that I've met with issue is an Html page for viewing chapter: What I have in mind is that by clicking on the url, I'll be redirected to the novel index page. But what happened is that I'm met with the NoReveseMatch error because the part that should have the slug that point to the index page is blank so I can't redirect to it. Anyone have an idea of what I did wrong ? Any helps or suggestions are appreciated -
How can I filter tags with django-taggit
I'm doing the following to filter the posts by tag. But the problem is when clicking the tag button, I do not see any results. urls.py : urlpatterns =[ ...... path('challengePage/', views.ChallengePage, name ='challengePage'), path('tag/<tag>', views.tag, name='tag_argument'), ] the views.py : def ChallengePage(request): challenges = Challenge_code.objects.prefetch_related('tags').all().order_by('-created_at') tags = Tag.objects.all() context = { 'challenges' : challenges, 'tags':tags, } return render(request,'challengePage.html',context) def tag(request,tag): challenges_tag = Challenge_code.objects.filter(tags__name__in=tag) return render(request, 'tag.html',{'tag':tag, 'challenges':challenges_tag}) the challengePage.html : <div style="text-align: center;"> {% for tag in tags %} <a href="{% url 'tag_argument' tag %}"><button style="text-align: center;" dir="ltr" class="buttonTag buttonTag2" > {{tag.name}}</button></a> {% endfor %} </div> the tag.html : <div class="code_body"> <div class="container_code"> {% for challenge in challenges_tag %} <div class="Box_code"> <p class="title_code"><bdi style=" color: #000;"> {{challenge.title}} <br> {% for tag in challenge.tags.all %} <small>{{tag}}, </small> {% endfor %} </bdi> </p> <a href="{% url 'challenge' challenge.id %}"><button class="button1" style="vertical-align:middle"><span>Join</span></button></a> <p class="name-user"> <bdi> By: {{challenge.auther.username}} </bdi> </p> </div> {% endfor %} -
Django Handling Multiple Image Uploads
I have a simple project that has two different models. One that handles a report and one that stores the images for each report connected by a ForeignKey: class Report(models.Model): report_location = models.ForeignKey(Locations, on_delete=models.CASCADE) timesheet = models.ImageField(upload_to='report_images', default='default.png') text = models.CharField(max_length=999) report_date = models.DateField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.report_location, self.report_date, self.created_by}" class TimeSheetAndPics(models.Model): report = models.ForeignKey(Report, on_delete=models.CASCADE) report_images = models.ImageField(upload_to='report_images', default='default.png') date = models.DateField(auto_now=True) def __str__(self): return f"{self.report} on {self.date}" My Goal is to have a user fill out the report and then upload multiple pictures, however i cannot figure out how to handle multiple image uploads. I have two forms for each model: class ReportCreationForm(ModelForm): class Meta: model = Report fields = [ 'report_location', 'text', ] class TimeSheetAndPicForm(ModelForm): report_images = forms.FileField(widget=ClearableFileInput(attrs={'multiple': True})) time_sheets = forms.FileField(widget=ClearableFileInput(attrs={'multiple': True})) class Meta: model = TimeSheetAndPics fields = [ 'time_sheets', 'report_images', ] And this is how i try to handle my views: class NewReport(LoginRequiredMixin, View): def get(self, request): context = { 'create_form': ReportCreationForm(), 'image_form': TimeSheetAndPicForm(), } return render(request, 'rakan/report_form.html', context) def post(self, request): post = request.POST data = request.FILES or None create_form = ReportCreationForm(post) image_form = TimeSheetAndPicForm(post, data) if create_form.is_valid() and image_form.is_valid(): clean_form = create_form.save(commit=False) clean_form.created_by = request.user clean_form.save() clean_image_form = … -
Django pass value to subquery inside annotate in a query set with mptt
i have a class based on ListCreateAPIView where i'm modifing get_queryset method.. i need pass inside a subquery for an annotate a paramether but seem OutherRef dosen't work i'm using Mptt library .... subqueryItem works fine, subqueryNested instead says cannot use OuterRef can be used only inside a subquery def get_queryset(self): queryset = super().get_queryset() subqueryItem = Subquery(Item.objects.filter(category=OuterRef('id')).order_by() .values('category').annotate(count=Count('pk')) .values('count'), output_field=IntegerField()) subqueryNested = Subquery(Item.objects.filter(category__in=ItemCategory.objects.get(pk=OuterRef('id')).get_descendants(include_self=True)).order_by() .values('category').annotate(count=Count('pk')) .values('count'), output_field=IntegerField()) queryset = queryset.annotate( collcount = Coalesce(subqueryItem, 0), collcountdeep = Coalesce(subqueryNested, 0), ) -
ModuleNotFoundError: No module named "tip_administration_app"
I'm trying to set up a complete environment to run a Django application on ubuntu 22.04 with gunicorn and nginx. I use a droplet provided by Digital Ocean and i'm trying to follow this tutorial : https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 Everything is going well until I have to link gunicorn to my wsgi.py file. When i'm trying this command : gunicorn --bind 0.0.0.0:8000 tip_administration_app.wsgi I have this error : [2022-12-20 14:08:25 +0000] [20676] [INFO] Starting gunicorn 20.1.0 [2022-12-20 14:08:25 +0000] [20676] [INFO] Listening at: http://0.0.0.0:8000 (20676) [2022-12-20 14:08:25 +0000] [20676] [INFO] Using worker: sync [2022-12-20 14:08:25 +0000] [20677] [INFO] Booting worker with pid: 20677 [2022-12-20 14:08:25 +0000] [20677] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/home/django/the-ideal-partner/myprojectenv/lib/python3.10/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line … -
How to show GenericRelation object field value in list_display?
models.py class ModelA(models.Model): name = models.CharField(max_length=40) class ModelB(models.Model): name = models.CharField(max_length=100) model_c = GenericRelation("modelc") class ModelC(models.Model): model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, limit_choices_to={"model__in":["modelb", "modelx", "modely"]}, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() details = GenericForeignKey("content_type","object_id") admin.py class AdminModelB(admin.ModelAdmin): list_display = ("name", "model_a") @staticmethod def model_a(obj): return obj.model_c.model_a # 'GenericRelatedObjectManager' object has no attribute 'model_a' I have ModelB having GenericRelation in field model_c where ModelC contain ContentType as ForeignKey. Now I want to display ModelA.name in list_display of ModelB. I have tried like other foreignkey fields but it gives me an error 'GenericRelatedObjectManager' object has no attribute 'model_a'.