Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field 'id' expected a number but got 'The Complete JavaScript' when i try to create a course i get this error
Here is my course model. class Course(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL,\ related_name='courses_created', on_delete=models.CASCADE) subject = models.ForeignKey(Subject,related_name='courses', on_delete=models.CASCADE) title = models.CharField(max_length=200) pic = models.ImageField(upload_to="course_pictures") slug = models.SlugField(max_length=200, unique=True,blank=True) overview = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) enroll = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='enrollment',blank=True) class Module(models.Model): course = models.ForeignKey(Course, related_name='modules', \ on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(blank=True) order = OrderField(blank=True, for_fields=['course']) class Meta: ordering = ['course'] class Content(models.Model): module = models.ForeignKey(Module,related_name='contents', on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE,\ limit_choices_to={'model__in':('text', 'video','image','file')}) object_id = models.PositiveIntegerField() item = GenericForeignKey('content_type', 'object_id') order = OrderField(blank=True, for_fields=['module']) Here is my function base view for creating course, When i try making a post request to create a course django throws the except ValueError Field 'id' expected a number but got 'The Complete JavaScript'. I wonder where this error is coming from, can anyone be of help. def course_create(request,*args,**kwargs): id = kwargs.get('id') if request.method =="POST": subject = request.POST['title'] course = request.POST['title'] overview = request.POST['overview'] front_pic = request.POST['pic'] title = request.POST['title'] desc = request.FILES.get('description') owner = Account.objects.get(username=request.user.username) course,create = Course.objects.get_or_create(title=course, owner=owner, subject=subject) subject,create = Subject.objects.get_or_create(title=subject) module,create = Module.objects.get_or_create(course=course, description=desc, title=title, order=id) data = Course(owner=owner, title=course, subject=subject, pic=front_pic, desc=desc, overview=overview, order=id, module=module.id) data.save() return redirect('course:main') return render(request,'manage/module/formset.html') -
Setting an initial value in a Django Form
I have to setup an initial value in a form and somehow is not working, it is extremely strange as I have exactly the same code in another view, but in this case my approach is not working: views.py @login_required def add_lead(request): if request.method == 'POST': lead_form = LeadsForm(request.POST) if lead_form.is_valid(): lead_form.save() messages.success(request, 'You have successfully added a new lead') return HttpResponseRedirect(reverse('add_lead')) else: messages.error(request, 'Error updating your Form') else: user = {"agent":request.user} lead_form = LeadsForm(request.POST or None, initial = user) return render(request, 'account/add_lead.html', {'lead_form': lead_form} ) forms.py class LeadsForm(forms.ModelForm): class Meta: model = Leads fields = ('project_id','company','agent','point_of_contact','services','expected_licenses', 'expected_revenue','country', 'status', 'estimated_closing_date' ) widgets = {'estimated_closing_date': DateInput(), } Essentially, the agent is the logged user, so I'm passing request.user as a variable, but I have not succeeded, which is very strange because I have that same logic in another form Any help will be appreciated -
Django check if ManyToManyField has connection
I have the following model: class Party(models.Model): participants = models.ManyToManyField(User, related_name='participants') How can I check if a user is participating the party? I've tried many lookups, but none are working. I'd like to have something like this in my views.py: def get_queryset(self): qs = models.Party.objects.all() qs.filter(participants__in=self.request.user.pk) return qs -
Simple internal server error because running uwsgi keeps on deleting the .sock file
I'm trying to deploy my first django app by following these steps. The problem I have is that, for some reason, running uwsgi --emperor venv/vassals/ --uid www-data --gid www-data after activating my venv just seems to delete the .sock file in my root dir. I assume this is causing the problem because looking at the nginx logs at /var/log/nginx/error.log suggest so: 2021/10/11 22:09:57 [crit] 4281#4281: *6 connect() to unix:///var/www/dolphin/dolphin.sock failed (2: No such file or directory) while connecting to upstream, client: 81.102.82.13, server: example.com, request: "GET /favicon.ico HTTP/2.0", upstream: "uwsgi://unix:///var/www/dolphin/dolphin.sock:", host: "example.com", referrer: "https://example.com/ Here is my config file in /etc/nginx/sites-available (symlinked to sites-enabled): ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # the upstream component nginx needs to connect to upstream django { server unix:///var/www/dolphin/dolphin.sock; #server unix:/var/www/dolphin/dolphin.sock; } # configuration of the server server { listen 443 ssl; server_name example.com; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /var/www/dolphin/app/media; } location /static { alias /var/www/dolphin/app/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /var/www/dolphin/uwsgi_params; } } My dolphin_uwsgi.ini file: [uwsgi] # full path to Django project's root directory chdir = /var/www/dolphin/ # Django's wsgi file … -
Django - Installed Django in virtualenv but cannot import it on git-bash
I am installing Django on virtualenv using git-bash However, I cannot import it to python. I tried to run django also keep getting ImportError Any idea why? -
Django automatic remove user if is no verified in time
I have a flag in django is_verified and i override User to CreateUser now i want automatic remove from db user if flag > 10 min == False, but when True nothing do. I created something like this in class CreateUser but this didn't work. def remove_user_time(self): user = super().objects.get(email=self.email) register_time = user.date_joined ten_minutes_later = (register_time + timedelta(hours=0.16)) if ten_minutes_later == datetime.now(): if user.is_verified == False: user.delete() -
Trying to autoassign a django group to users created by AAD/SSO process
I've spent the past 4 hours looking through so many resources trying everything to solve this and nothing with success. The short is that I'm trying to add a default group to all new users created. Users are created the first time they authenticate via AAD/SSO, but when they come in, they have no Auths. I'd like to have them receive a default group when the SSO process creates the user (e.g. from the post-save receiver of the User object). I've looked through dozens of examples using something very similar to the below code. OK fine, the process runs, never generates any errors, and successfully creates the CustomUserProfile record, but the user never gets assigned the default group. 110% chance the group exists and the get finds the group (have done exercises to confirm this). What do I have wrong on this?? Why won't this process create the group assignment (or hit the error process to tell me what's going on here)? using django 3.2.8, Python 3.8.7 @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): try: if created: instance.groups.add(Group.objects.get(name='Basis - Standard Access')) CustomUserProfile.objects.create(user=instance).save() except Exception as err: print('Error creating basis user profile!') print(err) -
Include paramquery into django application
Any idea why pqgrid from paramquery is not working? I tried import local files or link online files and it does not matter still not working. I think it is a problem when I am loading files into django project, but I don't know why. Any help? Here it is HTML template: {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Django Girls</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <link href="https://unpkg.com/jquery-ui-pack@1.12.2/jquery-ui.css" rel="stylesheet" /> <link href="https://unpkg.com/jquery-ui-pack@1.12.2/jquery-ui.structure.css" rel="stylesheet" /> <link href="https://unpkg.com/jquery-ui-pack@1.12.2/jquery-ui.theme.css" rel="stylesheet" /> <script src="https://unpkg.com/jquery-ui-pack@1.12.2/jquery-ui.js"></script> <link href="https://unpkg.com/pqgrid@8.1.1/pqgrid.min.css" rel="stylesheet" /> <link href="https://unpkg.com/pqgrid@8.1.1/pqgrid.ui.min.css" rel="stylesheet" /> <link href="https://unpkg.com/pqgrid@8.1.1/themes/steelblue/pqgrid.css" rel="stylesheet" /> <script src="https://unpkg.com/pqgrid@8.1.1/pqgrid.min.js"></script> <script src="https://unpkg.com/pqgrid@8.1.1/localize/pq-localize-en.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script> <script src="https://unpkg.com/file-saver@2.0.1/dist/FileSaver.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <div class="page-header"> {% if user.is_authenticated %} <a href="{% url 'post_new' %}" class="top-menu"><span class="fa fa-plus" aria-hidden="true"></span></a> <a href="{% url 'post_draft_list' %}" class="top-menu"><span class="fa fa-edit"></span></a> <p class="top-menu">Hello {{ user.username }} <small>(<a href="{% url 'logout' %}">Log out</a>)</small></p> {% else %} <a href="{% url 'login' %}" class="top-menu"><span class="fa fa-lock"></span></a> {% endif %} <h1><a href="/">Django Girls Blog</a></h1> </div> <div class="content"> <div class="row"> <div class="col"> <div id="grid_json" style="margin:100px;"></div> {% block content %} {% endblock %} </div> </div> </div> </body> </html> Settings files: # Static files … -
Loading and parsing a local JSON-file
I have a fully working function for displaying external JSON data from an URL def object_api(request): url = 'https://ghibliapi.herokuapp.com/vehicles' response = requests.get(url) data = response.json() arr = [dic for dic in data ] context = { 'data': arr, } return render(request, 'output.html', context) Now I need to load a local file, e.g. example.txt filled with JSON-data. How do I load such a file? My current problem is the transformation of data to a proper "context"-variable. -
message_set of Django model
i'm new with Django and as I read the code, I don't understand the message_set attribute of Django model(called Room): def room(request, pk): room = Room.objects.get(id=pk) **room_messages = room.message_set.all()** participants = room.participants.all() portion of Models: class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) participants = models.ManyToManyField( User, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) -
django admin foreign key filter
I would like to pre-filter a foreign key field on my django admin page. Here is my models: class Modalite(TimeStampedModel): class Meta: verbose_name = _(u"Modalite") verbose_name_plural = _(u"Modalites") protocole = models.ForeignKey(Protocole, related_name='modalite_protocole', on_delete=models.PROTECT) code = models.CharField(max_length=50) station = models.ForeignKey(Station, related_name="modalite_station", on_delete=models.PROTECT, null=True, blank=True) class Protocole(TimeStampedModel): class Meta: verbose_name = _(u"Protocole") verbose_name_plural = _(u"Protocoles") code = models.CharField(max_length=50) repetition = models.IntegerField() stations = models.ManyToManyField(Station, related_name="protocole_station") file = models.FileField() class Station(TimeStampedModel): class Meta: verbose_name = _(u"Station") verbose_name_plural = _(u"Stations") nom = models.CharField(max_length=50) Thus a "modalite" I linked to a "protocole". A "protocole" can have multiple "station", but a "modalite" can only have one "station". I would like in the admin instance edition of "modalite", to select only "station" foreign key that are already linked to the associated "protocole". In other terms, if the model "station" contains the following instance [A,B,C]; and a "protocole" is linked to only [A,B]. I want to be able, within a "modalite" to choose only in [A,B]. I guess I could do it with "formfield_for_foreignkey", but I don't know how to refer to the specific instance. This is my admin.py so far: @admin.register(Modalite) class ModaliteAdmin(admin.ModelAdmin): # form = ModaliteAdminForm list_display = ('code', 'station', 'protocole') list_filter = ('code', 'station', 'protocole') … -
Django - Filter for objects with field that is bigger than limit value
I want to filter for objects whose id is bigger than one that I've specified. This is what I am looking for: const LIMIT_ID = 100 bigIdPeople = Person.objects.filter(id > LIMIT_ID) Is this possible and how should I do this? Thank you! -
Are Django ForeignKeys field accesses executed lazily?
Given the following model: class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) And given the following code: article_1 = Article.objects.get(...) #1 print(article_1.reporter) #2 When executing line #1, does a call get done to the Reporter table? Or is it done only when executing #2? -
Redirect shortcut is not working, not redirecting me on browser
I have a code like this def maca_create(request, pk): return redirect("maca:detail" pk=pk) The view of that page inside redirect is excecuting, but in the browser is not happening anything. Can someone help me please? -
I want to check request.user in profile.favourite and followUser.folpr if an object exists delete or add but check don't work only add and create work
I want to check request.user in profile.favourite and followUser.folpr if an object exists delete or add but check don't work only add and create work class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favourite = models.ManyToManyField( User, related_name='favouriteUser', default=None, blank=True) avatar = models.ImageField( upload_to=user_directory_path, default='users/avatar.png') bio = models.TextField(max_length=5500, blank=True) class followUser(models.Model): folPr = models.ForeignKey(Profile, related_name='followfp', on_delete=models.CASCADE, default=None, blank=True) follUser = models.ForeignKey(User, related_name='followidf', on_delete=models.CASCADE, default=None, blank=True) @ login_required def favourite_add_user(request, id): post = get_object_or_404(Profile, id=id) if post.favourite.filter(id=request.user.id).exists(): post.favourite.remove(request.user) followUser.objects.get(user=request.user,folPr=post ).delete() else: post.favourite.add(request.user) followUser.objects.create(follUser=request.user,folPr=post ).save() return HttpResponseRedirect(request.META['HTTP_REFERER']) -
Deserialize Nested Object in Django-Rest-Framework
Good day, I'm trying to do a PUT request that contains a nested-object and I can't get the province to update correctly. There didn't seem to be anything obvious in the django-rest-framework docs to help with this and I've investigated the solutions of a few other similar problems but none have helped (set many=false, change to ModelSerializer, specialized serializers, etc.). Everything else about the address will update correctly and return a 200 response (no errors in django logs either). Am I wrong to assume that django-rest-framework handles this all for me for free? Do I have to override the update and create methods within the serializer to validate and save the nested-object? I'm thinking it's because I have the province serializer set to read_only within the address serializer. However, if I remove the read_only modifier on the province serializer, it gives an error about the province already existing: { "province": { "province": [ "valid province with this province already exists." ] } } Which is behaviour I do not expect and don't know how to resolve. I am not trying to add or update the province. I just want to change the province code in the address.province field and I … -
Django include template tag using as nested - side effects?
does anyone know or have any experience about bad side effects of using nested include tags? (I mean including a template file which itself includes another template) For example: file x.html: {% include "z.html" %} file y.html: {% inclide "x.html" %} -
Set up my form( leave form) need to automate a few things
So i set up my app for LEAVE MANAGEMENT. I was Wondering however is there a way i can automate the days. For example if sick leave==5days, when the user selects sick leave, the system automatically tells them how many days they have. They can be able to take all days, less but not more than the assigned days. And when the user selects when they want to start their leave, then the end date is automatically filled excluding weekends. Thank you i know it is a lot but i will gladly appreciate some help. SICK = 'sick' CASUAL = 'casual' EMERGENCY = 'emergency' STUDY = 'study' MATERNITY = 'maternity' LEAVE_TYPE = ( (SICK, 'Sick Leave'), (CASUAL, 'Casual Leave'), (EMERGENCY, 'Emergency Leave'), (STUDY, 'Study Leave'), (MATERNITY, 'Maternity Leave'), ) class Leave(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default=1) startdate = models.DateField(verbose_name=_('Start Date'),help_text='leave start date is on ..',null=True,blank=False) enddate = models.DateField(verbose_name=_('End Date'),help_text='coming back on ...',null=True,blank=False) leavetype = models.CharField(choices=LEAVE_TYPE,max_length=25,default=SICK,null=True,blank=False) reason = models.CharField(verbose_name=_('Reason for Leave'),max_length=255,help_text='add additional information for leave',null=True,blank=True) defaultdays = models.PositiveIntegerField(verbose_name=_('Leave days per year counter'),default=DAYS,null=True,blank=True) status = models.CharField(max_length=12,default='pending') #pending,approved,rejected,cancelled is_approved = models.BooleanField(default=False) #hide updated = models.DateTimeField(auto_now=True, auto_now_add=False) created = models.DateTimeField(auto_now=False, auto_now_add=True) -
How do I relate two table to know which value is included in ManyToMany field in Django?
Hope that the title is not as confusing as I thought it would be. I currently have a table for PaymentsData: class PaymentsData(models.Model): match = models.CharField(max_length=30) amount = models.DecimalField(default = 0, max_digits = 5, decimal_places = 2) players = models.ManyToManyField(Profile, blank=True) playerspaid = models.ManyToManyField(Profile, related_name='paid', blank=True) datespent = models.DateField('Date Spent') def __str__(self): return self.match This field is used to create matches and include the number of players that played within players section and when they paid move them to playerspaid field. What I wanted to do is using a different table, I wanted to present all the players individually, and include the matches that they need to pay for (which we can know by fetching the players in PaymentsData above). So it should look something similar to this: class PlayersPaymentDetails(models.Model): player = models.OneToOneField(Profile, on_delete=models.CASCADE) matches = models.ManyToManyField(PaymentsData, blank=True) amountdue = models.DecimalField(default = 0, max_digits=5, decimal_places = 2) here in the matches, it should show all the matches that the player is selected in the players field within PaymentsData and the amountdue should show how much the player owes all together. I have tried customising the model using the save() method, however when the players gets unselected from the PaymentsData, it … -
Add to cart function not executing
My add to cart function was working, but I made some changes to the products model that weren't related to the cart. I only built a function to add defaults. Now my add to cart function doesn't work. I even added a print function at the beginning of the function and that is never printed. My view function works (to view the cart), but not adding. views.py in cart app: def add_to_cart(request, slug): print("add_to_cart pressed") request.session.set_expiry(100000000) try: the_id = request.session['cart_id'] except: #create cart id new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass product_variations = [] if request.method == 'POST': qty = request.POST['qty'] for item in request.POST: key = item val = request.POST[key] try: v = Variation.objects.get(product=product, category__iexact=key, title__iexact=val) product_variations.append(v) except: pass cart_item = CartItem.objects.create(cart=cart, product=product) if len(product_variations) > 0: cart_item.variations.add(*product_variations) cart_item.quantity = qty cart_item.save() print("cart item added") return HttpResponseRedirect(reverse("carts:cart")) return HttpResponseRedirect(reverse("carts:cart")) urls.py in cart app: app_name='carts' urlpatterns =[ path('cart/', views.view, name='cart'), path('cart/<id>/', views.remove_from_cart, name='remove_from_cart'), path('cart/<slug:slug>/', views.add_to_cart, name='add_to_cart'), ] models.py in cart app class Cart(models.Model): total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) def __str__(self): return "Cart id: %s" %(self.id) class … -
Receiving CORS cross policy error only after being deployed for longer than a day?
Recently, I've been running into the dreaded CORS no cross origin policy error between my react and django apps, and after redeploying my django app to heroku I don't receive the same error until a while later. I'm absolutely puzzled on why this is the case and really can't think of an explanation for why it stops working shortly after deploying. Here's my settings.py file in my django app: Relevant Code settings.py import django_heroku from pathlib import Path from corsheaders.defaults import default_headers import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # blank to allow all ALLOWED_HOSTS = [""] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'pc_algo', ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'rpa_django.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'rpa_django.wsgi.application' … -
Why does Stripe CLI testing fail with dj-stripe?
I am trying to verify that the URLs work for DJ Stripe with the Stripe CLI. Originally I was going to implement the view on my own but then I decided to go with DJ Stripe. In my original view the CLI works just file listening on my URL and running stripe trigger checkout.session.completed: ✗ stripe listen --forward-to localhost:80/webhook/subscriptions / ⡿ Checking for new versions... A newer version of the Stripe CLI is available, please update to: v1.7.4 ⢿ Getting ready... > Ready! Your webhook signing secret is whsec_flxws0UD9fzx16CMB5krTZdzy5LI63SE (^C to quit) 2021-10-11 14:29:56 --> payment_intent.created [evt_3JjUC8KxszORsacj0V7a7Kll] 2021-10-11 14:29:56 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_3JjUC8KxszORsacj0V7a7Kll] 2021-10-11 14:29:59 --> customer.created [evt_1JjUCBKxszORsacjAxsANDCu] 2021-10-11 14:29:59 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_1JjUCBKxszORsacjAxsANDCu] 2021-10-11 14:29:59 --> payment_intent.succeeded [evt_3JjUC8KxszORsacj0ZPYDcwj] 2021-10-11 14:29:59 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_3JjUC8KxszORsacj0ZPYDcwj] 2021-10-11 14:29:59 --> charge.succeeded [evt_3JjUC8KxszORsacj001d3jMs] 2021-10-11 14:30:00 --> checkout.session.completed [evt_1JjUCBKxszORsacjedLR1580] 2021-10-11 14:30:00 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_3JjUC8KxszORsacj001d3jMs] 2021-10-11 14:30:00 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_1JjUCBKxszORsacjedLR1580] My working non-dj-stripe code is as follows: @csrf_exempt def stripe_subscription_webhook_received(request): stripe.api_key = cmu.get_stripe_api_key() webhook_secret = request.headers['STRIPE_SIGNATURE'] payload = json.loads(request.body) try: event = stripe.Event.construct_from(payload, stripe.api_key) except ValueError as e: return HttpResponse(status=400) if event.type == 'checkout.session.completed': payment_intent = event.data.object print(payment_intent) elif event.type == 'invoice.paid': # bunch of events... # ... … -
Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name (help)
i get an Error django.urls.exceptions.NoReverseMatch: Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name. even though i got everything in the right plays, i will show you some of the code -
Do Django models have access to the request object?
I would like for the model to have a property method and return a value based on the request. Does Django have a global request object? Is is possible to pass in a parameter to the model? class Person(models.Model): first_name = models.CharField(max_length=30) @property def full_name(self): if request.name == 'Mario': # request object reference? return 'It is me Mario!' else: return self.first_name -
Django is not using proper id autoincrement number after migrating to Postgres DB
I migrated my Django database from Sqlite into Postgres, the data is properly set and tested when reading. The thing is that, when I try to add a new registry into the table, Django is using id number as 1 instead to be the last registry id plus one. That of course returns an error, something like this: IntegrityError at /admin/accounting/expense/add/ duplicate key value violates unique constraint "accounting_expense_pkey" DETAIL: Key (id)=(2) already exists. How can I make Django to use the proper id number when trying to save a registry?