Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to dynamically set value for a field in django
I'm building dynamic sorting of django query.I added additional column to sort on, like so: class MyModel(models.Model): order_column = models.IntegerField() class Meta: ordering = ('order_column',) and now need to update its value accordingly on every change / sort action. Right now I do it the following way: def some(self): my_query = MyModel.objects.all() my_list = list(my_query) pop_index = 4 insert_index = 2 obj = my_list[pop_index] my_list.insert(insert_index, obj) for i, item in enumerate(my_list): item.order_column = i item.save() It works, but I don't like the save in for-loop. I know that to update query one can call query.update, so I tried: my_query.update(order_column=lambda x: images_list.index(x)) But it doesn't work. Is there a way to achieve this in a single expression like update? -
How can I change django admin template?
I've written a blog website with Django and now I want to change the Django adminstrator themplate.. -
Form fields not appearing in add pages of django admin page
within my admin.py, I register a few models, and within those registered models, I define a few fields, such as a search field. The fields show up in the 'change' section of the model, but they do not appear in the 'add' section of the model admin page. Overall what I am trying to accomplish is to have a filter on the add page of my model AuthGroupFilePermissions, such that when a user is adding an auth group file permission, they don't have to look through a long list of filepatterns (over 1000, so it's extremely unfriendly). The key is actually Filepattern_id and it is a foreign key to another model. I have tried overriding the formfield_for_foreingkey method, as well as using filter_vertical and filter_horizontal @admin.register(models.AuthGroupFilePermissions) class AuthGroupFilePermissions(admin.ModelAdmin): list_filter = ('group', ) search_fields = ['file_pattern__filename_pattern'] filter_vertical = ('file_pattern',) def formfield_for_foreignkey(self, db_field, request, **kwargs): print2(kwargs) if db_field.name == 'file_pattern': kwargs['queryset'] = models.CentralFeedInfo.objects.filter(filename_pattern__icontains='') return super().formfield_for_foreignkey(db_field, request=request, **kwargs) class Media: js = ('/static/admin/js/filepattern_search.js',) So really I am having two issues. One, the fields that I am adding to modelAdmin are not showing up in the model admin, and two, I am not sure how to add a filter to the add page, similar … -
Environment variables are not being read in django/docker environment
I am running a dockerized django app and would like to pass my AWS credentials into my settings.py. So I set my environment variables in my .bash_profile and then in settings.py I do: os.getenv[AWS_ACCESS_KEY_ID]. I also tried os.environ[...]. When I enter my shell for debugging I get: /usr/local/lib/python3.6/os.py in __getitem__(self, key) 667 except KeyError: 668 # raise KeyError with the original key value --> 669 raise KeyError(key) from None 670 return self.decodevalue(value) So i figure the environment variable is None, thus is not read. Is that a problem with docker/bash? I mean that it is not accessible? Or should it be? Or do I have to set it in my Dockerfile? If so, how? Any hint or help is very much appreciated! Thanks in advance! -
Limited usage of voucher code (maximum 3 times) without being bound to an user
I want to generate voucher codes with limited usage up to maximum 3 times without being bound to a user. views.py: class ApplyFormView(FormView): template_name = 'vouchers/apply.html' model = Voucher form_class = VoucherApplyForm def get_success_url(self): voucher = get_object_or_404(Voucher, pk=self.kwargs['voucher_id']) discount_value = voucher.value discount_type = voucher.get_type_display() messages.add_message(self.request, messages.INFO, "Congratulations! You've successfully redeemed %s" " %s off the selected item(s)." % ( discount_value, discount_type, )) return reverse('vouchers:apply', kwargs={'voucher_id': self.kwargs['voucher_id']}) def form_valid(self, form): self.code = self.cleaned_data['code'] form.apply_voucher() return super(ApplyFormView, self).form_valid(form) class VoucherDetailView(generic.DetailView): template_name = 'vouchers/detail.html' model = Voucher def get_context_data(self, **kwargs): context = super(VoucherDetailView, self).get_context_data(**kwargs) context['redemption_form'] = VoucherApplyForm(initial={'voucher':self.object}) return context def redeem(request, voucher_id): voucher = get_object_or_404(Voucher, pk=voucher_id) try: redeemed_voucher = voucher.redemption.get(pk=request.POST['voucher']) except (KeyError, Voucher.DoesNotExist): return render(request, 'vouchers/detail.html', { 'voucher': voucher, 'error_message': "Voucher is invalid.", }) else: redeemed_voucher.redemption += 1 redeemed_voucher.save() return HttpResponseRedirect(reverse('vouchers:apply', args=(voucher.id,))) urls.py: from django.urls import path from . import views app_name = 'vouchers' urlpatterns = [ path('<int:pk>/', views.VoucherDetailView.as_view(), name='detail'), path('<int:voucher_id>/apply/', views.ApplyFormView.as_view(), name='apply'), path('<int:voucher_id>/redeem/', views.redeem, name='redeem'), ] models.py: class Voucher(models.Model): code = models.CharField(max_length=30, unique=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() value = models.IntegerField(default=10) VOUCHER_TYPES = ((0, 'money-based discount, in RM,'), (1, 'percent')) type = models.SmallIntegerField(("Type"), choices=VOUCHER_TYPES, default=0) usage_limit = models.PositiveIntegerField(("Usage limit"), default=3) active = models.BooleanField() def __str__(self): return self.code @property def due_to_expire(self): now … -
Why am I getting 'function upper(bytea)' error in python 3?
Currently I am working to convert my py-2 project in py-3 & during this conversion I have faced below kind of error. Partner.objects.filter(name__iexact = name_kv).count() When I am running above query in py2 it working perfectly & getting output '0', means getting empty list. When I am running above query in py3 it showing below kind of error. django.db.utils.ProgrammingError: function upper(bytea) does not exist LINE 1: ...alse AND UPPER("partners_partner"."name"::text) = UPPER('\x4... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I have searched lot online & SO other questions but but not able to find any solution. I figured out that it must have been python version problem & I am getting above error when my ORM query does not have any records. -
Stripe subscription creates duplicate payment
I've created a stripe subscription using Django/Stripe SDK and since the software is in Europe it used the new SCA (Strong Customer Authentication). So first I attach the source to customers and then I try to subscribe them, it works but for certain customers I am seeing duplicated payments on Stripe control panel. I've contacted Stripe and their customer support recommended the following but I couldn't figure it out: I see what you mean when you say the customers are being charged more than once. The issue boils down to the API call requesting them to be added to a subscription is being sent more than once to Stripe from your server. To solve this on your end, you will need to make sure your system is sending a request only once. I would recommend checking your server to see where the requests are coming from. It may be an easy solve on that end once this is determined. @login_required def PaymentView(request): profile = Profile.objects.filter(user=request.user).first() try: address = profile.address.get(address_type="home") except: address = None user_membership = get_user_membership(request) try: selected_membership = get_selected_membership(request) except: return redirect(reverse("membership:select")) publishKey = settings.STRIPE_PUBLISHABLE_KEY if request.method == "POST": # try: source = request.POST.get('stripeSource', "") amend = request.POST.get('amend', '') … -
CVAT Installation on Kubernetes
Using v0.5.1 from the GitHub repo (https://github.com/opencv/cvat), I've pulled it down locally, built and tagged it, and pushed it up to a local docker registry. When I try to deploy it on a kubernetes instance from the registry I get the following error in the pod logs: Error: Format string '%(ENV_HOME)s/wait-for-it.sh db:5432 -t 0 -- bash -ic \\n"/usr/bin/python3 ~/manage.py migrate && \\n/usr/bin/python3 ~/manage.py collectstatic --no-input && \\nexec /usr/bin/python3 $HOME/manage.py runmodwsgi --log-to-terminal --port 8080 \\n--limit-request-body 1073741824 --log-level INFO --include-file ~/mod_wsgi.conf \\n%(ENV_DJANGO_MODWSGI_EXTRA_ARGS)s --locale %(ENV_LC_ALL)s"' for 'program:runserver.command' contains names ('ENV_DJANGO_MODWSGI_EXTRA_ARGS') which cannot be expanded. Available names: ENV_CUDA_SUPPORT, ENV_CVAT_PORT, ENV_CVAT_PORT_8080_TCP, ENV_CVAT_PORT_8080_TCP_ADDR, ENV_CVAT_PORT_8080_TCP_PORT, ENV_CVAT_PORT_8080_TCP_PROTO, ENV_CVAT_PORT_8443_TCP, ENV_CVAT_PORT_8443_TCP_ADDR, ENV_CVAT_PORT_8443_TCP_PORT, ENV_CVAT_PORT_8443_TCP_PROTO, ENV_CVAT_SERVICE_HOST, ENV_CVAT_SERVICE_PORT, ENV_CVAT_SERVICE_PORT_8080_TCP, ENV_CVAT_SERVICE_PORT_8443_TCP, ENV_DB2_PORT, ENV_DB2_PORT_50000_TCP, ENV_DB2_PORT_50000_TCP_ADDR, ENV_DB2_PORT_50000_TCP_PORT, ENV_DB2_PORT_50000_TCP_PROTO, ENV_DB2_PORT_55000_TCP, ENV_DB2_PORT_55000_TCP_ADDR, ENV_DB2_PORT_55000_TCP_PORT, ENV_DB2_PORT_55000_TCP_PROTO, ENV_DB2_PORT_60006_TCP, ENV_DB2_PORT_60006_TCP_ADDR, ENV_DB2_PORT_60006_TCP_PORT, ENV_DB2_PORT_60006_TCP_PROTO, ENV_DB2_PORT_60007_TCP, ENV_DB2_PORT_60007_TCP_ADDR, ENV_DB2_PORT_60007_TCP_PORT, ENV_DB2_PORT_60007_TCP_PROTO, ENV_DB2_SERVICE_HOST, ENV_DB2_SERVICE_PORT, ENV_DB2_SERVICE_PORT_50000_TCP, ENV_DB2_SERVICE_PORT_55000_TCP, ENV_DB2_SERVICE_PORT_60006_TCP, ENV_DB2_SERVICE_PORT_60007_TCP, ENV_DEXTR_MODEL_DIR, ENV_DJANGO_CONFIGURATION, ENV_HOME, ENV_HOSTNAME, ENV_KUBERNETES_PORT, ENV_KUBERNETES_PORT_443_TCP, ENV_KUBERNETES_PORT_443_TCP_ADDR, ENV_KUBERNETES_PORT_443_TCP_PORT, ENV_KUBERNETES_PORT_443_TCP_PROTO, ENV_KUBERNETES_PORT_53_TCP, ENV_KUBERNETES_PORT_53_TCP_ADDR, ENV_KUBERNETES_PORT_53_TCP_PORT, ENV_KUBERNETES_PORT_53_TCP_PROTO, ENV_KUBERNETES_PORT_53_UDP, ENV_KUBERNETES_PORT_53_UDP_ADDR, ENV_KUBERNETES_PORT_53_UDP_PORT, ENV_KUBERNETES_PORT_53_UDP_PROTO, ENV_KUBERNETES_SERVICE_HOST, ENV_KUBERNETES_SERVICE_PORT, ENV_KUBERNETES_SERVICE_PORT_DNS, ENV_KUBERNETES_SERVICE_PORT_DNS_TCP, ENV_KUBERNETES_SERVICE_PORT_HTTPS, ENV_LANG, ENV_LC_ALL, ENV_NGINX_REVERSEPROXY_PORT, ENV_NGINX_REVERSEPROXY_PORT_8080_TCP, ENV_NGINX_REVERSEPROXY_PORT_8080_TCP_ADDR, ENV_NGINX_REVERSEPROXY_PORT_8080_TCP_PORT, ENV_NGINX_REVERSEPROXY_PORT_8080_TCP_PROTO, ENV_NGINX_REVERSEPROXY_PORT_8443_TCP, ENV_NGINX_REVERSEPROXY_PORT_8443_TCP_ADDR, ENV_NGINX_REVERSEPROXY_PORT_8443_TCP_PORT, ENV_NGINX_REVERSEPROXY_PORT_8443_TCP_PROTO, ENV_NGINX_REVERSEPROXY_SERVICE_HOST, ENV_NGINX_REVERSEPROXY_SERVICE_PORT, ENV_NGINX_REVERSEPROXY_SERVICE_PORT_8080_TCP, ENV_NGINX_REVERSEPROXY_SERVICE_PORT_8443_TCP, ENV_OPENVINO_TOOLKIT, ENV_PATH, ENV_REID_MODEL_DIR, ENV_TERM, ENV_TEST_UI_PORT, ENV_TEST_UI_PORT_8080_TCP, ENV_TEST_UI_PORT_8080_TCP_ADDR, ENV_TEST_UI_PORT_8080_TCP_PORT, ENV_TEST_UI_PORT_8080_TCP_PROTO, ENV_TEST_UI_SERVICE_HOST, ENV_TEST_UI_SERVICE_PORT, ENV_TEST_UI_SERVICE_PORT_8080_TCP, ENV_TF_ANNOTATION, ENV_TF_ANNOTATION_MODEL_PATH, ENV_TZ, ENV_USER, ENV_WITH_DEXTR, ENV_http_proxy, ENV_https_proxy, ENV_no_proxy, ENV_socks_proxy, group_name, here, host_node_name, process_num, program_name in section 'program:runserver' (file: 'supervisord.conf') For help, … -
How can I get the latest date using Django?
Hello I have this query : myObject.objects.filter(id=id, date=date).distinct('start').order_by('start') In my table I have only as fields : id, date, start and end. date, start and end are datetime type. The problem is that I would like to get in the end the latest date not a random date when I did the distinct on the field start. How can I do this ? Thank you very much ! -
Convert amount to word in Python In Indian Format
Would you help me to convert amount to word in Indian? Previously I was using num2words library but its is presenting wrong set of words while presenting 'lakhs' and 'crores'. For example: num2words(903614.55, lang='en-IN') Its printing 'nine hundred and three thousand, six hundred and fourteen point five five' But actual Indian Amount Presentation should be nine lakhs three thousand six hundred fourteen and five five paisa. Then, I tried the below code: def num2words(num): under_20 = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen'] tens = ['Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety'] above_100 = {100: 'Hundred',1000:'Thousand', 100000:'Lakhs', 10000000:'Crores'} if num < 20: return under_20[num] if num < 100: return tens[(int)(num/10)-2] + ('' if num%10==0 else ' ' + under_20[num%10]) # find the appropriate pivot - 'Million' in 3,603,550, or 'Thousand' in 603,550 pivot = max([key for key in above_100.keys() if key <= num]) return num2words((int)(num/pivot)) + ' ' + above_100[pivot] + ('' if num%pivot==0 else ' ' + num2words(num%pivot)) But now an error is coming TypeError : list indices must be integers or slices, not decimal.Decimal Any help is appreciatable Thank you -
ModuleNotFoundError: No module named 'companyname' with Django in docker container
I am getting an error about my module named "companyname" (fake name as to not reveal this project) despite the fact that it is in the folder with my Dockerfile. Here is my Dockerfile: FROM python:3.7 RUN apt-get update && apt-get upgrade -y && apt-get autoremove && apt-get autoclean RUN apt-get install -y \ libffi-dev \ libssl-dev \ default-libmysqlclient-dev \ libxml2-dev \ libxslt-dev \ libjpeg-dev \ libfreetype6-dev \ zlib1g-dev \ net-tools \ vim COPY * ./ RUN pip install -U pipenv RUN pipenv install --system EXPOSE 8000 STOPSIGNAL SIGINT ENTRYPOINT ["python3.7", "manage.py"] CMD ["runserver", "0.0.0.0:8000"] Here is my manage.py: #!/usr/bin/env python import os import sys import pymysql pymysql.install_as_MySQLdb() if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "companyname.settings.dev") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) And then there is a file that is located ./companyname/settings/dev.py from my Dockerfile - so ostensibly it should exist in my Docker image from the copy command. However when I run: docker run <image hash> I get: ModuleNotFoundError: No module named 'companyname' Why can't manage.py find my module? The same directory structure should be observed, correct? -
Make django-taggit-labels selectable on admin list view
I am using djang-taggit-labels for my project. The thing is that I can only select tags in the model edit view. I would like to make this list item editable on the main list view, so users do not have to click on the record but select tags on the list. I know how to make list_editable with model fields, which are not custom made, but I can't think off anything in this scenario. admin.py class YoutubeVideoAdmin(admin.ModelAdmin): form = YoutubeTagLabel model = YoutubeVideo list_display = ( 'admin_thumbnail', 'user', 'title', 'admin_url', 'published_at', 'description', # Categories are the tags. 'categories' ) list_editable = ['categories'] list_filter = ( ('user__user', admin.RelatedOnlyFieldListFilter), 'published_at', ('tags', custom_titled_filter('Category')), ) ordering = ('-published_at', ) search_fields = ('title', 'description', 'tags__name', ) readonly_fields = ('time_created', 'time_modified', 'user',) def admin_thumbnail(self, obj): if obj.thumbnail_url: return mark_safe('<img src="%s" height = "60"/>' % obj.thumbnail_url) else: return None def admin_url(self, obj): return mark_safe(f'<a href={obj.url} target="_blank"> {obj.url}</a>') def get_queryset(self, request): return super().get_queryset(request).prefetch_related('tags') # def categories populate tags def categories(self, obj): return u", ".join(o.name for o in obj.tags.all()) forms.py class YoutubeTagLabelsWidget(LabelWidget): tags = TagField(required=False, widget=LabelWidget) class YoutubeTagLabel(forms.ModelForm): tags = TagField(required=False, widget=YoutubeTagLabelsWidget) models.py class YoutubeVideo(TimeStampedModel): user = models.ForeignKey(YoutubeUser, on_delete=models.CASCADE) title = models.TextField() url = models.URLField() published_at = models.DateTimeField() description … -
Fixtures - Working with many to many intermediary models
I am training myself on Django and working on a movie blog and have issues with my fixtures that I scrap from themoviedb's api. I am wondering the right way to insert a ManyToMany with intermediary model. Here is my current state (removing the useless fields): class Movie(models.Model): tmdb_id = models.AutoField(primary_key=True) original_title = models.CharField(max_length=255) actors = models.ManyToManyField(Person, through='Actor', related_name="movie_cast") staffs = models.ManyToManyField(Person, through='Staff', related_name="movie_staff") class Actor(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) role = models.CharField("person's role in a movie", max_length=40) class Staff(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) department = models.CharField(max_length=30) job = models.CharField("person's job in a movie", max_length=40) What I am doing now is insert manualy a model.actor or model.staff like this to the fixture. {"model": "blog.actor", "fields": { "person": people['id'], "movie": movie['id'], "role": people['character'], } } I try to pass this dict or just the additional field to movie.actor field but it needs a int foreign key. Am I doing right or there is a better way to do this ? Thanks. -
View Model class in Django
I want to make a view model class in Django whose main purpose is only to display data in templates. like I have an auction model which has the following properties: class Auction(models.Model): seller = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) description = models.CharField(max_length=4000) edit_token = models.CharField(max_length=500) starting_price = models.DecimalField(max_length=30, max_digits=19, decimal_places=2) bid_price = models.DecimalField(max_length=30, max_digits=19, decimal_places=2, null=True) winner_id = models.IntegerField(null=True) end_date = models.DateTimeField(blank=True) status = models.CharField(max_length=15, choices=STATUS__CHOICES, default='Active') revision = models.IntegerField(default=1) Now I only want to show title, description, starting_price etc to view and main purpose of the view model is I want to change the value of starting_price based on user currency selection so I wanted to add some business logic during the transformation of Database Model class to Template Model class. Can I use form models or are there any other models I can use? -
Django Static image not displaying while using block
I am using Django, I am trying to display the image but I am getting the error. Invalid block tag on line 35: 'static', expected 'endblock'. Did you forget to register or load this tag? If I added my image directly on index.html page then the image is displaying but when I am using extends and block to display then I am getting the error. setting.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) home.html {% extends 'demo1/index.html' %} {% block content %} <img src="{% static 'images/web/landing-page.png' %}" alt="Landing Page"> { % endblock %} index.html {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title%}Home{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/style.css'%}" type="text/css"> </head> <body> {% block content %} {% endblock %} </body> </html> -
Django post_save signal not saving
I have a custom user class and some of my users require automatic username generation so naturally I felt a post or pre save signal would be best to generate what was needed. I opted for post_save because I wanted to append the pk to the generated username @receiver(post_save, sender=CustomUser) def make_username(sender, instance, created, using, **kwargs): if created: if instance.is_resident: instance.username = f'{instance.first_name[0]}{instance.last_name}{instance.id}' print(instance.username) # is correct # instance.save(), can do this but why do I need to? My issue is that the instance username is not being saved when the signal is called but everything prints out as expected as shown above. I cannot seem to figure out what is going on. I can save the instance again as I show in the comments, but I'm not understanding why it is needed. Can someone explain what my issue is here? Here is my CustomUser class if anyone needs to see it. class CustomUser(AbstractUser, SafeDeleteModel): objects = CustomUserManager() middle_name = models.CharField(max_length=100, null=True, blank=True) is_admin = models.BooleanField(default=False) is_corporate = models.BooleanField(default=False) is_onsite_manager = models.BooleanField(default=False) is_onsite_staff = models.BooleanField(default=False) is_maintenance = models.BooleanField(default=False) is_security = models.BooleanField(default=False) is_resident = models.BooleanField(default=False) # email = models.EmailField(unique=True) phone = models.CharField(max_length=100, validators=[validate_phone]) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) revoked_permissions = … -
How am I able to display my comment replies in Django
I have a system where users can make posts, and I have recently made it so users can reply to these comments. However, they won't display. Here is some code. VIEWS.PY @login_required(login_url='/mainapp/user_login/') def add_comment_to_post(request,pk): post = get_object_or_404(Post,pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user # add this line comment.save() return redirect('mainapp:post_detail',pk=post.pk) else: form = CommentForm() return render(request,'mainapp/comment_form.html',{'form':form}) def get_queryset(self): return Comment.objects.filter(created_date__lte=timezone.now()).order_by('-created_date') @login_required(login_url='/mainapp/user_login/') def add_reply_to_comment(request,pk): comment = get_object_or_404(Comment,pk=pk) if request.method == 'POST': form = ReplyForm(request.POST) if form.is_valid(): reply = form.save(commit=False) reply.comment = comment reply.author = request.user reply.save() return redirect('mainapp:post_detail',pk=comment.pk) else: form = ReplyForm() return render(request,'mainapp/reply_form.html',{'form':form}) def get_queryset(self): return Reply.objects.filter(created_date__lte=timezone.now()).order_by('-created_date') Those are my views for adding a comment to a post and a view to a post. The urls.py and models.py don't need changing, since this does work, and it shows in the admin interface and all, however I don't know how to display it in my HTML {% for comment in post.comments.all %} {% if user.is_authenticated or comment.approved_comment %} <p>Posted by: <strong>{{ comment.author }}</strong></p> <p id="comment-text">{{ comment.text|safe|linebreaks }}</p> <p>{{ comment.created_date|timesince }} ago</p><br> {% endif %} {% for reply in comment.replys %} <p>Posted by: <strong>{{ reply.author }}</strong></p> <p id="comment-text">{{ reply.text|safe|linebreaks }}</p> … -
create absolute url for static files in django
I am using django rest framework tinymce for tutorial upload website. This is working but when I am sending data by API, youtube URLs and image URLs are passing like this: <iframe src="//www.youtube.com/embed/IFncZA5k_1k" width="560" height="314" ></iframe> <img src="../../../../../media/uploads/yoga_m.jpg" alt="" /> I need absolute URLs in HTML response -
404 while trying to generate pdf with reportlab
I am trying to implement option to generate pdf file for download from views.py. For now I am using sample code provided in django docs however for some reason when I try to generate sample pdf I get 404 error with message that: The current path, stv/DRG_result, didn't match any of these. --bunch of urls paths-- The current path, stv/DRG_result, didn't match any of these. That seems logical, because I did not set any path in urls.py for that (since there was no info that it is needed). Should I set it? Can somebody tell me how to do it correctly, since I am very new to django. Or error is somewhere else? My relevant views.py part: import io from django.http import FileResponse from reportlab.pdfgen import canvas def DRG_result(request): buffer = io.BytesIO() p = canvas.Canvas(buffer) p.drawString(100, 100, "hello world.") p.showPage() p.save() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='hello.pdf') Code part for the button from the template which calls this function: <form action='DRG_result' method='GET'> {% csrf_token %} <button type="submit" >Generuoti PDF</button> </form> -
Redis, Django, Windows - "Warning: no config file specified, using the default config... 'redis-server /path/to/redis.conf'"
I'm trying to create a Celery task for my Django application. I do it according to this tutorial. According to him "Redis as the message broker" between Django Project and the Celery workers I found documentation on how to install redis on windows: https://redislabs.com/ebook/appendix-a/a-3-installing-on-windows/a-3-2-installing-redis-on-window/ According to him, I download project redis-2.4.5-win32-win64.zip from GitHub and unpacked from ZIP. Now I am trying to run the file redis-server by double clicking on the appropriate file. This launches a window that disappears for a second. When I trying to stop this window, I see this message. How can I resolve this error to properly start the redis server on windows? I will add that the redis.conf file is in the same position as you can see in the attached picture. I also can't use the redis-server /path/to/redis.conf command because the window redis-server closes automatically. Any help will be appreciated. -
Django Ajax form validation
I want to do ajax form validation to display errors. I looked at many examples, but some are old and do not work, while others I do not understand.Below is the code, please help with the implementation of ajax requests. views.py def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) # Set the chosen password new_user.set_password(user_form.cleaned_data['password']) # Save the User object new_user.save() return HttpResponse('IZI') else: print(user_form.errors) user_form = UserRegistrationForm() # errors = user_form.errors data = {'user_form': user_form, 'errors': user_form.errors} return render(request, 'registration.html', data) # return HttpResponse(simplejson.dumps(errors)) else: user_form = UserRegistrationForm() return render(request, 'registration.html', {'user_form': user_form}) models.py class TestUser(AbstractUser): phone = PhoneNumberField(null=False, blank=False, unique=True) class Meta: db_table = '"fyzzys"."users"' forms.py class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) phone = PhoneNumberField(region='RU', required='true') email = forms.CharField(error_messages='') class Meta: model = TestUser fields = ('username', 'first_name', 'email', 'phone') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match.') return cd['password2'] -
Serialize data is not giving output as expected
I have 3 django models like this To keep record of orders class Orders(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, blank=True, null=True) total_amount = models.DecimalField(max_digits=10, decimal_places=2) which articles are in order like pizza etc class OrderArticle(models.Model): order = models.ForeignKey(Orders, on_delete=models.CASCADE) article = models.ForeignKey(Articles, on_delete=models.CASCADE) Article options of articles in order (like topping on pizza , now topping can be 4 or more types) class OrderArticleOptions(models.Model): article_option = models.ForeignKey(ArticlesOptions, on_delete=models.CASCADE) order_article = models.ForeignKey(OrderArticle, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) price = models.DecimalField(max_digits=10, decimal_places=2) To keep track of this multipul type of Article options I made this table . So example will be . Customer purchased a pizza with 2 toppings , 1st topping quantiity is 1 and 2nd topping quantity is 3 . to get this use case using Django Rest framework I am doing this My serilizer class OrderArticleOptionSerilizer(serializers.ModelSerializer): order_article = OrderArticleSerilizer(required=False, read_only=True) article_option=ListCategoriesSerializer(required=False, read_only=True) class Meta: model = OrderArticleOptions fields = '__all__' and my view to show it is @permission_classes([AllowAny]) class OrderedArticles(APIView): def get(self, request, restid): orders = OrderArticleOptions.objects.all() orderserlizer = OrderArticleOptionSerilizer(orders, many=True) return Response(success_response({'orders': orderserlizer.data}, "Restaurant with this all data."), status=status.HTTP_200_OK) Issue Now issue is when I add 2 type of toppings to a single article in order it creates 2 orders … -
django listing all debts of customers
I'm using the django-rest framework. I have a list called customers. (customers) and I have a table where I add the debts of the customer. I want to make a separate inquiry screen and list the debts of all customers. api / debtlist form a customer can have more than one debt record. therefore, I want to show the total debt, total received and remaining debt amounts of each customer in a single line. How can I do this? -
I want to add target="_blank" to Django's template html
I want to add target="_blank" to Django's template html,but I cannot understand how to do it. My html is like {% block meta_title %}AAA{% endblock %} and when I click this AAA button,my ideal is to be able to open new tab of AAA page. But I cannot understand how I should add target="_blank". -
Access the model through a foreign key
I have an Author object, and a Product object with a foreign key on the Author. How can I get all the products of the current author?