Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax error with django
I'm trying to activate add to the favorite button with ajax, also the same button should remove from favorite if it is already there,, here is my full files: models.py class Favorite(models.Model): item = models.ForeignKey(Item, on_delete='CASCADE') user = models.ForeignKey(UserModel, on_delete='CASCADE') class Meta: unique_together = (('item', 'user'), ) urls.py path('<int:pk>/favorite_item/', views.favorite_item, name='favorite_item'), views.py @login_required def favorite_item (request, pk): favitem = get_object_or_404(Item, pk=pk) data = { 'is_fav': Favorite.objects.get(user=request.user, item=favitem).exists(), } if data ['is_fav']: Favorite.objects.get(user=request.user, item=favitem).delete() else: new_entry = Favorite.objects.create(item=favitem, user=request.user) return JsonResponse(data) home.html {% extends 'fostania_web_app/base.html' %} {% block javascript %} <script> $("#add_to_fav").click(function () { console.log( $(this).val() ); }); $.ajax({ url: form.attr("data-favorite_item-url"), data: form.serialize(), dataType: 'json', success: function (data) { if (data.is_fav) { alert('تم'); } } }); }); </script> </script> {% endblock %} {% block content %} {% load static %} {% include 'fostania_web_app/slide.html' %} <!-- Page Content --> <div class="container"> <h1 class="my-4" align="right" dir="rtl">إستثمرى فساتينك القديمة مع Fostania</h1> <!-- Marketing Icons Section --> <div class="row"> <div class="col-lg-4 mb-4"> <div class="card h-100"> <h4 class="card-header" align="right">إنشاء حساب جديد</h4> <div class="card-body"> <p class="card-text" align="center"><img src="{% static 'img/add_user_big.png' %}"><Br> قم بإنشاء حساب جديد على فوستانيا حتى تستطيع عرض الفستان على الموقع</p> </div> <div class="card-footer" align="right"> <a href="{% url 'signup' %}" class="btn btn-primary" style="background: linear-gradient(to right, … -
Django admin field display
This is my Device that I registered in admin.py: @admin.register(Device) class DeviceAdmin(admin.ModelAdmin): search_fields = ["device_type","serial_number","in_use_by","brand","model","type_number","mac_address"] list_display = ("device_type","serial_number","in_use_by","brand","model","type_number","mac_address","invoice",) list_filter = ("device_type","in_use_by","brand",) This is my Device model in models.py class Device(models.Model): device_type = models.ForeignKey(DeviceType,to_field='device_type') serial_number = models.CharField(max_length=200,unique=True) in_use_by = models.ForeignKey(User,to_field='username') brand = models.CharField(max_length=200,default="-", null=False) model = models.CharField(max_length=200,default="-", null=False) type_number = models.CharField(max_length=200,blank=True,null=True, default = None) mac_address = models.CharField(max_length=200,blank=True,null=True, default = None) invoice = models.BinaryField(blank=True) This is my form class from forms.py class ReturnForm(forms.ModelForm): class Meta: model = Device fields = "__all__" widgets = {"device_type": forms.Select(attrs={"class":"custom-select col-sm-4"})} exclude = ("serial_number","in_use_by","brand","mac_address","type_number","model","invoice",) Now, when I view my admin panel, the invoice gets displayed as a column name in the panel. But, when I view an object in more detail by clicking it, the invoice field is not displayed. What is the problem that has occured? How can I resolve this issue? Requesting immediate help. -
Give boost score within Django query set that matches a given list of ids
I have an SVD recommendation system that calculates score based on other users' votes. This gives a score to each article based on current user's voting preference. I also have a hotness field, which is a combination of time the article was created and how many votes it received. This is a user agnostic field. I am trying to combine them both when recommending new contents to a user since the user may not have done any made any votes and SVD will not work. While showing the user with hottest contents, I want to boost the value of hotness if the results matches the ids in rec_ids. If I can incorporated rec_scores, within the calculation, that will be even better! results = SVD_engine(user) rec_ids = [recommendation.object_id for recommendation in results] rec_objs = [recommendation.object for recommendation in results] rec_scores = [recommendation.score for recommendation in results] Article.objects.order_by('-hotness').??? I suppose I can try to combine the results, but the result I get from the SVD_engine is a list and it does not mix well with Query Set. -
How to Serialize Complex Object to JSON in python
I have complex object that composite list of other objects. I will serialize this object to JSON value to perform creation an viewModel. class refereereport(Model): competition = models.ForeignKey(competition, on_delete=models.CASCADE) reportdate = models.CharField(max_length=10) reporttime = models.CharField(max_length=10) reviewerreferee = models.ForeignKey(reviewer, on_delete=models.CASCADE) federationdeletage = models.CharField(max_length=100) longdescriptions = models.TextField() isdelete = models.BooleanField() class competitionreferee(Model): competitionkey = models.ForeignKey(competition, on_delete=models.CASCADE) referee = models.ForeignKey(referee, on_delete=models.CASCADE) type = models.CharField(max_length=30, choices=refereemebers) -
djnago user.get_users showing wrong username
I was developing login page and home page for the loggedin user. Everything is working perfectly but after i deployed it on heroku and checked my website on my mobile phone some user names are incorrect. Either some characters are missing or some are added. <header id="header"> <div class="inner"> <a href="{% url 'home' %}" class="logo">criclysis</a> <nav id="nav"> <a href="{% url 'home' %}">Home</a> <a href="{% url 'about' %}">About</a> {% if user.is_authenticated %} <div class="dropdown"> <a><i class="fa fa-user"></i> {{ user.get_username }}</a> <div class="dropdown-content"> <a href="{% url 'logout'%}?next={{request.path}}">Logout</a> </div></div> {% else %} <a href="{% url 'login'%}?next={{request.path}}">Login</a> {% endif %} </nav> </div> </header> This is my code. -
How to send SMS in python/django
I create a table which has multiple checkboxes in it. now what I want is this when the checkbox is selected the SMS will send to the particular number which gets by the table. -
Does Django emit signals when email messages are sent?
Would like to know if signals are emitted when an email is sent using send_mail or send_mass_mail and how to listen in on them. Or do I have to emit messages myself. My use case is I want to log whenever an email is sent. The issue is that I do not want to have to mechanically log the sending of emails as this could be scattered over many parts of the application. -
handle spaces in the URL parameter using re_path
I am passing 2 variables in the URL foo, bar. The variable bar has a multiple words with spaces between it. On the basis of foo and bar the content of the template is rendered. Whenever bar has a space in between the words my url handler gives a 404. example: localhost/post/foo/ba r/ results in a 404 urls.py urlpatterns = [ re_path('post/<slug:foo>/<slug:bar>/', post), ] views.py def post(request, foo, bar): query = Blog.objects.all().filter(category=foo, title=bar) return render(request, 'blog/post.html', {'blog': query, 'cat': foo, 'tit': bar}) post.html {% for i in blog %} {{ i.content }} {% endfor %} -
Django form prints no error and is not valid
To create a form in my website, I created some models corresponding to my fields. Then I created ModelForms from them, some views and templates. My problem is that I never see my forms errors first, and second, this particular field always has his form not valid, even with one attribute in it. Can you explain me what I'm doing wrong ? models.py class Grapheme(models.Model): lexeme = models.ForeignKey(Lexeme, on_delete=models.CASCADE) value = models.CharField(max_length=256) class Meta: verbose_name = "grapheme" ordering = ["value"] def __str__(self): return self.value forms.py class GraphemeForm(forms.ModelForm): class Meta: model = Grapheme fields = ['value'] views.py @login_required def lexeme_edit_view(request, lexicon_id): [...] if request.method == 'POST': lexeme_form = LexemeForm(request.POST) grapheme_form = GraphemeForm(request.POST) [...] if grapheme_form.is_valid(): [...] template.html {% if grapheme_form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in grapheme_form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} [...] <div class="form-group row"> <label for="graphemeInput" class="control-label col-lg-2">{{ grapheme_form.value.label }}</label> <div class="col-lg-6"> {% if grapheme_form.is_bound %} {% if grapheme_form.value.errors %} {% for error in grapheme_form.value.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% endif %} {% if grapheme_form.value.help_text %} <small class="form-text text-muted">{{ grapheme_form.value.help_text }}</small> {% endif %} {% endif %} {% render_field grapheme_form.value type="text" class+="form-control" id="graphemeInput" %} … -
Split the date_hierarchy and get_queryset in django admin
I'm working with django 1.11 and I want to split the date_hierarch from get_queryset, because I want to have selected items in the list, but at the top of the page, I want to be able to choose all months. Is it possible? admin.py date_hierarchy = 'date' def get_queryset(self, request): currentMonth = datetime.now().month qs = models.Event.objects.all().filter(date__month__lte=currentMonth+1) return qs -
How to make use of auth_group table in Django
I have written a class in views.py file for adding a group in auth_group table. But i am getting an error message saying: - duplicate key value violates unique constraint "auth_group_name_key" DETAIL: Key (name)=() already exists. Following is my views.py file code. class AddGroup(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) def post(self, request): log.debug("Getting into the function !!") try: log.debug(request.data) group11 = Group.objects.create() log.debug(group11) group11.save(2, str(request.data['customer'])) # group11.save(str(request.data['customer'])) log.debug(group11) return Response(request.data['customer']+' created successfully !!', status= status.HTTP_201_CREATED) Following is my models.py code class MyGroup(GroupManager): use_in_migrations = True def create(self, group_name): # GroupManager.create(group_name) group = self.model( group_name=group_name, ) group.save(using=self._db) return group -
Django 1.11 admin: Create a OneToOne relationship and it's object in the admin
I have a simple app (about qr codes) in which I have two models. The first on is for defining the QR Code and the second one is for giving it a function. (For those wondering: I split it up into two models, because our qr codes are complex and sometimes lack functions and are read only. I wanted to keep our database as normalized as possible.) Here is the model (models.py): from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.utils.translation import ugettext_lazy as _ from core.behaviors import QRCodeable, UniversallyUniqueIdentifiable from core.utils import QR_CODE_FUNCTIONS from model_utils.fields import StatusField from model_utils.models import SoftDeletableModel, TimeStampedModel QR_CODE_PREFIX = "QR Code" QR_CODE_FUNCTION_PREFIX = "Function" QR_CODE_FUNCTION_MIDFIX = "for" class QRCode( UniversallyUniqueIdentifiable, SoftDeletableModel, TimeStampedModel, models.Model ): @property def function(self): try: return self.qrcodefunction.qr_code_function except ObjectDoesNotExist: return "" class Meta: verbose_name = _('QR code') verbose_name_plural = _('QR codes') def __str__(self): return f'{QR_CODE_PREFIX} {self.uuid}' class QRCodeFunction( UniversallyUniqueIdentifiable, SoftDeletableModel, TimeStampedModel, QRCodeable, models.Model ): QR_CODE_FUNCTIONS = QR_CODE_FUNCTIONS qr_code_function = StatusField(choices_name="QR_CODE_FUNCTIONS") class Meta: verbose_name = _('QR code function') verbose_name_plural = _('QR code functions') def __str__(self): return f'{QR_CODE_FUNCTION_PREFIX} {self.qr_code_function} {QR_CODE_FUNCTION_MIDFIX} {self.qr_code}' The mixin QRCodeable is an abstract base class which gives the function a OneToOne relation to the qr code. The mixin … -
Proper way to access nested foreignkey objects?
I have models with hierarchical relationships: class School(models.Model): name = models.CharField() class Class(models.Model): school = models.ForeignKey(School) class Student(models.Model): class = models.ForeignKey(Class) And I'd like to retrieve every Student objects related to certain School. I usually did it like below: the_school = School.objects.get(name='Springfield Elementary School') students = Student.objects.filter(class__school=the_school) But this method needs two models to look up (School and Student) which seems somewhat unnecessary... For me. So I tried to make a single line query, using Django's built in related manager: students = School.objects.get(name='...').class_set.student_set.all() # or students = School.objects.get(name='...').class_set.all().student_set.all() ...which did not work. How can I make a query referencing down from given School object? Or is there any better solution? -
Django GeneratePDF with xhtml2pdf - Method not allowed (GET)
I would modify the following class GeneratePDF for rendering my template that is dynamically generated views.py class GeneratePDF(View): def get(self, request, *args, **kwargs): template = get_template('invoice.html') context = { "invoice_id": 123, "customer_name": "John Cooper", "amount": 1399.99, "today": "Today", } html = template.render(context) pdf = render_to_pdf('invoice.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %("123") content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") I generate my template with the following: class MyReport(ListView): model = Reports template_name = 'myreports.html' context_object_name = 'myreports' def get_context_data(self, *args,**kwargs): context = super(MyReport, self).get_context_data(*args,**kwargs) context['reports'] = Reports.objects.all().values('id','idsys','itemcode','ordercode').filter(id=self.kwargs['id'],idsys=self.kwargs['idsys']) return context and I'm trying to generate PDF with the following class modified: class GeneratePDF(View): def get_context_data(self, *args,**kwargs): template = get_template('myreports.html') context = super(GeneratePDF, self).get_context_data(*args,**kwargs) context['reports'] = Reports.objects.all().values('id','idsys','itemcode','ordercode').filter(id=self.kwargs['id'],idsys=self.kwargs['idsys']) html = template.render(context) pdf = render_to_pdf('myreports.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "myreports_%s.pdf" %("1") content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") urls.py url(r'^reports_pdf/(?P<id>\d+)/(?P<idsys>\d+)/$', views.GeneratePDF.as_view()) but I receive the error: Method not allowed (GET) Have you any suggestions? Thank's (I followed this: Render_to_PDF_in_Django) -
Issue with installing new SSL certificate in my server
I am running an application in a Centos 6.4 VM. Last year I have installed SSL certificates from rapidssl vendor and everything was working fine till now. IT send me the new certificates and I installed them in a similar way but they do not work as expected. The application I am running is a Django project which is using an Nginx server (and Uwsgi) together with Tomcat (tomcat6). In the Tomcat server there is a Geoserver deployed. So after installing the new SSLs certificates the interaction of the application with the Geoserver broke. That means that certain functionalities (such as loading services from Geoserver etc.) do not work anymore. Apparently the vendor of the new certificate is different (Comodo). They use 2 intermediate certificates, which can affect installs. I also read that if the application hasn't been updated yet to allow industry standard SSL Certificate security then this could be the issue. But since I am not an administrator expert (neither SSL expert), I am not sure exactly what this means. I am trying to find out the source of the issue. Could it be the version of the OS (Centos 6.4?) Could it be the version of the … -
Security measures before inserting data into MySQL in Django
I have this ajax code that sends the text of textarea to my Django code $.ajax({ url:'/fun/submitblog', data:{ 'text':$(".blogtext").val().trim() }, datatype:'json', success:function(data){ console.log(data); } }); I receive this data like this in Django: def submitblog(request): txt = request.GET.get('text', None) Now i want to insert this 'txt' into database,but i want to do it maximumly safe.What safety precautions should be taken? -
How to QuerySet for Post per month
I have a model as such class Post(models.Model): submission_time = models.DateTimeField() user = models.ForeignKey(User) and I would like to have a queryset where it returns the number of Posts a user has made per month. I have tried using ExtractMonth as so : user.post_set.annotate(month_sub=ExtractMonth('submission_time')).values('month_sub').annotate(count=Count('month_sub')) But its giving me a QuerySet like this : <QuerySet [{'month_sub': 5, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}]> Instead of one like this(Which i'd like to have) : <QuerySet [{'month_sub': 5, 'count': 1}, {'month_sub': 6, 'count': 7}]> Any Ideas on how to receive a queryset like so ? -
Django file saving to sqlite3 db and retrieval
The following is my device model: class Device(models.Model): device_type = models.ForeignKey(DeviceType,to_field='device_type') serial_number = models.CharField(max_length=200,unique=True) in_use_by = models.ForeignKey(User,to_field='username') brand = models.CharField(max_length=200,default="-", null=False) model = models.CharField(max_length=200,default="-", null=False) type_number = models.CharField(max_length=200,blank=True,null=True, default = None) mac_address = models.CharField(max_length=200,blank=True,null=True, default = None) invoice = models.FileField(upload_to='', null=True) Here, the invoice field is not of use to me in my website but, it is of use to me as a admin. What I am basically trying to do is, if a device request is accepted then, I will upload the invoice of the device into my sqlite db using the admin panel. I am a newbie to Django and hence, require help for this purpose. Also, I will only upload file through django admin. How should I achieve this? What should I write in upload to parameter so that the file is stored in database? -
Django Admin. How to add background color for each row in list view, when object has boolean field == True?
My env is: Django 2.0.6, Python 3.6.4 I have standard Django Admin (with inline edit): How to add background color for each row in list view, when object has field is_active_city=True? For example, background-color: green; for is_active_city=True and background-color: yellow; for is_active_city=False, like this: -
How to fix this error in geonode
when we run this command : :/usr/local/lib/python2.7/dist-packages/geonode/locale/si/LC_MESSAGES# geonode makemessages --all Get this error message : CommandError: This script should be run from the Django Git tree or your project or app tree. If you did indeed run it from the Git checkout or your project or application, maybe you are just missing the conf/locale (in the django tree) or locale (for project and application) directory? It is not created automatically, you have to create it by hand if you want to enable i18n for your project or application. could you please help for me to solve this problem... -
Improve server performance of a client-server application
I am new at client-server applications, and I am developing an application using Django (which is not a must): The application contains projects: the data structure of all projects are identical (use the same classes – about 20). The content is not shared between one another (each project contains hundreds of instances of those classes – in total, each JSON size is less the 1MB) The number of concurrent users will be less than a dozen (most of the time there will be only one user if at all) There won’t be more than a few thousands of projects during the life of the product. There are different requests per project, each request results with the need to run over all the project’s content (read), and may modify/add/delete. Currently I am using the Django model (squlite3), and one action computing time may take around 10 seconds (by the server). Note that I tried all Django optimization suggestions. The question is how can I significantly reduce the processing time (down to micro sec)? I assume that due to the Django model architecture (columns and tables per class), the latency of each request is due to the Django architecture - the distribution … -
Generate barcode from UUID in Django
What's the best way to generate a Barcode from a model in Django? I don't need to store the image generated just create a Barcode in .svg to show in the DetailView of the model. Javascript solutions are welcome but I aim to do it in a Django/Pythonic way if possible. -
MultiSelect in django no alloiwng multiple choices
I have an option for the user to select times, (half hours of the day), they can select as many as they like, and there are no constraints so (00:00, 01:00, 01:30) would be ok. But I can't get that to work as a field, I always get (is not in the available choices, as the specific combination will not be in their unless I enumerate all, but even with that I've struggled. Current files: forms.py from django import forms from .models import InputData class InputForm(forms.ModelForm): class Meta: model = InputData fields = ('periods') widgets = { 'periods': forms.MultipleSelect(attrs={'class': 'form-control','size': 48}), models.py times_list = ['00:00', '00:30','01:00','01:30','02:00'] periods_choices = list(choices(times_list,times_list)) class InputData(models.Model): periods = models.CharField("Available periods:", max_length=96, choices=periods_choices, blank=False, default='all') I've tried enumerating all the possibilities with itertools.combinations but I can't get the output to work as a set off choices. -
Using Daphne behind nginx
I have a Django app that used uWSGI alongwith Nginx for production deployment. Now I am integrating Channels 2.0 and realised that Daphne is the substitute for uwsgi here. I am able to get Daphne to serve when running it in standalone mode, but when I try to run it behind nginx proxy, i keep getting Connection Timeout (504) My nginx config file was what I configured for uWSGI server and I am expecting it to just work otb because the socket name is same. Possible Issues: From what it looks like in the nginx logs, nginx tries to connect to uwsgi://unix:///path/to/nginx.sock but I think it should not be prefixed with uwsgi and should be just unix:///path/to/nginx.sock. Followup Questions: Is it recommended to use Daphne to server http and websocket both? Or should I be using uWSGI for http and Daphne only for websockets. If using Daphne for both, am I correct in keeping the same uwsgi_params file? settings.py INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_celery_results', 'home', 'corsheaders', 'rest_framework', 'channels' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware' ] WSGI_APPLICATION = 'home.wsgi.application' ASGI_APPLICATION = "home.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": … -
Django sign-up form scroll default
Hi in Django I have created a sign-up page, but the problem is if the page is loaded the page automatically scrolls to the e-mail field of the form instead of the top of the page. How can I stop this?