Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model field automatically incremented, but not according IDs
I am a beginner with Django and I have been searching around this but not reaching a satisfactory solution. Let's say I would like to create a Model to identify a given chair of a table located in a given room of a house, and also its height (of the chair). Consider then records like the following: House Room Table Chair Chair Height (cm) White House Kitchen 1 1 75 White House Kitchen 2 1 55 White House Kitchen 2 2 65 Buckingham Palace Main State Room 1 1 70 Buckingham Palace Main State Room 1 2 70 The compound primary key should include House, Room, Table and Chair. The model I have created does not allow me to increment the integer value of the Chair, once the House, Room and Table are introduced. Is there a way to do that in the models.py file? I do not want to allow the user to introduce any number for the chair field, but to introduce the corresponding following one according to the house, room and table already introduced (There should not be, for example, a 3rd chair without existing the 1st and the 2nd ones). I have been searching the AutoField … -
social-auth-app-django Login for a Django Project not working
I am trying to add Facebook login for my Django Project, but I keep getting: Facebook has detected djangosociallogin isn't using a secure connection to transfer information. and Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. Here is the steps for what I did: 1: pip install social-auth-app-django 2: Add the social_django to your INSTALLED_APPS:'social_django', 3: Update the MIDDLEWARE_CLASSES by adding the SocialAuthExceptionMiddleware to the end of it:'social_django.middleware.SocialAuthExceptionMiddleware', 4: update the context_processors inside TEMPLATE: 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', 5: Add the AUTHENTICATION_BACKENDS in your settings.py file: AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.github.GithubOAuth2', 'django.contrib.auth.backends.ModelBackend', ) 6: Update the urls.py add the social-auth-app-django URLs: path('oauth/', include('social_django.urls', namespace='social')), 7: Added App ID and App Secret in the settings 8: In the developers facebook added Platform and add a website. For the Site URL put http://localhost:8000 and then in the App Domains put just localhost 9: Here is the login Template <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> <small class="text-muted ml-2"> <a … -
Django Stripe Payment: Invalid card object: must be a dictionary or a non-empty string
When I try to send a payment to stripe I get an error message: "Invalid card object: must be a dictionary or a non-empty string." The payment is for a set amount of 5 Euros. I am using the credit card number 4242 4242 4242 4242 to test the payment. I can see the 'Post' parameters to stripe are all correct apart from the 'stripe_id'. I have been trying to see what is wrong with 'stripe_id' but I am at a loss. Can anyone help me find what is wrong with my code? checkout.html: {% extends "base.html" %} {% load static from staticfiles %} {% load bootstrap_tags %} {% block head_js %} <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script type="text/javascript" src=""> //<![CDATA[ Stripe.publishableKey = '{{ publishable }}'; // ]]> </script> <script type="text/javascript" src="{% static 'js/stripe.js' %}"></script> {% endblock %} {% block content %} <form action="{% url 'checkout' %}" method="post" id="payment-form" class="col-md-6 col-md-offset-3"> <legend>Payment Details</legend> <div id="credit-card-errors" style="display: none;"> <div class="alert-message block-message error" id="stripe-error-message"></div> </div> <div class="form-group col-md-6"> {{ payment_form|as_bootstrap }} </div> {% csrf_token %} <div class="form-group col-md-12"> <input class=" btn btn-primary" id="submit_payment_btn" name="commit" type="submit" value="Submit Payment of 5 Euros"> </div> </form> {% endblock %} forms.py: from django import forms class MakePaymentForm(forms.Form): print("MakePaymentForm...") MONTH_CHOICES … -
django how can i get the request before the main urls.py
in django i got urlpatterns = [ path("something/", include("something.urls")), path("something2/", include("something2.urls")), ] i want to see details about the request before they come to "urlpatterns" i want to get the request object to see the ip everytime in all the urls and not metter when he want to go even if he go to "http://mywebsite.com/blablabla" i want to see the request and be able to send him back status 400 if i dont like this ip also i want to send all the requests to a statistic.py and analyze all the request to see stuff like if they got cookie and see the META of the request how can i achieve this? -
different extend from different applications
I'm trying to create one template for all apps, but with different base (related to app). i'm using django_hosts: hosts.py: from django_hosts import patterns, host host_patterns = patterns('', host(r'app1', 'app1.urls', name = 'app1'), host(r'(app2|application2)','app2.urls', name = 'app2'), ) tree: templates/document.html app1/templates/app1/base.html app2/templates/app2/base.html templates/document.html: {% extends base %} And the idea is: when I go to http://app1.example.com/document/ i will see templates/document.html extended with app1/templates/app1/base.html, and if I go to http://app2.example.com/document/ or http://application2.example.com/document/ extended with app2/templates/app2/base.html generally it works if I use in app1/views.py: (...) context={ 'base' : 'app1/base.html' } return render(request,'document.html', context) app2/views.py: (...) context={ 'base' : 'app2/base.html' } return render(request,'document.html', context) But I want to remove context 'base' from every views' def . I can't use app1/context_processors.py and app2/context_processors.py, because it would override themselves, because context_processors are global not app local. There's an idea: #main/contexts.py from django.core.urlresolvers import resolve def appname(request): return {'appname': resolve(request.path).app_name} but i don't have urls.py with includes, because i have hosts definition.... -
Letting Users Delete their own accounts in Django
In the Django 2.2 docs , it states the following : "is_active " is a Boolean. Designates whether this user account should be considered active. We recommend that you set this flag to False instead of deleting accounts; that way, if your applications have any foreign keys to users, the foreign keys won’t break. My question is this, If I had a website, and I gave my users the ability to delete their own accounts by following this practice, wouldn't my database be filled with non-active accounts once my website gains a bit of traffic? What would be the best method to letting users ( without staff or super user status ) on your website delete their own accounts properly in Django 2.2 ? Thank you in Advance for any Help -
ValueError: not enough values to unpack while running unit tests Django ModelViewSet
Am testing an endpoint that retrieves data using a ModelViewSet, and am passing a param via a URL to it to get data but am getting this error when I run the unit tests: for key, value in query: ValueError: not enough values to unpack (expected 2, got 1) This is how I have structured my tests , plus some dummy data for testing : class TemplateData: """Template Mock data.""" step_get_data = { "param": "step" } block_get_data = { "param": "block" } get_no_data = { "param_": "block" } class TemplateViewTests(TestCase, TemplateData): """Template Tests (Block & Step).""" def setUp(self): """ Initialize client, Step and Block id and data created. """ self.client = APIClient() self.block_id = 0 self.step_id = 0 self.create_block_step_data() def create_block_step_data(self): """Create ProcessVersion, Step, & Block mock data.""" self.process_version = ProcessVersion.objects.create( tag="TESTING_TAG", is_process_template=False, status="IN EDITING", attr_map="TESTING_ATTR", loan_options=None ) self.step = Step.objects.create( version=self.process_version, is_process_template=True, title="TESTING", help_text="TESTING", order=1, slug="slug", can_be_duplicated=False, max_duplicated_number=2, ) self.step_id = self.step.pk self.block_id = Block.objects.create( step=self.step, is_process_template=True, title="TESTING", information_text="This is testing " "information", order=1, depending_field="depending_field", visibility_value="visibility_value", slug="slug", can_be_duplicated=False, max_duplicated_number=2, ).pk self.process_version_1 = ProcessVersion.objects.create( tag="TESTING_TAG", is_process_template=False, status="IN EDITING", attr_map="TESTING_ATTR", loan_options=None ) self.step_1 = Step.objects.create( version=self.process_version_1, is_process_template=True, title="TESTING", help_text="TESTING", order=1, slug="slug", can_be_duplicated=False, max_duplicated_number=2, ) self.block_1 = Block.objects.create( step=self.step, is_process_template=True, title="TESTING", information_text="This … -
reactjs django admin page not found
I have project with react and django after running commande npm run build and change django static fiels settings to: 'DIRS': [os.path.join(BASE_DIR, 'frontend/build')], but after build up the project I can't access to django administration "http://localhost:8000/admin/" how can I solve this probleme -
Javascript parse URL as parameter for $.getJSON
I'm trying to parse an URL as paramter together with multiple others in my frontend to send a JSON request to my Django backend, but I receive the well known 404 error - not found. Django urls.py path: path("updateAssignment/<iD>/<body>/<deadline>/<user>/<url>/<game>/<aK>/<seoTitle>/<payment>/<wordCount>/<category>/<state>/", Dashboard.update_assignment, name="updateAssignment") Javascript $.getJSON Request function updateAssignment(assignmentId){ const assignmentUpdateEndpoint = "/updateAssignment/"; let body = encodeURIComponent(document.getElementById("Assignment-Body"+assignmentId).value); let deadline = encodeURIComponent(document.getElementById("Assignment-Deadline"+assignmentId).value); let user = encodeURIComponent(document.getElementById("Assignment-User"+assignmentId).value); let url = encodeURIComponent(document.getElementById("Assignment-URL"+assignmentId).value); let game = encodeURIComponent(document.getElementById("Assignment-Game"+assignmentId).value); let additionalKeywords = encodeURIComponent(document.getElementById("Assignment-Additional-Keywords"+assignmentId).value); let seoTitle = encodeURIComponent(document.getElementById("Assignment-SEOtitle"+assignmentId).value); let payment = encodeURIComponent(document.getElementById("Assignment-Payment"+assignmentId).value); let wordCount = encodeURIComponent(document.getElementById("Assignment-WordCount"+assignmentId).value); let category = encodeURIComponent(document.getElementById("Assignment-Category"+assignmentId).value); let state = encodeURIComponent(document.getElementById("Assignment-State"+assignmentId).value); assignmentId = encodeURIComponent(assignmentId); let reqUrl = assignmentUpdateEndpoint + assignmentId + "/" + body + "/" + deadline +"/" + user + "/" + url + "/" + game + "/" + additionalKeywords + "/" + seoTitle + "/" + payment + "/" + wordCount + "/" + category + "/" + state + "/"; $.getJSON(reqUrl).done((response) => { }); I have already tried encoding it via various methods but it just would not work. Help would be great. -
Django: Reverse for 'image_upload' with no arguments not found. 1 pattern(s) tried: ['image_upload/(?P<user_post>[0-9]+)$']
I'm trying to pass primary key as URL argument from CreatePost to UploadImage view but I'm constantly getting an error even if I see primary key in URL. I'm new to Django, so please help me :) views.py class CreatePost(CreateView): model=shopModels.UserPost template_name='shop/create_post.html' fields='__all__' def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['category'].widget.attrs['class'] = 'form-control' form.fields['category'].widget.attrs['oninvalid']="this.setCustomValidity('Ovo polje je obavezno!')" return form def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('login') return super(CreatePost, self).dispatch(request, *args, **kwargs) def get_success_url(self): return reverse('image_upload',kwargs={'user_post':self.object.id}) class UploadImage(CreateView): model=shopModels.Image template_name='shop/images_upload.html' fields='__all__' def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return reverse('login') return super(UploadImage, self).dispatch(request, *args, **kwargs) urls.py ... path('create_post/',views.CreatePost.as_view(),name="create_post"), path('image_upload/<int:user_post>',views.UploadImage.as_view(),name="image_upload"), ... models.py class UserPost(models.Model): id = models.AutoField(primary_key=True) user=models.ForeignKey(Account,on_delete=models.CASCADE) title=models.CharField(max_length=255) text=models.TextField(null=True) category=models.ForeignKey(Category,null=True,on_delete=models.SET_NULL) is_used=models.BooleanField(default=False) price=models.IntegerField(default=0) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return self.title + ' | ' + str(self.user) def get_absolute_url(self,*args,**kwargs): return reverse('image_upload', kwargs={'user_post':self.id}) class Image(models.Model): id = models.AutoField(primary_key=True) user_post=models.ForeignKey(UserPost,default=None, on_delete=models.CASCADE) image=models.ImageField(null=True,blank=True,upload_to='images/') def __str__(self): return self.user_post.title def get_absolute_url(self): return reverse('index') -
how do I make toast messages work together
I'm working on a toast message setup where when if multiple of them are in bound they're not visible except the one in the front (so maybe a margin of 15px would help) and display them on the bottom-corner of the screen(fixed) doesn't change position when scrolling and make them disappear after 3 secs one by one. How do I go about solving this with javascript? Thnx for any help. {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <div class="color-green"> <div class="color-white"> <div class="icon-success"> <i class="fas fa-check icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'info' %} <div class="color-blue"> <div class="color-white"> <div class="icon-info"> <i class="fas fa-info icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'warning' %} <div class="color-orange"> <div class="color-white"> <div class="icon-warning"> <i class="fas fa-exclamation-circle icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'error' %} <div class="color-red"> <div class="color-white"> <div class="icon-cross"> <i class="fas fa-times icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% endif %} {% endfor %} {% endif %} .color-green{ bottom: 0; position: absolute; background-color: #40ff00; box-shadow: 4px 4px 16px 0 rgba(0, 0, 0, 0.05); margin-bottom: 10px; margin-left: … -
How to edit Django models
Let's say that I have some data on my model and that I want to edit it, how can I do that without deleting the model or recreating a new one like I would do it on the admin panel? -
Saving python datetime value to a mySQL timestamp with timezone field
I am baffled. I assign to a Django model field as follows: listing.modify_date = datetime.now() where the field is defined as: listing_modify_date = models.DateTimeField(default=datetime.now, blank=True) Printing out the assigned value... print("modify_date=" + str(listing.modify_date)) I get: modify_date=2020-12-18 21:35:09.178392 But the mySQL table is not updated. However: non-"timestamp with timezone" fields in the row are updated; The following query in pgAdmin updates modify_date: update public.listings_listing set listing_modify_date = '2020-12-01 15:00:01' I have run out of things to try. Help appreciated. -
How to render all fields in m2m with a through model?
How could I manage to render something similar to this picture (https://i.imgur.com/3LPGbys.png), where I have my toppings as checkboxes and the amount as a normal input field. E.g. Lets say I have these models (this example is completely fictional) #models.py class Order(models.Model): pizza = models.ForeignKey(Pizza) toppings = models.ManyToManyField(Topping,through='QuantityTopping') class QuantityTopping(models.Model): order = models.ForeignKey(Order) topping = models.ForeignKey(Topping) quantity = models.IntegerField(default=0) class Topping(models.Model): topping = models.CharField(max_length=200) I tried several things, including: Attempt 1. Problem: it just renders the toppings, but not the quantity in any way. Not good, unfortunately. #forms.py class OrderForm(ModelForm): class Meta: model = Order fields = ['pizza', 'toppings'] Attempt 2: I tried to make a separate form only for toppings (my through model). Problem: It managed to all topping as checkboxes (yay!) but only 1 input field. Bummer. #forms.py class ToppingsForm(ModelForm): class Meta: model = QuantityTopping fields = ['topping', 'quantity'] widgets = {'topping':forms.CheckboxSelectMultiple,} Any ideas? thanks in advance! -
Django Exception Value: invalid filter error:
I am trying to display a division result in float. So I just arrived to this conclusion that a filter could be helpful, as below: in views.py: from django import template register = template.Library() @register.filter def div(value, div): return round((value / div) * 5, 2) in template: {% for post in Posts %} {{ post.likes|div:post.total_like }} {% endfor %} where value=post.likes and div=post.total_like but it gives the something like importing error: Invalid filter: 'div' I also tried to put div function/filter in a different file like mfilteter.py and import it in template like {% load mfilteter %} but didn't work! -
How can i add order detail to paypal smart button checkout
Hi i am building an ecommerce website with django and i was looking for a way to pass order details to the merchant account. I have tried this createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '30.11', }, description: 'this is a description', }] }); }, this method worked but i can only pass strings. I have tried to pass lists but it didn't work createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '30.11', }, description: [{ order: "dress5", price: "30" }] }] }); }, any recommendations on what i should do? -
Python, Django: Alternative to a raw-sql-query
Good evening, I would like to ask, if there's a different method to a raw sql query to update items by a certain condition inside my views.py? For example, I know I could do an insert query like this: models.py class Person(models.Model): name = models.CharField() age = models.IntegerField() value = models.IntegerField() views.py def something(request): ... qs = Person(name="John Doe", age=34, value=10) qs.save() ... Is there a similiar method for updating all "Persons" if they fit a certain condition? ... qs = Person("UPDATE Person SET value=5 WHERE age < 30") # or something like this qs.save() ... Thanks for all your help and advice and a great weekend to all of you! -
Custom threaded django comments - django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I am using django 3.1x and I'm following the example here to create a threaded comment app for my project. The article instructs to add the following lines to the __init__.py file so that django can use these hooks to lookup the altered models and forms and to overrides the default set. Here is the content of __init__.py: from models import MPTTComment from forms import MPTTCommentForm def get_model(): return MPTTComment def get_form(): return MPTTCommentForm The error message makes sense, because we appear to be importing objects that have not yet been created ... However, the author of the article states that it works - and none of the comments (granted, they are a year old) seem to be complaining of this issue. Am I missing something, or has the internals (loading sequence of django) changed? How do I fix this? -
Reverse for 'operation_info' with keyword arguments '{'id_operation': ''}' not found
I had this problem while trying to pass arguments through the template this is my urls.py path('Operation/Info/<id_operation>',views.operation_info,name='operation_info'), and this is my template {% for o in operation_list %} <tr><td scope="row">{{ o.nom_operation }}</td><td>{{ o.date_prevu }}</td><td><a href="{% url 'operation_info' id_operation=c.id %}"><i class="fa fa-info" style="color:green;font-size:33px;"></i></a></td></tr> {% endfor %} this is my view : def caravane_info(request,id_caravane): connected = request.user.is_authenticated if connected: U_ID = request.user.id F = Membre.objects.get(userr_id=U_ID) bureau_level = F.Grade_bureau caravane = Caravane.objects.get(id=id_caravane) return render(request,'Bureau/operation_info.html',locals()) -
django html template not loading from generic view from model
Introduction I am currently working on a small piece of the project to understand more about the Django ORM and to display individual objects. Using Generic views to keep the code clean. (I am somewhat new to Django Framework) Goal The goal of this piece is to show how many users have written an article. For example, I have total of 4 articles. I need to show how many articles written by each user. My console output: User Article Count testuser 2 testuser1 2 testuser2 0 my output on the HTML template: User Article Count testuser 0 testuser1 0 testuser2 0 Problem I am not understanding why my console output is correct, but my HTML template isn't showing the results. Please HELP me understand why it is doing this!!!!! If there is a similar post let me know! I have been looking everywhere for the answer, but I couldn't find it on the internet. Code views.py from django.views.generic import ListView from .models import Article from django.contrib.auth import get_user_model class ArticleListView(ListView): model = Article template_name = 'article_list.html' context_object_name='article_list' queryset=Article.objects.order_by('-date') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) users = get_user_model().objects.all() context["users"] = users articles = Article.objects.all() for user in users: article_count = articles.filter(author__exact=user).values('author').count() … -
Dajngo Model embed multiple Abstract Models
Suppose I have an Order model for storing customers' orders on my site. There will be two address fields: shipping_address and billing_address. I could write it something like this: class Order(models.Model): order_number = models.CharField() time_created = models.DateTimeField() ... shipping_name = models.CharField() shipping_city = models.CharField() shipping_street = models.CharField() shipping_building = models.CharField() billing_name = models.CharField() billing_city = models.CharField() billing_street = models.CharField() billing_building = models.CharField() ... Then access fields by order.shipping_name and order.billing_name, but that is getting really cumbersome when every address needs to contain 15-20 fields. I tried One-to-One relationships, but code in other places of the application becomes very complicated. If there would be only one address field I could use an Abstract Model to make it a bit cleaner: class Address(models.Model): class Meta: abstract = True name = models.CharField() city = models.CharField() street = models.CharField() building = models.CharField() ... class Order(Address, models.Model): order_number = models.CharField() time_created = models.DateTimeField() But this way I can only have one set of address data and field names from the Address class would clash with fields from Order. Is there a way to inject or embed fields with given prefix in DB to given Model? I am looking for something similar to @Embedded decorator used … -
Django rest framework charfilter json
I have a filter in django rest charfilterinfilter(field_name= 'genres__name', lookup_expr= 'in').I have in the database is which two categories to approach I through Many To Many did ,But I have when filtrating two categories of this product there are two elements I need only one element views class CharFilterInFilter(filters.BaseInFilter, filters.CharFilter): pass class ShoppFilter(filters.FilterSet): price = filters.RangeFilter() genres = CharFilterInFilter(field_name='genres__name') title = SearchFilter() class Meta: model = smartphone fields = ['price','genres','title'] class MDShopListView(generics.ListAPIView): queryset = smartphone.objects.all() filter_backends = (DjangoFilterBackend,SearchFilter) search_fields = ['title'] filterset_class = ShoppFilter def get(self, request): queryset = self.filter_queryset(self.get_queryset()) serializer=MDShopListSerializer(queryset,many=True) return Response(serializer.data) models genres = models.ManyToManyField(Genre, verbose_name="жанры") class Genre(models.Model): [enter image description here][1] name = models.CharField("Имя", max_length=100) img json 1: https://i.stack.imgur.com/4WR6L.png -
How do I add 3 different licenses with 3 different prices in django Models
I have a product and I wanted to add three purchase options that depend on the license you buy. For example: class Product(models.Model): productname = models.CharField(max_length=200) license = models.???? There should be a multiselector here in order to select all three licenses when applicable. But how? discription = models.TextField() image = models.CharField(max_length=5000, null=True, blank=True) class License(models.Model): Here should be some kind of choice field that connects the price to the choice.... but how??? Help please. -
How to use Django channels to push newly created data to client side without reloading and not completely changing the existing normal view code
Hey guys I am quite new to django and django channels. I have a small doubt related to channels. For example, if I have a post model and I created a post, for the user to view the post, they need to either reload the page or we need to redirect them to the list page to view all the posts. What if I want to push the newly created post to the front end or to the client side without having them to reload the page? Can we use channels for that? And if we use channels for that purpose, do we need to rewrite all the codes we wrote in normal views or adding a snippet code like sending a signal when created and running an async function will do the trick? Is it difficult to implement? Thanks -
How add a custom SLA in Defect Dojo
I know that there are a option to define the default SLA days in Defect Dojo... But I have a especial finding that the SLA is diferent that my default SLA, is there option to custom de SLA to only one finding? For exemple: My SLA to High is 30 days, in default SLA in System Settings, but this Especial Finding is high with 60 days of SLA, can I change the SLA only this finding? Thanksss!!!