Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter by tags with custom Tag model
i'm trying to filter objects by tags names but get an exception. models.py: class Etiqueta(CommonGenericTaggedItemBase, TaggedItemBase): object_id = models.CharField(max_length=50, verbose_name=_('Object id'), db_index=True, null=True) class Lugar(Entidad): etiquetas = TaggableManager(verbose_name=_("Etiquetas"), through=Etiqueta) lugares = cms_models.Lugar.objects.filter(etiquetas__name__in=['pueb']) Throws an error: HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Anybody could help me please ? Thanks in advance. -
Need help on NGINX DJANGO for Oversized Response data
we have one endpoint where it is downloading 50 MB of data and recently data size went up to 60 MB, so application is not able to download this data, but it is fine working with 50 MB. Do we need to change any Nginx configuration to handle such kind of requests ? apiVersion: v1 kind: ConfigMap metadata: name: nginx-conf data: nginx.conf: | upstream app { server 127.0.0.1:9000 max_fails=0; } server { listen 80; server_name ___MY_DOMAIN_NAME___; charset utf-8; gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; client_max_body_size 100M; client_body_buffer_size 100M; client_body_temp_path /tmp/client_body_temp/ 1 2; proxy_ignore_client_abort on; include uwsgi_params; location / { uwsgi_pass app; uwsgi_read_timeout 600; } } -
JsonResponse Error is not showing as messages
I am building a BlogApp and I am trying to show JsonResponse errors as messages in browser to user ( like a popup ). But Json Response error is not showing, No error are showing in terminal and no errors in browser console. When user dislike the post and tries to like then the error will show. views.py def post_like(request, post_id): post = get_object_or_404(Post, pk=post_id) post_id = request.GET.get('post_id') data['message'] = "You cannote Like" if request.GET.get('submit') == 'like': if request.user in post.likes.all(): return JsonResponse({'action': 'dislike'}) else: return JsonResponse(data) else: return redirect('app1:home') post_detail.html <div class="message-container"> </div> <script> // Function only for showing errors. function show_error_message(question_id) { $.ajax({ url: "{% url 'post_like' data.id %}", datatype: 'json', data: { post_id: post_id }, success: function(json) { $('.message-container').html('') $('.message-container').html( 'You Cannot Vote' ); } }) } </script> <script> // Function for Like post document.addEventListener('DOMContentLoaded', function () { window.addEventListener('load', function () { $('.Likeblogpost').submit(function (e) { e.preventDefault(); let thisElement = $(this) $.ajax({ url: "{% url 'post_like' data.id %}", data: { 'submit': 'like', }, dataType: 'json', method: 'get', async: false, success: function (response) { if (response.action == 'dislike') { html(`<button name='submit' type='submit' value="accept">Unliked</button>`) } } }) }) }) }) </script> Json Response error message is still not showing. Any … -
The partition key must be defined on delete queries in django-cassandra-engine
from django.utils import timezone from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel class RequestResponse(DjangoCassandraModel): id = columns.UUID(primary_key=True, default=uuid.uuid4) sel_no = columns.Text(index=True) transaction_type = columns.Text() created_at = columns.DateTime(default=timezone.now()) updated_at = columns.DateTime(default=timezone.now()) I am using django-cassandra-engine==1.6.1. When I am trying to delete my all data from this model then these errors occurred. My command line: RequestResponse.objects.all().count() >> 10123 RequestResponse.objects.all().delete() Then these errors occurred. 996 partition_keys = set(x.db_field_name for x in self.model._partition_keys.values()) 997 if partition_keys - set(c.field for c in self._where): --> 998 raise QueryException("The partition key must be defined on delete queries") 999 1000 dq = DeleteStatement( QueryException: The partition key must be defined on delete queries -
Control access to a page in UpdateView
Hello!! I want to control that only the superuser and for example the teacher, can access a page inherited from UpdateView and redirect others to the /404 page. My class in views.py : class Edit_news(UpdateView): model = News form_class = edit_NewsForm template_name = "profile/Edit_news.html" URL of class in urls.py : from django.urls import path from .views import Edit_news urlpatterns = [ path("edit-news/<pk>", Edit_news.as_view()), ] Thanks for your help... -
Add an eye icon on the password_change_form.html Django admin
I want to override the password_change_form.html Django admin form, most specifically by adding an eye icon on the password section. The eye icon hides and shows the password. My steps were to first extend the template by creating this file templates/registration/password_change_form.html , but I don't exactly know how to override the inputs. Below is how my form looks : The form looks different than the default django one because I changed it's boostraping. How can I go about this? -
Django : KeyError: "Got KeyError when attempting to get a value for field `channel` on serializer ``
model class Metric(models.Model): date = models.DateField() channel = models.CharField(max_length=50) country = models.CharField(max_length=10) os = models.CharField(max_length=10) impressions = models.IntegerField() clicks = models.IntegerField() def __str__(self): return "{} - {}".format(self.date, self.channel) My view class MetricViewSet(viewsets.ModelViewSet): serializer_class = MetricSerializer queryset = Metric.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = MetricFilter My serializer class MetricSerializer(serializers.ModelSerializer): class Meta: model = Metric fields = '__all__' I need to group by one or more columns: date, channel, country, operating system and serialize it. Can someone help me with how I can do it? select channel, country, sum(impressions) as impressions, sum(clicks) as clicks from sample dataset where date < '2017-06-01' group by channel, country order by clicks desc; channel | country | impressions | clicks ------------------+---------+-------------+-------- adcolony | US | 532608 | 13089 apple_search_ads | US | 369993 | 11457 vungle | GB | 266470 | 9430 vungle | US | 266976 | 7937 My view lass MetricViewSet(viewsets.ModelViewSet): serializer_class = MetricSerializer queryset = Metric.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = MetricFilter def get_queryset(self): sort_by_dict = {'asc': '', 'desc': '-'} queryset = Metric.objects.all() group_by = self.request.query_params.get('group_by', None) # grouping the queryset if group_by is not None: queryset = queryset.values(group_by).annotate(dcount=Count(group_by))#.order_by() return queryset I am getting the following error KeyError: "Got KeyError when attempting to … -
Django Crispy Forms does not display the border of a certain field
I am using bootstrap and crispy forms to style my website. But a border around all my username fields dont get displayed. Like shown here (I cut off some parts). It is confusing to me, as all other fields get displayed properly: My Code (Form / HTML / View) looks like: class LWRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = LWUser fields = ['username', 'email', 'password1', 'password2'] . ... <form method="POST"> {% csrf_token %} <fieldset class="form-group"> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-dark" type="submit">{% trans "Register" %}</button> </div> </form> . ... def get(self, request): form = LWRegisterForm() context = {'form': form} return render(request, 'users/register.html', context) In order to fix it I tried in the HTML to use {% crispy update_form %} and {{ update_form.username|as_crispy_field }} instead of my code. Both still displayed it without a border. I also tried swapping around the order of things that get displayed with {{ update_form.email|as_crispy_field }} {{ update_form.username|as_crispy_field }} but still the username field was without a border. I tried reinstalling django-crispy-forms via pip unistall. Did not work. Now I am out of ideas. What could it be? -
How mass update data on django db table?
I need often parse big xml file and insert and update data to db table. How I can do it fast without delete data from database. Now I delete all data before parse and insert all data after. But it way broke all foreign keys. for category in self.root.findall('.//categories/category'): try: cat_id = category.get('id') cat = CategoryModel( id=cat_id, name=category.text, picture=category.get('picture') ) categories[cat_id] = cat CategoryModel.objects.all().delete() CategoryModel.objects.bulk_create(categories.values(), batch_size=50000) Next my code generation. I use bulk_update: all_categories = CategoryModel.objects.all() created_categories = [str(cat[0]) for cat in all_categories.values_list('id')] new_cats = [] update_cats = [] for category in self.root.findall('.//categories/category'): try: cat_id = category.get('id') cat = CategoryModel( id=cat_id, name=category.text, picture=category.get('picture') ) categories[cat_id] = cat if cat_id in created_categories: update_cats.append(cat) else: new_cats.append(cat) CategoryModel.objects.bulk_create(new_cats, batch_size=50000) all_categories.bulk_update(update_cats, fields=['name', 'picture'], batch_size=1000) It code work. But may be you know better way? -
Django LDAPS TLS started failing with error SERVER_DOWN
Today we had the pleasure of LDAPS failing in a Django application. Our Pip requirements includes: python-ldap==3.3.1 django-auth-ldap==3.0.0 Our Django settings file includes: AUTH_LDAP_SERVER_URI = "ldaps://ldaps.server.net.au:636" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0, ldap.OPT_NETWORK_TIMEOUT: 5.0, ldap.OPT_TIMEOUT: 5.0, } The vague error we're seeing is: Caught LDAPError while authenticating sighmon: SERVER_DOWN({'result': -1, 'desc': "Can't contact LDAP server", 'errno': 115, 'ctrls': [], 'info': '(unknown error code)'},) It had been working nicely for ~2 years prior to today. We tried pinning django-auth-ldap to various older versions, but all failed in the same way. -
AttributeError: 'datetime.datetime' object has no attribute 'save' - While saving time
I am building a BlogApp and I am trying to save time when the post was liked. Than I create a field of like_time so i can save the time while liking the post BUT When I save the time of like post then it is showing AttributeError: 'datetime.datetime' object has no attribute 'save' models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) date_post_added = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField(User,related_name='like ',blank=True) like_time = models.DateTimeField(auto_now=True) views.py def like_post(request,blogpost_id): blogpost = get_object_or_404(BlogPost, pk=blogpost_id) if request.GET.get('submit') == 'like_post': blogpost.like.add(request.user) blogpost.like_time.save() else: redirect('home') Like is successfuly adding BUT time is not saving and showing error. I also tried by adding :- from django.utils import timezone blogpost .like_time.save(timezone.now()) BUT It showed me same error. Than i tried :- import datetime timestamp = datetime.datetime.now() blogpost.like_time.save(timestamp) It also showed same error. Any help would be much Appreciated. Thank You in Advance. -
uploded image not saved in media folder
settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / "static"] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, "media/") MEDIA_URL = '../media/images/' urls.py if settings.DEBUG: # Use static() to add url mapping to serve static files during development (only) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py profile_image = models.ImageField(upload_to="../media/images") file path: -main_project /app #django app /media/images #media folder inside image folder /main #django main app /static/css #static folder for js,css,images,fonts /templates #html templates I have also tried other way but still, my image is not uploaded in media folder -
Printing pdf on network printer using python
I am currently working on application that generates pdf file and i am trying to send it to network printer. I am using reportlab to create pdf and docker and docker-compose to run app. I can't send the pdf file to the printer. Does anyone knows how to print pdf on network printer? -
Dataframe.ixmax on timezone-signed datetime data
I extracted some datetime data from my django app: data = list(MyModel.object.values_list("date1", "date2")) # >>> [ ( None, datetime.datetime(2020, 4, 9, 15, 43, 59, 433515, tzinfo=<UTC>) ), ( datetime.datetime(2020, 4, 9, 15, 44, 27, 328075, tzinfo=<UTC>), datetime.datetime(2020, 4, 9, 15, 44, 27, 328075, tzinfo=<UTC>), ) ] I input this in a dataframe: df = pd.DataFrame(data, columns=["date1", "date2"]) and I want to know for each row which date column is the highest so I use the idxmax function on axis=1: result = df.idxmax(axis=1) However I get this error: TypeError: reduction operation 'argmax' not allowed for this dtype My column types are datetimes so they argmax should work on them. df.dtypes # >>> # date1 datetime64[ns, UTC] # date2 datetime64[ns, UTC] # dtype: object Am I missing something? -
How secure image url in Django Rest Framework? [closed]
I'm building an API that stores some pictures from different users. I want to build a system, where only the user(who add a picture) and admin can view the picture. Any ideas on how to make it? As a result, I want to get something like this: https://office.kentonfinance.com/api/clients/60f984637c3cc260ea471526/documents/uccppuzhganfp0e2m94nrgvnv.png https://office.kentonfinance.com/api/clients/ code for user_id /documents/ picture name P.S. Searching in Google and in StackOverflow didn't give the result. -
Efficiently creating object from user inputted data in django
I am creating a web app where users will enter some details regarding a patient, an algorithm will then process these and generate some treatment recommendations. My question is how to both best design my models and then how best for the algorithm to access the user inputted data. These are my current models for capturing the user inputted data. The Diagnosis, Problem, CurrentMed and PastMed models all have flexible number of entries (the user can dynamically add rows to the entry form) which is why I do not have a single larger Patient model: models.py class Patient(TimeStampedModel): # get a unique id for each patient patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) name = models.CharField("Patient Name", max_length=255) age = models.IntegerField("Age", default=0) class Sex(models.TextChoices): MALE = "male", "Male" FEMALE = "female", "Female" UNSPECIFIED = "unspecified", "Unspecified" sex = models.CharField( "Sex", max_length=20, choices=Sex.choices, default=Sex.UNSPECIFIED) creator = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) class Diagnosis(TimeStampedModel): DIAG_CHOICES = [ (‘cancer’, ‘Cancer’), (‘influenza’, ‘Influenza’), ('unspecified', 'Unspecified'),] diag_name = models.CharField( "diag", max_length=200, choices=DIAG_CHOICES, default="unspecified") patient = models.ForeignKey(Patient, on_delete=models.CASCADE) class Problem(TimeStampedModel): PROB_CHOICES = [ (‘pain’, ‘Pain’), (‘wheeze’, ‘Wheeze’), ('unspecified', 'Unspecified'),] prob_name = models.CharField( "prob", max_length=200, choices=PROB_CHOICES, default="unspecified") patient = models.ForeignKey(Patient, on_delete=models.CASCADE) class Med(TimeStampedModel): MED_CHOICES = [ (‘Antibiotics’, ( (‘penicillin’, … -
Can not call Django view function via ajax function
viwes.py def post_upload(request, resolution, format, size): print(resolution) print(format) print(size) return render(request, 'upload .html') urls.py path(r'^post_upload/$', views.post_upload, name='post_upload') give.js: $(".btn").bind('click', function(){ console.log('download button clicked'); var resolution = $(this).closest("tr").find(".resolution").text(); var format = $(this).closest("tr").find(".format").text(); var size = $(this).closest("tr").find(".size").text(); var csrf_token = $("input[name='csrfmiddlewaretoken']").val(); console.log(resolution,format,size, csrf_token); $.ajaxSetup({ headers: { 'X-CSRFToken': csrf_token } }); $.ajax({ type: 'POST', url : "{% url 'post_upload' %}", data: { resolution: resolution, format: format, size: size, }, dataType:"html", success: function(data, status, xhr){ //do something with your data } }); return false; }); html file: {% csrf_token %} <button type="button" name="url" value="{{ request.GET.url }}" type="submit" id="download" class="btn btn-success" >Download</button> </form> <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/bootstrap.bundle.min.js'%} "></script> <script src="{% static 'js/plugin.js' %}"></script> <!-- sidebar --> <script src="{% static 'js/jquery.mCustomScrollbar.concat.min.js' %}"></script> <script src="{% static 'js/custom.js' %}"></script> <script src="https:cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script> <script src="{% static 'js/give.js' %}"></script> -
Django: fetching data from database. "WaitForSingleObject()" is taking 96% of execution time. Any Solution?
I'm using Django and trying to fetch data from PostgreSQL database. The table contains 2000 records and the request is taking 4-15 seconds. Upon profiling I saw that "WaitForSingleObject()" is taking most of the time. any solutions? -
VS Code and Django: Exception has occurred: ImportError
I'd like to automate some daily thinks on my job and struggle with this problem at the moment. System Versions: Python 3.9.6// VS Code: 1.59.1// Django: 1.6.0 I tried to create my first site and followed this tutorial: https://code.visualstudio.com/docs/python/tutorial-django I can run the server in the terminal with "python manage.py runserver". But when I try to run with debugger launch profile (the green arrow) the ImportError Msg occur. "Exception has occurred: ImportError Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" The manage.py consists of a def main() method with a try/except block: def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'web_projct.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) I don't know why but I couln't find the "execute_from_command_line".py in die django.core.managment directory. I set a lot of system variable for the pythonpath so I would not think that this is the erroer cause. Do I have explained my problem understandable? Is there somebody with … -
Cannot insert the value NULL into column 'id', table 'XXX'; column does not allow nulls
I have the below model: class Loan(models.Model): id = models.BigAutoField(primary_key=True) date = models.DateField(default=timezone.now) description = models.TextField(max_length=255) When I try to save date and description I get the above error below is my admin.py file: @admin.register(Loan) class LoanAdmin(admin.ModelAdmin): pass How can I solve this? -
Django. Foreign key
I have 2 tables: Side and AdditionalCost now AdditionalCost has the following foreign key field: side = models.ForeignKey(Side, on_delete=models.CASCADE, related_name='costs') I want to have another foreign key field in AdditionalCosts: number_of_additional_installations = models.ForeignKey(Side, on_delete=models.CASCADE, related_name="number_of_additional_installations") The Side model has the following field: number_of_additional_installations = models.IntegerField(null=True, blank=True, db_column='number_of_additional_installations', verbose_name='Количество доп монтажей') But I get the following error: ERRORS: <class 'kinetics.apps.address_program.admin.AdditionalCostInline'>: (admin.E202) 'address_program.AdditionalCost' has more than one ForeignKey to 'address_program.Side'. address_program.AdditionalCost.number_of_additional_installations: (fields.E302) Reverse accessor for 'AdditionalCost.number_of_additional_installations' clashes with field name 'Side.number_of_additional_installations'. HINT: Rename field 'Side.number_of_additional_installations', or add/change a related_name argument to the definition for field 'AdditionalCost.number_of_additional_installations'. address_program.AdditionalCost.number_of_additional_installations: (fields.E303) Reverse query name for 'AdditionalCost.number_of_additional_installations' clashes with field name 'Side.number_of_additional_installations'. HINT: Rename field 'Side.number_of_additional_installations', or add/change a related_name argument to the definition for field 'AdditionalCost.number_of_additional_installations'. I cannot figure out why this happened because I see that code has these lines: buyer_org = models.ForeignKey("acl.Organization", on_delete=models.SET_NULL, null=True, blank=True, related_name='buyer_costs') client_org = models.ForeignKey("acl.Organization", on_delete=models.SET_NULL, null=True, blank=True, related_name='client_costs') that are obviously two foreign fields that relate to columns of one model. If you need full code of the models let me know, it is quite large but I can add it if you need. Thank you p.s. If I rename the related_name of number_of_additional_installations, i still get the … -
How to upload a django app in docker container to AWS ECS
I have built a django application in docker container and I want to upload it Amazon ECS but I don't know how to go about it. Does anyone have a tutorial they can point me to -
DJANGO Python how to save data to database(mysql) and generate qrcode in another page using the data that save to database
DJANGO Python how to save data to database and generate QR code in another page using the data that save to database -
How to delete many to many relation objects in Django model
I have a model Post having many to many relation images. When a post is deleted, I would like all associated images to be also deleted. class Post(models.Model): images = models.ManyToManyField(Image, blank = True, related_name = 'posts') Are there something like models cascade options or I have to do something else? -
How to call app name when calling a one to one model in django?
This is my apps: user students university Now, how to use same names for two model ? for instance each student and university have profile model. At first when i do "Class Profile" under student It gets a new table named student_profile now in students app i can user student_profile = user.request.profile But how to do the same for university ? The table gets created like univerity_profile But how to use on views ? university_profile = user.request.profile How to use the app name when calling user.request.profile ?