Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I specify HTTP method in Django generic ListCreateAPIView?
ListCreateAPIView in Django includes HEAD and OPTIONS methods. How can I get rid of them? -
The current path, accounts/signUp/signUp, didn't match any of these
hello im facing an issue when trying to make a sign up page in django when i submit in the html form a user should be created in the database but its not happening and it shows this message "The current path, accounts/signUp/signUp, didn't match any of these" and this in the terminal "Not Found: /accounts/signUp/signUp" views.py: from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth # Create your views here. def signUp(request): if request.method=='post': first_name=request.POST['first_name'] last_name=request.POST['last_name'] username=request.POST['username'] password1=request.POST['password1'] rePassword=request.POST['repassword'] email=request.POST['email'] user = User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name) user.save(); else: return render(request,'signUp.html') signUp.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sign Up</title> </head> <body> <form action="signUp" method="post"> {% csrf_token%} <input type="text" name="first_name" placeholder="First Name"><br> <input type="text" name="last_name" placeholder="Last Name"><br> <input type="text" name="username" placeholder="Username"><br> <input type="email" name="email" placeholder="email"><br> <input type="password" name="password" placeholder="Password"><br> <input type="password" name="rePassword" placeholder="Confirm Password"><br> <input type="submit"> </form> </body> </html> -
CKeditor 4.0.0 - Unable to scroll on mobile when editor is present
I am developing a form on Django that uses djangocms-text-ckeditor 4.0.0. The page has a few fields, and then a CKEditor textarea field. When the page loads, I am able to scroll with a mouse wheel just fine. However when using a Mobile device to scroll using a touch screen, it won't scroll unless you touch the text box for CKEditor and swipe up and down. Touching anywhere outside that box does not allow you to scroll at all. I searched online, but didn't find anything that seemed to work to resolve this issue. -
how to add login with phone number wihile using django allauth package
I am using Django all auth package (google) how can I set up login with phone number feature to it? can someone please guide me -
Saving ModelForm progress values to session in Django
I have flow where users can create (model) forms. If form is valid, object gets saved and flow continues, but selection is in multiple pages. I need to keep current state of created object, which cannot be saved before it's completely valid. One thing I can do is to always pass things around those views in the ModelForm to make sure, that user never loses data, but I also wanna make sure, that if he leaves the flow and comes back, he doesn't lose data, that he already entered previously. That's why I decided I wanna save all the fields to session. Is this correct approach? How would you do this? Where would you put this session logic? What's best way of getting the fields from incomplete form to be saved? -
Django : on_delete=models.SET.NULL gives error
Why attribute in my model class where class Tour_Cart: tours=models.ForeignKey(Tours,on_delete=models.SET.NULL,blank=True,null=True) Throws error: AttributeError: 'function' object has no attribute 'NULL' Why so? Any help will be appreciated? -
Implement Java API in Django
I am working on a Django project where I have to implement a Java API, especially guacamole-common. Help would be very helpful -
How to solve MissingRate error in Django?
I want to convert currencies in my Django app. I created a model Customer. In customer model, there are two fields for that credit_limit and currency_choice. I am using django-money for conversion. But I get an error: MissingRate at /customer Rate GBP -> USD does not exist How can I solve it? views.py from djmoney.money import Money from djmoney.contrib.exchange.models import convert_money def customer(request): form_class = NewCustomerForm current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) company = userP[0].company if request.method == 'POST': form = NewCustomerForm(request.POST) if form.is_valid(): newCustomer = form.save() newCustomer.company = company selected_currency = newCustomer.currency_choice selected_limit = newCustomer.credit_limit value = Money(selected_limit, selected_currency) converted = convert_money(value, 'USD') print(converted) newCustomer.save() return redirect('user:customer_list') else: form = form_class() return render(request, 'customer.html', {'form': form}) models.py class Customer(models.Model): ... CURRENCIES = [ ('USD', 'USD'), ('EUR', 'EUR'), ('GBP', 'GBP'), ] ... credit_limit = models.FloatField(default=0) currency_choice = models.TextField(max_length=50, default='Select', choices=CURRENCIES) settings.py ... INSTALLED_APPS = [ ..., 'djmoney', ... ] ... EXCHANGE_BACKEND = 'djmoney.contrib.exchange.backends.FixerBackend' CURRENCIES = ('USD', 'EUR', 'GBP') OPEN_EXCHANGE_RATES_URL = 'https://openexchangerates.org/api/historical/2017-01-01.json?symbols=EUR,NOK,SEK,CZK,USD,GBP' FIXER_URL = 'http://data.fixer.io/api/2013-12-24?symbols=EUR,NOK,GBP,SEK,CZK,USD,GBP' traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/customer Django Version: 3.1.4 Python Version: 3.8.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'register', 'customer', 'financial_analysis', 'ocr', 'core', 'approvals', 'crispy_forms', 'ckeditor', 'rest_framework', 'requests', 'ckeditor_uploader', 'django_filters', 'activity_log', … -
ALLOWED_HOSTS when using Django behind Caddy reverse proxy
Using Django behind a Caddy reverse proxy leads to a lot of error notifications like the following: Invalid HTTP_HOST header: 'www.msftncsi.com'. You may need to add 'www.msftncsi.com' to ALLOWED_HOSTS. Isn't Caddy supposed to only pass on requests from my own domain to the Django app? The respective Caddyfile is: mydummyyapp.com { # Use 'route' to allow this ordering. Otherwise, 'file_server' would need to come last. route { # Redirects just to be nice. redir /login /accounts/login permanent # Serve static files directly. file_server /static/* { root /home/apps/mydummyapp } # Pass on everything else to django/daphne. reverse_proxy 127.0.0.1:8000 } log { output file /var/log/mydummyapp_access.log { roll_size 1gb roll_keep 5 roll_keep_for 168h } } } I would assume that requests that do not originate at mydummyyapp.com to not even reach the Django/daphne server running at 127.0.0.1:8000. Naive and wrong? -
Is there a way to put the paragraph on multiple lines in limited space?
i have this project: User should be able to add a comment in a box but the box is have max lenght of 250 characters. This is my snippet from Html: <div class="comment-box"> <div class="list-comments"> <span> Comments </span> <hr> {%for i in comments.all%} <div class="comment"> <p class="description"> {{i.description}} </p> <p> <i><b>{{i.user}}</b>, {{i.date}}</i> </p> </div> {%empty%} <p> There aren't comment here! </p> {%endfor%} </div> <div class="leave-comment"> <form action="{% url 'add_comment' item.id %}" method="POST"> {% csrf_token %} {{comment_form}} <input type="submit" value="Send comment" class="button"> </form> </div> Mine css .comment-box{ margin: auto; display: flex; flex-wrap: wrap; width: 60%; border: 1px groove rgb(133, 133, 219); border-radius: 5px; } .list-comments{ padding: 5px; flex-basis: 60%; overflow-y: scroll; height: 450px; width: 450px; } .leave-comment{ padding-top: 50px; font-size: 16px; margin-left: 10px; flex-basis: 30%; background-color: white; text-align: center; } .comment{ border: 1px groove rgb(133, 133, 219); border-radius: 5px; padding: 10px; background-color: white; } .description{ max-width: 320ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } And this is the result The problem is that the comment is displayed with ... and not entire comment. Is there a way to put the comment on multiple lines in limited space? -
How can I skip authentication in a Django APIRequestFactory call?
So essentially I want to make a request to a ViewSet without requiring to authenticate, does Django APIRequestFactory make this possible? This works: from django.test import TestCase from .views.SomeViewSet from rest_framework.test import APIRequestFactory class ViewSetsTest(TestCase): ... ... ... def test_db_instance_viewset(self): api_request = APIRequestFactory.patch("", HTTP_AUTHORIZATION="Bearer xyz123ppouu") detail_view = SomeViewSet.as_view({'patch': 'update'}) response = detail_view(api_request) self.assertEqual(response.status_code, 200) But the issue is, the bearer token is something that is generated 'somewhere far' every 24 hours. Hence, I want to skip authentication. Thank you in advance. -
If length of String > 33 then move to next line with same y axis coordinate in Reportlab PDF Django
Hey i have this type of code which helps me to build pdf from data render from database. But there is a problem if length of a string is too big then it overcross to other string like in billing head. Any Solution regarding this according to my code. This Pdf built through reportlab python in django. Image Attached. As u see Values in Charges Discription Overcross the coloumn of SAC section. I want to put half characters to next line if the length of Charges Discription is too big to avoid overcross. def sea_export_local_invoice_pdf(request, pk): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = ' filename="local_invoice.pdf"' c = canvas.Canvas(response) # _______________________ get object ___________________ lir_fed = SeaExLocalInvoiceReceivable.objects.get(pk=pk)c.setFont('Helvetica-Bold', 9) c.drawString(85, 548, 'Charges Description') c.line(201, 560, 201, 300) c.drawString(210, 548, 'SAC') c.line(237, 560, 237, 300) c.drawString(243, 548, 'Unit') c.line(268, 560, 268, 300) c.drawString(273, 548, 'Rate') c.line(296, 560, 296, 280) c.drawString(298, 548, 'Ex.Rate') c.line(332, 560, 332, 280) c.drawString(340, 548, 'Amount') c.line(381, 560, 381, 300) c.drawString(384, 548, 'IGST') c.line(407, 560, 407, 300) c.drawString(410, 548, 'CGST') c.line(437, 560, 437, 300) c.drawString(440, 548, 'SGST') c.line(467, 560, 467, 165) c.drawString(474, 548, 'Tax Amt') c.line(519, 560, 519, 280) c.drawString(533, 548, 'Total') c.line(25, 540, 575, 540) a = '07' # a = … -
"getattr(): attribute name must be string" in django rest framework
There is an error "getattr(): attribute name must be string",i don't know how to solve this, views.py class VideoViewset(ResponseViewMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): def post(self, request, *args, **kwargs): try: serializer = VideoSerializers(data=request.data) if not serializer.is_valid(): return self.jp_error_response('HTTP_400_BAD_REQUEST', self.error_msg_list(serializer.errors)) serializer.save() return self.jp_response(s_code='HTTP_201_CREATED', data={'video': serializer.data}) except Exception as e: print(e) return self.jp_error_response('HTTP_500_INTERNAL_SERVER_ERROR', 'EXCEPTION', [str(e), ]) serializers.py class VideoSerializers(serializers.ModelSerializer): class Meta: model = Video fields = ('video_type', 'relevance', 'difficulty', 'category', 'sub_category') models.py class Video(BaseModel, Timestamps, SoftDelete): relevance_difficulty_choices = ( ('low', 'Low'), ('medium', 'Medium'), ('high', 'High') ) video_type_choices = ( ('micro', 'Micro'), ('mini', 'Mini'), ('grand', 'Grand') ) create_date = models.DateTimeField(auto_now_add=True, null=True) video_type = models.CharField(max_length=50, choices=video_type_choices, null=False) relevance = models.CharField(max_length=50, choices=relevance_difficulty_choices, null=False) difficulty = models.CharField(max_length=50, choices=relevance_difficulty_choices, null=False) category = models.CharField(max_length=254, null=False, blank=False) sub_category = models.CharField(max_length=254, null=False, blank=False) created_by = models.ForeignKey(Employee, null=True, on_delete=models.CASCADE) contributer = models.CharField(max_length=254, null=False) file_url = models.CharField(max_length=254, null=True, blank=False) -
ValueError at /api/addorderitem badly formed hexadecimal UUID string in Django rest framework
I tried to create a random unique string in a charfield using uuid but it is giving me above error. My model is: from utils import create_new_ref_number class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True orderItem_ID = models.UUIDField(max_length=12, editable=False,default=str(uuid.uuid4())) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) total_item_price = models.PositiveIntegerField(blank=True,null=True,) -
Is it good way to write all js code in html page and include that html page in another html page insted of .js file?
I just want to know that is it a good idea to write all javascript code in an HTML(instead of writing in .js) file and that the HTML file will be included in another HTML file. I'm writing js code in an HTML file because I can access Django templates in an HTML file. Django templates are not accessible in pure JS files. -
Django Framworks: URL error? my tutor has no clue
Maybe you could help me with the following issue, I'm following a course and changing the code for my own project. Original code: https://github.com/ckz8780/boutique_ado_v1 My project: https://github.com/asforrest/Milestone-4-CarFix The issue is coming from this page: https://8000-brown-earwig-xhtc2sv5.ws-eu03.gitpod.io/subscriptions/ And has to do with this app: https://github.com/asforrest/Milestone-4-CarFix/tree/master/subscriptions Any idea? Thank you. -
how to use a redirect Mixin in CreateView django for Registration Form?
i have created my registration form with CreateView, can i use custom Mixins to restrict user reach a webpage? i am trying to restrict users when they are --> is_authenticated. these are my codes, as you can see i have created a custom Mixin but it doesn't work! Mixins.py class UserAthenticatedRedirectRegisterMixin(): def dispatch(self,request,*args,**kwargs): if self.reuqest.user.is_authenticated: return redirect("account:home") else: return super().dispatch(request, *args, **kwargs) Views.py class Register(UserAthenticatedRedirectLoginMixin,CreateView): form_class = SignupForm template_name = "account/register.html" def form_valid(self,form): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(self.request) mail_subject = "ایمیل فعال سازی حساب کاربری" message = render_to_string('account/activate_account.html',{ 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') # gereftane email user email = EmailMessage( mail_subject,message,to=[to_email] ) email.send() return HttpResponse('لینک فعال سازی به ایمیل شما ارسال شد. <a href="/login">ورود</a>') anyway to fix this problem? -
pushing into a declared list not working in jquery
I am trying to put id values into a list in jquery but I get an error saying that push is not a function. somehow it seems that my list is turned into an object. I am using django. It all worked but suddenly it stoped. why? <script> $(document).ready(function() { $("button").click(function() { var vals = []; console.log('cons1:',vals) console.log('cons1:',typeof(vals)) $.each($("input[name='checkb']:checked"),function(vals) { vals.push($(this).attr('id')); }); console.log('cons2:',vals) alert("values2: " + vals.join(", ")); }); }); </script> -
Show specific form-fields at specific places in the HTML template (Django)
I have a form with three fields field1,field2,field3 - in my template I want to show those fields at specific places, and not together. At best field1, field2 are "shown together" and then a bit further down, I need field3 to be shown. My HTML is right now <div class="content-section"> <div class="add-link-wrapper"> <legend class="border-bottom mb-4"> Add product </legend> <form method="POST"> {% csrf_token %} {{form|crispy}} <div class="form-group"> <button class="btn btn-outline-info" type="submit">Add</button> </div> </form> </div> </div> but {{form}} shows all three fields - I would like to have it a bit like <div class="content-section"> <div class="add-link-wrapper"> <legend class="border-bottom mb-4"> Tilføj produkt til tracking </legend> <form method="POST"> {% csrf_token %} {{form.field1 and form.field2 |crispy}} <!-- Show field1 and field 2 here --> <div class="form-group"> </div> </form> some more html code </div> {{form.field3|crispy}} <!-- Show field3 here --> <button class="btn btn-outline-info" type="submit">Add</button> </div> -
Show all possible error-messages for fields (Django)
In Django, say I have a User field and I want to change the "this user alread exist" error message. I know I can parse a dictionary in e.g forms.py like class MyForm(Form): . . . error_messages={"unique": ("Wups, enter a unique username")} but it requires I know the key/value pair, which might not always be obvious what the key is. Is there a way (in the Django documentation it seems pretty scattered) where these error-message key/value pairs are, or what is the most easy way to find those? -
referring to associated field in another model in Django
I want to create a table with buyer's name and the fruits that he bought based on that season. class Buyer(models.Model): name = models.CharField(max_length=10) season = models.ForeignKey(Season, on_delete=models.CASCADE) fruit = models.ManyToManyField(Fruit, through=‘Season’, related_name=‘seasonal_fruit’) class Fruit(models.Model): fruit_name = models.CharField(max_length=10) class Season(models.Model): season = models.CharField(max_length=10) fruit = models.ForeignKey(Fruit, on_delete=models.CASCADE) The above code throws the following error: app.Season: The model is used as an intermediate model by 'app.Buyer.fruit', but it does not have a foreign key to 'Buyer' or 'Fruit'. -
Why do I get "reverse accessor for 'model.user' clashes with reverse accessor for 'model.account' even though I set AUTH_USER_MODEL?
I've seen the same question posted a few times, and the answer is always.. did you set AUTH_USER_MODEL? Here is the snippet from my settings.py file. ## Accounts AUTH_USER_MODEL = 'accounts.Account' Here is the error message I am getting when I try to generate migrations for my new model. ERRORS: admin.LogEntry.user: (fields.E304) Reverse accessor for 'LogEntry.user' clashes with reverse accessor for 'LogEntry.account'. HINT: Add or change a related_name argument to the definition for 'LogEntry.user' or 'LogEntry.account'. logs.LogEntry.account: (fields.E304) Reverse accessor for 'LogEntry.account' clashes with reverse accessor for 'LogEntry.user'. HINT: Add or change a related_name argument to the definition for 'LogEntry.account' or 'LogEntry.user'. Here is the model that is causing the problem. class LogEntry(models.Model): log = models.ForeignKey(Log, on_delete=models.CASCADE) account = models.ForeignKey(Account, on_delete=models.SET_NULL, blank=True, null=True) entry = models.TextField() I'm developing on sqlite3, so I have tried destroying the sqlite file and emptying my migrations folders. I run the command again and get the same result. I know that I could define a related_name on the field, but I would rather address the underlying problem. It shouldn't class with LogEntry.user because I am not creating any association between those models directly... or am I? -
Date range filter doesn't work as expected
I made a custom filter by date range with a django-filter library. class AccountingStockBalanceFilter(filters.FilterSet): date = filters.DateFromToRangeFilter(method="filter_date") @staticmethod def filter_date(queryset, name, date_slice): queryset = queryset.filter( invoice_product__invoice__supplier_creation_date__range=( date_slice.start, date_slice.stop, ) ) return queryset but if I do request like this http://localhost/api/accounting/stock_balances/?date_after=2021-03-01&date_before=2021-04-20 then it won't return anything...Though if I do request like http://localhost/api/accounting/stock_balances/?date_after=2021-02-01&date_before=2021-04-20 (I have changed date_after from 2021-03-01 to 2021-02-01), then I'll get in some entries in response with only the date of 2021-02-11. Then I made this filtering with a built-in filter() function like this: class AccountingStockBalanceFilter(filters.FilterSet): date = filters.DateFromToRangeFilter(method="filter_date") @staticmethod def filter_date(queryset, name, date_slice): queryset = filter( lambda wp: date_slice.start < wp.invoice_product.invoice.supplier_creation_date < date_slice.stop if wp.invoice_product.invoice.supplier_creation_date else wp, queryset, ) ids = [wp.id for wp in queryset] queryset = ( WarehouseProduct.objects.prefetch_related( "invoice_product__invoice__order__serviceinvoice_set", "invoice_product__invoice__service_set", "invoice_product__invoice__order__invoice_set__invoiceproduct_set", "invoice_product__invoice__invoiceproduct_set", "invoice_product__invoice__order__serviceinvoice_set__service_set", "invoice_product__invoice__self_serial_number", "invoice_product__invoice__self_proforma_serial_number", ) .select_related( "nomenclature__category__unit_of_measure", "invoice_product__invoice__order", "invoice_product__invoice__supplier", "locator", ) .filter( ~Q(nomenclature__type=Nomenclature.Type.ASSEMBLY), locator__warehouse_id=1, quantity__gt=0, id__in=ids, ) ) return queryset And it works correctly returning me a response with dates like 2021-03-06 e.g. but it costs extra database queries and I got 18 queries instead of 9. What am I doing wrong with django's filter()? BTW here is my view: from warehouse_api.models import Product as WarehouseProduct class AccountingStockBalancesView(ListAPIView): """API endpoint that returns a list of … -
Django Rest Framework: Is it possible to allow users to get/post data via ajax but not directly via viewset url?
I'm learning web development since a few months, so the answer could be quite trivial: I also couldn't find anyone asking that before so it's probably a really stupid question, neither in the [drf official doc](https://www.django-rest-framework.org/api-guide/viewsets/). Most similar question I could find is [this](https://stackoverflow.com/questions/57328203/django-user-with-limited-permissions-can-see-all-default-models-in-rest-framewor), and I understood it but did not really help me. My problem is that I have a drf viewset very simple, like this, in views.py: from .serializers import MyModelSerializer from .model import MyModel from django.contrib.auth.decorators import login_required @method_decorator(login_required, name='dispatch') class MyViewSet(viewsets.ModelViewSet): serializer_class = MyModelSerializer queryset = MyModel.objects.all() My urls.py looks like this: from views import MyViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('myviewset', MyViewSet, basename='myviewset') urlpatterns = [ path('viewset/', include(router.urls)), # ... other paths ... ] Inside my javascript (jQuery) code I call this url, in some ajax requests: it performs well and that's wonderful. Unfortunately, users can do the same thing directly by going to /viewset/myviewset/ and this is a real problem to me. So, is it possible or am I simply using the wrong module to do this? In that case, what other module/objects could I use? Thank you very much. -
Django Password Reset timeout
Whenever I want to reset password, my browser goes timeout. I have the same EMAIL_HOST_USER and EMAIL_HOST_PASSWORD than in dev environment, yet it doens't work in Production. settings.py with open('/etc/config.json') as config_file: config = json.load(config_file) LOGIN_URL = 'login' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config.get('EMAIL_USER') EMAIL_HOST_PASSWORD = config.get('EMAIL_PASSWORD') config.json { "SECRET_KEY":"***", "EMAIL_USER":"***", "EMAIL_PASSWORD":"***" }