Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make ckeditor image upload simple drag and drop
In CKeditor, I did the RichTextUploadingField and all. Everything working perfectly fine. I can see the Image button in top menu. But it is too confusing for user. Like clicking on image button->upload->select Image->send it to server. It's too much for User. Like I need it very simple image upload in ckeditor. What I want is simple image uploading. Meaning, User friendly like click on Image button and then drag and drop or select image(Browse) and upload. There are many thing like image info, link and advanced which I don't want. Because it confuse my users. Can anyone help me with this? Please. By the way I am using django-ckeditor==5.9.0 -
can I display (django's detailview) on (Bootstrap's Modal view)?
I wanna Open an object details(DetailView) in a Bootstrap Modal dialog(not redirecting to another page) thnx in advance -
how to extract particular data from text file on django
when i click on upload file from front end. i would like to extract data from uploaded file in django views.py demo.txt <p> <table border=3D"1"> <tbody> <tr> <th> ID</th> <th>Action</th> <th>Date/Buyer</th> <th> Due By</th> <th> Title</th> </tr> <tr> <td>1435523</td> <td>MODIFIED</td> <td>07/13/2020 02:50:52 PM EDT</td> <td>07/17/2020 03:00:00 PM EDT</td> <td>test</td> </tr> </tbody> </table> </p> </a>Also, please remember that you have the opportunity= to view on additional in django views im trying to extract data from a textfile,and i want to extract only inside data and save it into database,i dont know what to do can any one help me with this def upload_view(request): if request.method == 'POST': print(request.POST) f=request.FILES['file'].read() print(f) inFile = f outFile = open("result.txt", "w") buffer = [] keepCurrentSet = True for line in inFile: buffer.append(line) if line.startswith("<p>"): # ---- starts a new data set if keepCurrentSet: outFile.write("".join(buffer)) # now reset our state keepCurrentSet = False buffer = [] elif line.startswith("</p>"): keepCurrentSet = True print(buffer) return render(request, 'upload.html') else: return render(request, 'upload.html') -
problem in making the groups using django framework! PLEASE HELP OUT
A user want to make a group so that he is the admin of that groups but he also want that if any other user of the site who is not his friend is interested in his group, can click the join button for joining the group then he should be prompted for the password of the group in order to join the group (password of group is set by admin while creating the group). <-- This is what i want but i am unable to find a way to take the password from group admin and authentication with it for other users for joining the group... PLEASE HELP ME AS I AM NOT PROFESSIONAL IN DJANGO here is my models.py file from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.utils.text import slugify # from accounts.models import User import misaka from django.contrib.auth import get_user_model User = get_user_model() from django import template register = template.Library() class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') description_html = models.TextField(editable=False, default='', blank=True) members = models.ManyToManyField(User,through="GroupMember") def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) self.description_html = misaka.html(self.description) super().save(*args, **kwargs) def get_absolute_url(self): return … -
AttributeError at /mobile/7/delete/ 'tuple' object has no attribute '_meta'
I am trying to delete an item from my project but it gives error. interestingly it is deleting the item but gives error mention above. views.py: def delete_mobile(request, mobile_id): mobile1 = get_object_or_404(Mobile, pk=mobile_id).delete() form = MobileForm(instance=mobile1) if form.is_valid(): form.delete() return redirect('mobile') return render(request, 'device/delete_mobile.html', {'mobile': mobile1}) delete_mobile.html: {% extends 'device/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <form action="{% url 'delete_mobile' mobile.instance.id %}" method="POST"> {% csrf_token %} <h3>Delete {{ header }}:</h3> {{ mobile|crispy }} <button class="btn btn-success" type="submit">Delete</button> </form> {% endblock %} urls.py: path('mobile/<str:mobile_id>/delete/', views.delete_mobile, name='delete_mobile'), -
Configuring Django Rest Framework Pagination
The docs for Django Rest Framework say that configuring pagination is as simple as adding the default pagination class and size to settings.py and making sure that you are using a GenericAPIView. I am doing both of these things and the pagination is not working for me. GET /domains/example.com/hosts/?page=1 returns a 404 error GET /domains/example.com/hosts?page=1 returns all the results What am I missing here? settings.py REST_FRAMEWORK = { 'COERCE_DECIMAL_TO_STRING': False, # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_RENDERER_CLASSES': DEFAULT_RENDERER_CLASSES, 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } views.py class HostList(generics.ListAPIView): """ List all hosts for a given domain """ host_service = HostService() queryset = Host.objects.all() pagination_class = PageNumberPagination def get(self, request, domain_name, format=None): hosts = self.host_service.find_hosts_by_domain_name(domain_name) if len(hosts) == 0: return Response(status=status.HTTP_404_NOT_FOUND) serializer = HostSerializer(hosts, many=True) return Response(serializer.data) urls.py urlpatterns = [ path('domains/', views.DomainList.as_view()), path('domains/<str:domain_name>', views.DomainDetail.as_view()), path('domains/<str:domain_name>/whois', views.DomainWhoisDetail.as_view()), path('domains/<str:domain_name>/hosts', views.HostList.as_view()) ] serializers.py class HostSerializer(serializers.Serializer): created = serializers.DateTimeField() last_updated = serializers.DateTimeField() name = serializers.CharField(); -
Vscode does not read the css after restart
I'm student of programming and i just started working at yesterday on vscode. I'm trying to make a social/house rent platform by using django/jquerry. I made some html, css, js pages, there is a no problem about this, everything okay and working.. then i slept and today just turned on my pc but vscode didn't read the css files (not sure about js files too). I use href="{% static 'polls/style.css'}" method for calling static files I tried everything but it's still wasn't reading the current files. So i did <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> to //the only difference is name of the css file <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> and renamed my stlye.css file to styles.css and bang it's working... I thought it was a one time bug but it's not. Before 15 min ago i put my computer to sleep mode and when i came back i solved the same problem the same way.. does anyone have this problem and how can i fix it ? -
Dynamically add inline formset in django using javascript
I have modelform called WorkExperienceForm. Currently the form is adding only one information. I want to convert it in formset. forms.py: class WorkExperienceForm(forms.ModelForm): """ Creates a form for saving employee work experiences """ class Meta: model = WorkExperience fields = [ 'previous_company_name', 'job_designation', 'from_date', 'to_date', 'job_description', ] widgets = { 'previous_company_name': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'job_designation': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'from_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal3'}, format='%m/%d/%Y'), 'to_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal4'}, format='%m/%d/%Y'), 'job_description': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) I want to add a "Add" button to the frontend. When user presses add button, same form will be generated. This can be done unlimited times. Any help will be appreciated. -
Django filter is not working with a field having + value
I have a field in my models as: cl_name Whenever i try to filter any queryset : def get_queryset(self): cl_name = self.request.query_params.get('cl_name', None) //somecode queryset = queryset.filter(cl_name=cl_name) Whenever cl_name has lorem+ipsun ,filter is not working but it's working fine if there's no + sign. -
pass argumant in url without clean other argumant in django and js
i use Paginator django and when i click on pages button. url changes to this : /admin/orders/?page=2 now i want to set status in url arguments like this : /admin/orders/?status=1. it works! but in this case when i change page , status parameter is cleaned! i want to set both of parameter in url like this : /admin/orders/?status=1&page=2 how can i solve this problem with js? this is my paginator code : if request.method == "GET": orders = get_orders(request.GET) orders = Paginator(orders,5) page = request.GET.get('page') if page is None : page = 1 order_list = orders.page(page) print(len(orders.page_range)) index = order_list.number - 1 max_index = len(orders.page_range) start_index = index - 3 if index >= 3 else 0 end_index = index + 3 if index <= max_index - 3 else max_index page_range = list(orders.page_range)[start_index:end_index] for o in order_list: o.product.name = get_product_name(o.product) statuses = Status.objects.all() context = { 'orders' : order_list, 'page_range' : page_range, 'statuses' : statuses } return render(request,'staff/orders/products.html',context) and this is my paginator section in html template : {%if orders.has_previous%} <li class="page-item"> <a class="page-link" href="?page={{orders.previous_page_number}}" tabindex="-1">قبلی</a> </li> {%else%} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1">قبلی</a> </li> {%endif%} {% for pg in page_range %} {% if blogs.number == pg %} <li class="page-item … -
Why function to_excel of Pandas lowercases the formulas string?
thank you for helping me. I'm trying to write an excel from a pandas.DataFrame using function .to_excel(). It's everything ok, but the issues is that something happen to the formulas I have in the dataframe, I show you what: for indx in range(len(currency)): if currency[indx] in list_currencies: row = str(list_currencies.index(currency[indx]) + 2) c_2019 = '=%s*$Currency.%s%s'%(str(gt_2019_mzero[indx]), index_excel['2019'], row) c_2020 = '=%s*$Currency.%s%s'%(str(gt_2020_mzero[indx]), index_excel['2020'], row) c_2021 = '=%s*$Currency.%s%s'%(str(gt_2021_mzero[indx]), index_excel['2021'], row) c_2022 = '=%s*$Currency.%s%s'%(str(gt_2022_mzero[indx]), index_excel['2022'], row) c_2023 = '=%s*$Currency.%s%s'%(str(gt_2023_mzero[indx]), index_excel['2023'], row) gt_2019_toconvert.append(c_2019) gt_2020_toconvert.append(c_2020) gt_2021_toconvert.append(c_2021) gt_2022_toconvert.append(c_2022) gt_2023_toconvert.append(c_2023) ... dataframe_impacts.insert(32, 'inde_2019 >= 0 €', gt_2019_toconvert) dataframe_impacts.insert(33, 'inde_2020 >= 0 €', gt_2020_toconvert) dataframe_impacts.insert(34, 'inde_2021 >= 0 €', gt_2021_toconvert) dataframe_impacts.insert(35, 'inde_2022 >= 0 €', gt_2022_toconvert) dataframe_impacts.insert(36, 'inde_2023 >= 0 €', gt_2023_toconvert) Then, in the view: # Create a Pandas Excel writer using XlsxWriter as the engine. options = {} options['strings_to_formulas'] = True writer = pd.ExcelWriter(excel_path, engine='openpyxl', options=options) # Write on excel: impacts.to_excel(writer, sheet_name='Impacts', index=False) currencies_table.to_excel(writer, sheet_name='Currency', index=True) So, for example c_2019 should be --> c_2019 = "=500*$Currency.C3" ( is value*%SHEET_NAME.CELL_COORDINATES) But what I actually get inside the excel file in the cell is "=500*&currency.c3", all letters in lowercase making the formulas does not working at all. Can anyone help me to figure it out? I'm using: Python 3.7.8; … -
413 Request Entity Too Large error in Django on AWS
I have a Django application which it's deployed to Amazon Elastic Beanstalk(Python 3.7 running on 64bit Amazon Linux 2/3.0.3). I need to get .igs file in one of my forms but I'm getting 413 Request Entity Too Large error. I have tried the solution below and it's combinations but they didn't work. .ebextensions/nginx-file-fize.config container_commands: 01_reload_nginx: command: "sudo service nginx reload" files: "/etc/nginx/conf.d/proxy.conf" : mode: "000644" owner: root group: root content: | client_max_body_size 25M; How can I fix this issue? -
Query based on ManytoMany Field Django
I have the following models on which I want to query based on ManytoMany Field: class Topping(models.Model): topping_name=models.CharField(max_length=16) class Cart_Item(models.Model): pizza=models.ForeignKey(Pizza, blank=True, null=True, on_delete=models.CASCADE) toppings=models.ManyToManyField(Topping, blank=True) quantity=models.IntegerField() I have a list of toppings available with me. I want to query a Cart_Item where toppings field contains all the values in the list. For example if my list is toppings_list=["Pepperoni","Mushroom"], then I want the Cart_Item where toppings contains only these 2 toppings. How can I query like that? -
xlwt showing date differently
i am trying to generate a excel file from model in django but the date comes different how do i change it. i tried num_format_str but it changes everything to date import xlwt def excelfilegenerator(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="users.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('details') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['DATE', 'UNIT', 'Blowroom', 'Waste_collection','Carding','Comber_and_drawing','Speedframe','pre_total','Spg_db1','Spg_db2', 'Spg_db3','Spg_db4','Spg_total','Autoconner','Post_Spinning_Total','Pre_HMD','Spg1_HMD','Spg2_HMD','Post_spg_HMD','Total', 'Compressor','Lightning','Total_units','Production','U_K_G','Con_pro_40s','Con_UKG_40s','Compac_con_pro_40s','Compac_con_ukg_40s',] # columns = ['DATE',] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() date = xlwt.XFStyle() date.num_format_str = 'dd/mm/yyyy' rows = TableModel.objects.all().values_list('Date','Unit', 'Blowroom', 'Waste_collection','Carding','Comber_and_drawing','Speedframe','pre_total','Spg_db1','Spg_db2', 'Spg_db3','Spg_db4','Spg_total','Autoconner','Post_Spinning_Total','Pre_HMD','Spg1_HMD','Spg2_HMD','Post_spg_HMD','Total', 'Compressor','Lightning','Total_units','Production','U_K_G','Con_pro_40s','Con_UKG_40s','Compac_con_pro_40s','Compac_con_ukg_40s') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response -
How to display only the allowed foreign key values on the form in django?
I have four models class Courses(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=254) assigned_teacher=models.ForeignKey('users.Teacher',null=True,blank=True,on_delete=models.SET_NULL) price=models.DecimalField(max_digits=6,decimal_places=2) class Section(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=254) course=models.ForeignKey(Courses,on_delete=models.CASCADE) class Video(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=254) url=models.URLField(max_length=200) section=models.ForeignKey(Section,on_delete=models.CASCADE) course=models.ForeignKey(Courses,on_delete=models.CASCADE) class Teacher(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) bought_course=models.ManyToManyField(Courses) I am making a video creation form that has the foreign key section. Now, I want the course foreign key to only display the courses that have been assigned to the teacher and further show the sections available in the course selected. Any suggestions on how to proceed with this? I am working in Django. -
GUnicorn not showing up locally, not using any ports (Django)
I am trying to run a Docker container via the command: docker run --rm -d projectname:latest And I get the following gunicorn lines: [2020-07-28 11:56:50 +0000] [10] [INFO] Listening at: http://127.0.0.1:8000 (10) [2020-07-28 11:56:50 +0000] [10] [INFO] Using worker: sync [2020-07-28 11:56:50 +0000] [12] [INFO] Booting worker with pid: 12 From this I thought it was working fine. However, nothing is showing up in 127.0.0.1:8000. After using Network Utility's port scanner, no ports above or including 8000 are being used. When I right click on the container in Visual Studio Code (with Docker extension installed) and click 'Open in Browser' it states "No valid ports are available. Source: Docker (Extension)". How can I see the app running locally? What could the issue possibly be? -
DjangoCMS Getting Authors and Their Article Counts Efficiently
I am currently trying to setup a plugin for a site running DjangoCMS. This plugin does something quite similar to what some plugins in AldrynNewsBlog do. However, there will be some differences. Basically, there are authors and they have articles, videos and other content on the site. The plugin will serve the page that contains thumbnails of all these authors and a summary of content for each author. This is the plugin code: class AuthorsPlugin(NewsBlogAuthorsPlugin): """ We are modeling this plugin after AldrynNewsBlog Authors plugin. It is a good start, and there will be some diveregences in functionality. """ label = models.CharField(_("Plugin Name"), max_length=200) draft_id = models.IntegerField(null=True, blank=True) authors = models.ManyToManyField(CommonModels.AuthorProfile, related_name="authors_list_plugin") def copy_relations(self, oldinstance): #self.mentors = oldinstance.mentors for author in oldinstance.authors.all(): self.authors.add(author) author.save() def get_authors_and_article_counts(self, authors): """stub for future method returning authors and their article counts""" # first set up getting the article count subquery = """ SELECT COUNT(*) FROM aldryn_newsblog_article WHERE aldryn_newsblog_article.author_id = aldryn_people_person.id AND aldryn_newsblog_article.app_config_id = %d""" #limit subquery to published articles subquery += """ AND aldryn_newsblog_article.is_published %s AND aldryn_newsblog_article.publishing_date <= %s """ % (SQL_IS_TRUE, SQL_NOW_FUNC, ) for author in self.authors: pass Author model is as follows: from aldryn_people.models import Person @python_2_unicode_compatible class AuthorProfile(models.Model): full_name = HTMLField(configuration='CKEDITOR_SETTINGS_TITLE') … -
Why am I getting logs in this order while making ajax call?
I am trying to make ajax call using JQuery in Django but I am not able to get the expected output. Not able to debug even after struggling for hours now I am posting it on stack overflow, Would be glad if you explain me the problem Input var team_with_mentor; var team_without_mentor; var users = []; var mentors; var names = {}; $.ajax({ url: "{% url 'mentor' %}", method : 'GET', dataType: 'json', success: function (data) { mentors = data; // console.log(mentors); } }).then(() => { for(let i=0; i<mentors.length; i++){ get_name(mentors[i].id) } }).then(() => { console.log(mentors); for(let i=0; i<mentors.length; i++){ let name = names[mentors[i].id] console.log("name1", names); $('.selector').append(`<option class='p-3' key=${mentors[i].id}>${name}</option>`); } }) async function get_name(id) { await $.ajax({ url: "{% url 'mentor' %}", method : 'GET', data: { "id": id }, dataType: 'json', success: function (data) { // console.log(data.mentor) names[id] = data.mentor console.log("name2", names); } }) } Output name1 {} name2 {26: "asad asdasd"} name2 {26: "asad asdasd"} name2 {26: "asad asdasd"} name2 {26: "asad asdasd"} name2 {26: "asad asdasd"} name2 {26: "asad asdasd"} name2 {26: "asad asdasd"} please help me to understant what's happening behind the seen Doubt: Why it's not waiting for the second .then() block to finish before … -
How to fix playback error or get playback in Django?
I am trying to add a player in admin admin.py class Admin(admin.ModelAdmin): readonly_fields = ('player',) def player(self, obj): template = f'<audio controls>' \ f' <source src="{{obj.get_url()}}"> ' \ f'</audio>' #template = f'<audio src="obj.get_url()" controls></audio>' return mark_safe(template) Method get_url contain in some model: def get_url(self): return self.sound.url If I use commented template, I get an error: If I use uncommented template, music doesn't playback: -
How can i increase my quantity fields when users viewed second times on the same page
models.py class ProductDetailHistory(models.Model): user = models.ForeignKey(User, blank=True, on_delete=models.CASCADE) viewed_product_detail_id = models.CharField(max_length=120, blank=True, null=True) viewed_product_quantity = models.PositiveIntegerField(default=1) timestamp = models.DateTimeField(auto_now_add=True) views.py class ProductDetail(APIView): def get(self, request): if request.user.is_authenticated: user = self.request.user product_detail_id = request.GET.get('itemId') ProductDetailHistory.objects.create(user=user, viewed_product_detail_id=product_detail_id) here i want to update the quantity when the user views the product which he/she already viewed once if already created this users objects but i have no idea to do that. -
Django serializer string to float
I have a model with this field in the serializer: answer_star = DecimalField(max_digits=1, decimal_places=1, blank=True, null=True) I'm passing strings in the payload, e.g. "4.0" and this fails at the serializer level: @transaction.atomic def post(self, request, pk, format=None): review = self.get_object(pk) questions = request.data.get('questions') submitted = request.data.get('submitted') if submitted: review.update(status='PENDING') for updated_question in questions: question_id = updated_question.get('id') question = ReviewQuestion.objects.filter(pk=question_id) question.update(**updated_question) return Response() decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>] What's the cleanest approach for converting the answer_star field from a string to a float? -
i am unable to include static files in my django project
I know this is a common question but please excuse me as i have tried a lot of things.. my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "mainapp/static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') INSTALLED_APPS = ['django.contrib.staticfiles'] html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> <link rel="stylesheet" href="{% static 'mainapp/home.css' %}"> </head> <body> <div>hedge-born static files</div> </body> </html> css: .div{ color: aqua; font-size: 300px; } -
Trying to load a css stylesheet from a child template in django
I have a parent template with this code <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> {% load static %} <link rel="stylesheet" href="{% static 'base.css' %}"/> {% block additionalStyles %}{% endblock %} </head> and I have a child template with this code {% block additionalStyles %}<link rel="sytlesheet" href="{% static 'rants.css' %}"/>{% endblock %} this doesn't seem to work and I don't get an error either. The base.css loads fine and when I inspect element on the webpage I can see <link rel="sytlesheet" href="{% static 'rants.css' %}"/> in the HTML code but it doesn't have any affect on any of the elements that it should. Is there a better way of doing this? and why is it not working? -
search multple values over multiple fields in django filter
I have a Product Model with fields: Name -> CharField (product name) Brand -> FK to a model named Brand (Brand has a name and id) Description -> TextField (product description) I need to make a search for products which would intake multiple values eg. "Nike Black Shoes" where i need to search every word in every field described above. eg Nike would match in brand and Black would match in Description and Shoes would match in Name.. Something like that. Right now I'm using django-filters. https://django-filter.readthedocs.io/en/stable/ from django.forms.fields import MultipleChoiceField class MultipleField(MultipleChoiceField): def valid_value(self, value): return True class MultipleFilter(df_filters.MultipleChoiceFilter): field_class = MultipleField class ProductFilterBackend(df_filters.FilterSet): search = MultipleFilter( field_name="???", lookup_expr="icontains", widget=CSVWidget ) class Meta: model = models.Product fields = ["search"] I can put only a single field in field name so how do I search over all the 3 fields defined above ? If this can be done then is there way to get products ranked according to the amount of match so more relevant products can come above. -
Django - Why should I extend User as opposed to creating my one user class
All, I'm having some difficulty understanding what is the advantage of extending the user class in Django? I feel it's more advantageous to overwrite it and create my own user class, with all the files that I want. I'm asking this because all the tutorials that I see always refer to create a profile class and from there extend the user class. I would see the advantage if I wanted to extend the user class multiple times, but I feel that this never happens.