Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load serialized data in django?
I have created a view to serialize model instance in django: Like this: def getcompanyObject(request, pk): company_details = get_object_or_404(Company, pk=pk) all_objects = list(Group1.objects.filter(user=request.user,company=company_details.pk)) + list(Ledger1.objects.filter(user=request.user,company=company_details.pk)) data = serializers.serialize('json', all_objects) data = json.dumps(json.loads(data), indent=4) response = HttpResponse(data , content_type='application/json') response['Content-Disposition'] = 'attachment; filename=export.json' return response It will serialize the model instance of Group1 and Ledger1 and the user can download the serialized file in .dat format(I am doing this on purpose). I want a functionality just like python manage.py loaddata in my project that user can load the serialized file by clicking on a button or something. Any idea anyone how to perform this? Thank you -
Django 2.7.1 - "TemplateDoesNotExist at /munichlivingapp/seekers/
Django 2.7.1 - "TemplateDoesNotExist at /munichlivingapp/seekers/" (The identical issue: Templates Django (Does not exist at/) ) 1) the browser error message: [https://ibb.co/ryLhjRp] 2) my project files structure: [https://ibb.co/GQc1TFZ] 3) the relevant part of my settings.py file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', "django.core.context_processors.media", ], }, }, ] -
Read model h5 from web application
How to read Keras model from the web application (Django framework)? Python code for model reading is: pd.HDFStore('./pathtofile", mode = 'r') From Django application I need to send pathtofile variable according to file choosen by user. Django code cannot deliver path: def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'core/simple_upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'core/simple_upload.html') Any suggestion of best practice to make my keras model more approchable through the web browser? -
Django PostgreSQL ForeignKey-Relation always throws error
I switched from sqlite to PostgreSQL (in a django project). Everything worked in sqlite but in PostgreSQL are some errors. I tried to fix them and now I'm stuck in this error. I have an article model and an image model (with a foreignkey relation to article). class Image(models.Model): Article = models.ForeignKey(Article, on_delete=models.CASCADE, verbose_name="Artikel") When I try to migrate my database I get this error: Key columns "image_id" and "id" are of incompatible types: character varying and integer. I didn't delete my migrations. -
Send Email through Outlook Shared Mailbox in Django
Currently I have been using my licensed outlook email address to send emails in django using the below settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = smtp.outlook.office365.com EMAIL_PORT = 587 EMAIL_HOST_USER = 'xyz@company.com' EMAIL_HOST_PASSWORD = 'Password' Recently we have setup a new shared mailbox 'noreply@company.com' to replace it with my email but having issues sending emails as it doesn't accepts the credentials (i.e password) and throws an SMTPAuthenticationError exception. Is it possible to send emails using the shared mailbox over smtp server ? If yes, how can I achieve this in Django ? -
How can I have 127.0.0.1:8080/photo/static/subImages/blah.jpg instead of 127.0.0.1:8080/works/29/photo/static/subImages/blah.jpg?
I faced with http://127.0.0.1:8080/works/29/photo/static/subImages/blah.jpg innstead of http://127.0.0.1:8080/photo/static/subImages/blah.jpg in inspect element. and the images do not load. models.py class SubImage(models.Model): image = models.ForeignKey('Image', on_delete=models.SET_NULL, null=True) file = models.ImageField(upload_to='photo/static/subImages/',max_length=1000, null=True) class Image(models.Model): title = models.CharField(max_length = 100) file = models.ImageField(upload_to='photo/static/images/',max_length=1000, null=True) works.html <img src="{{subImage.file}}"> urls.py url(r'^works/(?P<param1>\d+)/$', views.specsView, name='specsView'), views.py def specsView(request, param1): subImage_list = models.SubImage.objects.filter(image_id__exact = '29') return render(request, 'photo/works.html', {'subImage_list':subImage_list}) how can i do in urls or other file to load my images?? thanks -
error occured while installing npm package in ubuntu
I am trying to install npm package in ubuntu 18. But every time it is showing root administrator error. Have a look of error my getting.npm ERR! Linux 4.15.0-46-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "@angular/cli" npm ERR! node v8.10.0 npm ERR! npm v3.5.2 npm ERR! path /usr/local/lib npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall access npm ERR! Error: EACCES: permission denied, access '/usr/local/lib' npm ERR! { Error: EACCES: permission denied, access '/usr/local/lib' npm ERR! errno: -13, npm ERR! code: 'EACCES', npm ERR! syscall: 'access', npm ERR! path: '/usr/local/lib' } npm ERR! npm ERR! Please try running this command again as root/Administrator. npm ERR! Please include the following file with any support request: npm ERR! /home/ujjwal/npm-debug.log -
How do display error when submitting django form with jquery
am trying to do a password change form, but am submitting the form using jquery, my problem is that when a user submits a form with the wrong password, i cannot get the error message like if the new password and the confirm new password do not match, it will display that both passwords do not match, or if the old password is wrong, it will display that password is not correct, Here is my code profile.html <form action="." enctype="multipart/form-data" method="POST" id="PassChan__form"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Change Your paswsord</legend> <input type="hidden" value="Chan_Pass" name="hidden_data" /> {{ c_form | crispy }} </fieldset> <div class="form-group"> <h6 id="PassChan__show"></h6> <img src="{% static 'images/ajax-loader.gif' %}" style="Display:none;" id="PassChan__img"> <button class="btn btn-outline-info" type="submit" onclick="submit_form('PassChan__form', 'PassChan__submit', 'PassChan__img', 'PassChan__show', 'no')" id="PassChan__submit">Change Password</button> </div> </form> views.py def profile(request): if request.method == 'POST': response_data = { 'SType': 'danger', 'message': "An Error Occured, pls try again later" } c_form = PasswordChangeForm(user=request.user, data=request.POST) if c_form.is_valid(): c_form.save() update_session_auth_hash(request, c_form.user) response_data = { 'SType': 'success', 'message': "Your Password was changed successfully" } return HttpResponse(json.dumps(response_data), content_type="application/json") context={ 'c_form':PasswordChangeForm(user=request.user) } return render(request, 'users/profile.html', context) pls how can i do this -
Bootstrap Mobile Toggle not working in Django
I am using Django and I have bootstrap4 loaded with min.css/js files included in my stylesheet references that are properly linked and yet my mobile toggle menu refuses to toggle when clicked. My browser source shows that it has loaded these files without any errors so I am assuming I am missing a file that is required to use bootstrap toggle menus in Django. {% load static %} <!DOCTYPE html> <head> <meta charset="utf-8"> <title>Flash Stacks</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.js' %}"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous"> </head> <body> <!--NAVIGATION--> <header class="main-head"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">EXAMPLE APP</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#main-nav" aria-controls="main-nav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <!--COLLAPSIBLE CONTENT--> <div class="collapse navbar-collapse" id="main-nav"> <!--LINKS--> <ul class="nav navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href='#'>About</a> </li> <li class="nav-item"> <a class="nav-link" href='#'>Pricing</a> </li> <li class="nav-item"> <a class="nav-link" href='#'>Products</a> </li> </ul> </div> </div> </nav> <div class="page-header container-fluid"> <h1>Flash Card Stacks</h1> </div> </header> <!--BODY CONTENT --> <div class="content container-fluid"> {% block content%} {% endblock %} </div> <!--FOOTER CONTENT--> <div class="footer container-fluid"> <p>This is the footer of the webpage!</p> </div> </body> </html> -
Django - Positive/Negative Integerfield depending on choice
I have a model which consists of cashflows: positive and negative ones. I would like to enforce a positive or negative amount when a user fills in a form. So basically: 1/ first you choose inflow or outflow 2/ next you type in the amount. the sign will depend on your previous choice How can I achieve this? I am aware of PositiveIntegerField which works such as Integerfield but don't see how to integrate this in the model? many thanks !! class CashFlow(models.Model): POSITIVE= 'inflow' NEGATIVE= 'outflow' cashflowchoices = ( (POSITIVE, 'inflow'), (NEGATIVE, 'outflow'), ) type = models.CharField(max_length=20, choices = cashflowchoices, default=CALL) amount = models.DecimalField(max_digits=20, decimal_places=2, default='1') -
Django-Reversion Display specific instance of record
I know I should show code first but I'm stuck about how to attempt this. I'm using django-reversion to create a history of my model data. I would like to present the data of a previous version of the record in specific instances without reverting to the previous version. For example, say I have a house with a Sale Record against it. Subsequently an extension is added to the House. When The Sale Record is selected I want it to show the House as was (without an extension) rather than as is now. Can (How do) I achieve this or is there a better approach? -
How to add imaged to Django blog
I hope this question is not off topic. I've created a Django blog. It currently displays a title, the blog body itself, the creation date and the author name. I now wish to add images. Initially I'd be happy to be able to upload and display one image in my blog post but eventually I may wish to be able to upload several images and have them display in some neat way. I'm thinking I'd like the actual image file to be sotred in and AWS bucket and for my database to reference it. This is all new to me though so if I'm completely wrong, I'd be keen to hear of a better solution. Is there any standard way of doing something like this or any libraries that may help me? -
How to check image width & height in Django admin class?
I have registered a class like below to have an admin panel to upload images: android_dashboard.register(Banner, BannerAdmin) The banner model is as below: class Banner(models.Model): image = ImageField( _('Image'), upload_to=upload_path, blank=True, null=True, content_types=['image/jpg', 'image/jpeg', 'image/png'], max_size=1 * 1024 * 1024, extensions=['jpg', 'jpeg', 'png'] ) type_of_banner = models.CharField(_('Type of Banner'), max_length=3, default='web') class Meta: verbose_name = _('Banner') verbose_name_plural = _('Banners') def __str__(self): return '%s' % str(self.id) And the model admin is like below: class BannerAdmin(admin.ModelAdmin): model = Banner fields = ('image', 'type_of_banner') list_display = ('image', 'type_of_banner') For now when I login into admin section I can upload image directly to server. But I want to check ratio before uploading the image. The question is how and in what stage I should check the image width & height before uploading the image? -
How can i Pass arguements and execute R script from django forms
How can i pass arguements and execute R script in django forms. I have an idea, something like in the gif file below but instead of graph i just want to give the model's predicted output in R. My model and dataset is all ready and predicting completely. Just need the right start to it. https://www.codeproject.com/KB/PHP/1119237/phprscript_2.gif -
algorithm to calculate the profile percentage complete
I have written a simple code for calculating the percentage of profile complete. The way i have done does not covers the field which are a foreign key to the profile model. Here is how i have done def calculate_profile_percentage(self, context): # fk related field are not here fields = {'full_name': 10, 'age': 10, 'city': 10, 'address': 10} completed_profile_percent = 0 try: user = json.loads(context.get('user'))[0].get('pk') profile_instance = model_to_dict(Profile.objects.get(user=user)) print('profile get_instance', profile_instance) for field in profile_instance: print ("field", field) if fields.get(field) is not None: print("field found", field) completed_profile_percent += fields[field] except Profile.DoesNotExist: logger.error("Profile does not exist") print("completed_profile_percent", completed_profile_percent) return completed_profile_percent This is a basic one but how do i handle fk related part either. Does anyone have better algorithm considering the Fk fields either? -
In the forms of an inline formset can I customize the field generated by can_delete?
In the forms of an inline formset can I customize the field generated by can_delete ? I want to add a class and an attribute to the field, for front-end manipulation. -
Djang ORM queryset count always returns zero
I have a django ORM queryset that I am trying to retrieve the count from. I have tried to approach this in several ways but I can't explain queryset behavior based on what I have found in the docs. Her is what I've tried: 1) queryset.count() always zero without hitting the db 2) queryset.aggregate(Count('id')) returns: {'id__count': None} (and it still doesn't hit the database). 3) list(queryset) hits the database and shows that records exist(yields list of model instances) -
Django: Dynamic forms, drop down onchange
How do I create form that dynamically change dependent upon which choice I make in a drop down? implementation in Django, Bootstrap. e.g. I choose "CAR" and get the form fields "Color", "No of wheels". e.g. if I choose "ANIMAL" then I get the form fields "Type", "No of Legs". I wish not to create a separate page for each form. I am aware that the answer might involve JQuery, Ajax, but pointing that out, is unfortunately no help, its a bit too theoretical to convert into a practical solution. However, the real problem/my question is to get tips of existing examples of practical implementations I could learn from. No matter how much I search google I cannot find it (as I most likely use wrong technical terms). I just need help with some crumbles to get starting, I can later post my solution. Much appreciate help with some code examples. -
Problem in installing third party application in django
I want to install Django-keyboard-shortcuts package using pip in my virtual environment but when I try to do pip install django-keyboard-shortcuts (the installation command for Django-keyboard-shortcuts package), I am getting the following error: Collecting django-keyboard-shortcuts Using cached https://files.pythonhosted.org/packages/b9/00/743c60d56a50cab02ca 8c2a2177b63e5b4548f3ce4293604422ad6651f67/django-keyboard-shortcuts-0.0.7.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\BRACKE~1\AppData\Local\Temp\pip-install-fo3hx5g1\django-key board-shortcuts\setup.py", line 121, in <module> long_description=read('README.rst'), File "C:\Users\BRACKE~1\AppData\Local\Temp\pip-install-fo3hx5g1\django-key board-shortcuts\setup.py", line 12, in read return codecs.open(os.path.join(os.path.dirname(__file__), *parts)).read () File "c:\users\bracketline\bracket\lib\encodings\cp1252.py", line 23, in d ecode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 8439: character maps to <undefined> ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\BRACKE~1 \AppData\Local\Temp\pip-install-fo3hx5g1\django-keyboard-shortcuts\ Can anyone tell me why this is happening? I am using django version 2.0.6 and python 3.6.8 Thank you -
Consommer rest ip Get avec Django
J ai fait une api avec Django qui retourne l adresse ip du client..je veux bien savoir comment consommer ce web service..quelles sont les lignes de code que je peux ajouter pour le faire. -
/i18n/setlang/ HTTP/1.1 302 set_language dosen't work
Configured localization, but language switching does not occur, in the console is issued "POST /i18n/setlang/ HTTP/1.1" 302 0 Settings: LANGUAGE_CODE = 'en' LANGUAGES = ( ('ru', _('Russian')), ('en', _('English')), ) LOCALE_PATHS = ( project_dir + "/apps/locale", ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['src/templates/', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', ... urls: urlpatterns = [ path('admin/', admin.site.urls), path('i18n/', include('django.conf.urls.i18n')), ... in template: <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> Generated localizations, translated and compiled -
get the profile of the requested user which is send as a serialized object
I am sending the requested user object to the background task which is responsible for getting the profile of that user and then calculate the completeness of profile. I could send the serialized user object but could not get the profile of that user. How do i do this? consumers.py class AccountBackgroundTasks(SyncConsumer): def calculate_profile_percentage(self, context): print("arrived here successfully") logger.info("context", context) weight = {'full_name': 10, 'age': 10, 'city': 10, 'address': 10} total = 0 try: user = context.get('user') profile_instance = model_to_dict(Profile.objects.get(user=user)) for field in profile_instance: try: total += weight[field] except AttributeError: logger.error("Could not find the field") continue except Profile.DoesNotExist: logger.error("Profile does not exist") return return total query.py @staticmethod def resolve_profile(self, info, **kwargs): print('info', info.context.user) # type <class 'apps.accounts.models.User'> print('type', type(info.context.user)) if info.context.user.is_authenticated: channel_layer = get_channel_layer() print("channel_layer", channel_layer) async_to_sync(channel_layer.send)('accounts', { 'type': 'calculate.profile.percentage', 'text': serializers.serialize('json', [info.context.user, ]) }) return Profile.objects.get(user=info.context.user) return None -
Django - Object has no attribute 'date'
I have the below code in my django project which works properly as long as the query returns items. If the Queryset returns no items (because no items are yet in the database), I get the following error: 'NoneType' object has no attribute 'date'. How Can I solve this? Thanks ! date_first_cf = CashFlow.objects.filter(item__slug=itemslug).first().date -
Object of type User is not JSON serializable
I am using django channels for background related task. I need to pass the requested user so that i can get the profile of that particular user and calculate the completeness of profile percentage. However, i get Object of type User is not JSON serializable issue. I tried json.dumps and JsonResponse but none of them worked. How can i now pass the requested user to my background task? Here is how i have done consumers.py class AccountBackgroundTasks(SyncConsumer): def calculate_profile_percentage(self, context): print("arrived here successfully") logger.info("context", context) weight = {'full_name': 10, 'age': 10, 'city': 10, 'address': 10} total = 0 try: user = context.get('user') profile_instance = model_to_dict(Profile.objects.get(user=user)) for field in profile_instance: try: total += weight[field] except AttributeError: logger.error("Could not find the field") continue except Profile.DoesNotExist: logger.error("Profile does not exist") return return total query.py @staticmethod def resolve_profile(self, info, **kwargs): print('info', info.context.user) # type <class 'apps.accounts.models.User'> print('type', type(info.context.user)) if info.context.user.is_authenticated: context = { 'id': info.context.user } channel_layer = get_channel_layer() print("channel_layer", channel_layer) async_to_sync(channel_layer.send)('accounts', { 'type': 'calculate.profile.percentage', 'text': json.dumps(context) }) return Profile.objects.get(user=info.context.user) return None i tried JsonResponse(context, safe=False). This did not work either. -
How to get all query of get method in django
i have a question about django, i want to show value of get method in value of input, i have code below, when i search single string like "first", it doesn't have any problem, but when i search like "first blog" the value of input just only first. How i can have and show all value of q in GET method. Thanks this is my view: model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5i def get_queryset(self): user = self.request.user queryset = user.post_set.all() request_get = self.request.GET if request_get.get('q'): queryset = queryset.filter(Q(title__icontains = request_get.get('q')) | Q(content__icontains = request_get.get('q'))) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["search"] = self.request.GET.get('q') return context and this my template: {% block content %} <form class="form-inline" method="GET"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="q" value={{request.GET.q}}> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}" > <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"D d M Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% if is_paginated …