Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Make a GET Request to a URL that is advanced
So I have Chat Rooms and I have Messages. Then I have two urls: /messages and /rooms. And these display all your rooms and messages. Also a message can be assigned to a room. So in the Room API I have the messages assigned to that room. Let's say that the room is called 'Room1' and the messages are 'hey', 'yo' and 'wassup'. If I make a request to just /messages I will get all of the messages. Let's say that only two of the messages are assigned to 'Room1' and the other message is assigned to another room not named. I want a way to make a get request and only get those two messages assigned to 'Room1 with id = 3' (localhost:8000/rooms/3/messages) instead of: (localhost:8000/messages). This is an example of when I make a get request to /rooms/3/ { "id": 3, "name": "Room 1", "members": [ { "id": 1, "username": "william" }, { "id": 2, "username": "eric" }, { "id": 3, "username": "ryan" } ], "messages": [ { "id": 7, "content": "hej", "date": "2019-07-08", "sender": { "id": 1, "username": "william" } }, { "id": 8, "content": "yoyo", "date": "2019-07-08", "sender": { "id": 2, "username": "eric" } }, { … -
URL mapping not works as I want
Header section main-page By selecting 'About' from the main-page-options, /app1/about template is called, which is fine. However by selecting the Portfolio-drop-down items, I get an error. That is because the item is saved in mysite/app1/template folder and django is looking in the root of mysite. How can I map it? # Here is my mysite/app1/urls.py from django.urls import path from app1 import views urlpatterns = [ path('about/', views.about, name='about'), path('services/', views.services, name='services'), path('contact/', views.contact, name='contact'), path('portfolio1/', views.portfolio1, name='portfolio1'), ] # part of my views.py def portfolio1 (request): return render (request, 'portfolio1.html') 404 Error: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ [name='index'] app1/ ^static/(?P<path>.*)$ The current path, portfolio1.html, didn't match any of these. -
how to add fields dynamically with adding a new product to ManyToMany field
i'm trying create a Restaurant Order management system based on django when someone order some kinds of foods , it may order 3 Pizza with 2 sandwich , how to let the customer to define the quantities of each product , and then calculate with its prices class Restaurant(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Topping(models.Model): name = models.CharField(max_length=50) product_names = models.ManyToManyField(Restaurant, blank=True) quantity = models.PositiveIntegerField(default=1) #total price of orders , for one product for example : one pizza with one sandwich however they order more than one pizza and sandwich @property def total(self): return self.product_names.aggregate(Sum('price'))['price__sum'] i expected to provide a quantity field for each selected items : pizza : 3 , sandwich:2 , then calculate them (3*pizza price , 2*sandwich price) -
How to get an array with the counts of each field with the same parameter in Django in get_context_data?
I use a ListView for a template that displays all the Sensor in the database. Each Sensor can have more SensorViews and I'm trying to display in the same tempalte how many views each sensor has. The models are related to eachother by a field called "sensor_id". Any idea how I could do this in views.py? The line that works to an extent is the following context['number_of_sensor_views'] = SensorView.objects.filter(sensor_id = F('sensor_id')).count() However, this counts all SensorViews in the database and displays the same value for all entries. Any idea how I could count, store and display them individually? -
How to fix "dictionary update sequence element # 0 has length 104; 2 is required" error
I want to create a login page, when the username and password are incorrect there is this error "dictionary update sequence element # 0 has length ... is required". How to correct this error? forms.py class LoginForm(forms.Form): username = forms.CharField(max_length=250, required=False) password = forms.CharField(max_length=250, required=False) views.py class LoginView(View): template_name = 'login/index.html' form_class = LoginForm def get(self, request): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) next_var = request.GET.get('next') # redirect to url in next var else return to login home page return redirect('%s' % next_var) if next_var else redirect('%s' % settings.LOGIN_REDIRECT_URL) return render(request, self.template_name, {'form': form}) When the fields are not filled there is this error "dictionary update sequence element #0 has length 104; 2 is required" that appears. but when I log in and I go back to the login page to log in without anything filled in I'm reported that the fields are not filled -
ERRORS: book.Book.author: (fields.E300) book.Book.author: (fields.E307)
my English is poor , sorry this is my struct bookstore ---author(app1) ---book(app2) from django.db import models from author.models import Profile from django.contrib import admin class Book(models.Model): title = models.CharField(max_length = 150) page = models.IntegerField() price = models.IntegerField() author = models.ForeignKey( 'Profile', on_delete=models.CASCADE,) publish_date = models.DateField() class Meta(object): db_table = "book" class BookAdmin(admin.ModelAdmin): pass admin.site.register(Book, BookAdmin) mysql have some data , now I want to use them to show my web ,not to do that creat data in database thank you guys!!! I have a question My Django == 1.9 , python == 3 , windows10 I want to use mysql (my database contect is really do it) when I find some resource, I will see that "python manage.py sql [appname]" it is Django to SQL when I want to use Django to mysql Can I "python manage.py inspectdb"?? it will have a models.py "python manage.py sql [appname]" = "python manage.py inspectdb" ? ERRORS: book.Book.author: (fields.E300) Field defines a relation with model 'Profile', which is either not installed, or is abstract. book.Book.author: (fields.E307) The field book.Book.author was declared with a lazy reference to 'book.profile', but app 'book' doesn't provide model 'profile'. -
how to fix the following error regarding fetching url
i am not able to access those urls mentioned in program //urls.py from django.conf.urls import include, url from rest_framework import routers from imgstore.views import QueryImage from imgstore.views import ImageActionViewSet # this is DRF router for REST API viewsets router = routers.DefaultRouter() router.register(r'api/v1/imgaction', ImageActionViewSet, r"imgaction") router.register(r'api/v1/queryimage', QueryImage, r"queryimage") urlpatterns = [ url(r'', include(router.urls, namespace='imgaction')), url(r'', include(router.urls, namespace='queryimage')) ] Error occured while running server: Exception in thread django-main-thread: Traceback (most recent call last): File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/urls/resolvers.py", line 581, in url_patterns iter(patterns)TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/root/.pyenv/versions/3.5.7/lib/python3.5/threading.py", line 914, in _bootstrap_innerself.run() File "/root/.pyenv/versions/3.5.7/lib/python3.5/threading.py", line 862, in runself._target(*self._args, **self._kwargs) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapperfn(*args, **kwargs) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_runself.check(display_num_errors=True) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/management/base.py", line 377, in _run_checksreturn checks.run_checks(**kwargs) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/checks/registry.py", line 72, in run_checksnew_errors = check(app_configs=app_configs) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolverreturn check_method() File"/root/.pyenv/versions/3.5.7/lib/python3.5/sitepackages/django/urls/resolvers.py", line 398, in checkfor pattern in self.url_patterns: File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/utils/functional.py", line 80, in get__res = instance.__dict[self.name] = self.func(instance) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/urls/resolvers.py", line 588, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'image_storage.urls' does not appear to have any patterns in it. … -
Unable to display the list object retrieved from python dajngo -view to ajax autocomplete
I'm passing list object from view to ajax autocomplete in template but unable to show the no Cars found in the drop down list I'm passing a list object as 'No Cars Found' if no objects found in dB and if found the relevant objects are sent.But i Could see DB objects are shown in the dropdown but 'No Cars Found' is not shown in the Dropdown when no objects found. < script type = "text/javascript" > jQuery(function complete() { $(".basicAutoComplete").on('keyup', function() { var value = $(this).val(); $.ajax({ url: "{% url 'ajax_autocomplete' %}", data: { 'search': value }, dataType: 'json', success: function(data) { var carslist = data.list; list = carslist; $(".basicAutoComplete").autocomplete({ source: list, minLength: 2, }); } }); }); }); < /script> View def autocomplete(request): if request.is_ajax(): q=request.GET.get('search') queryset = Cars.objects.filter(car_model__istartswith=q).values('car_model') list = [] for i in queryset: list.append(i['car_model']) if not list: list.append('No Cars Found') data = { 'list': list, } return JsonResponse(data) I need No Cars Found to be displayed in the dropdown when no matching cars found in DB. -
Modifying queryset in changelist_view on Django Admin
I need to modify the final queryset used by the changelist in the django admin. I believe (correct me if I'm wrong) I can achieve this by overriding changelist_view(), but trying to change the queryset doesn't work, just original queryset loads in the admin. def changelist_view(self, request, extra_context=None): response = super().changelist_view( request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response response.context_data['cl'].queryset = qs.filter(pk__in=qs.order_by().values('pk').distinct('target')) return response I thought that changing the context data for the changelist would achieve this, but it didn't work. How can I do this, note I need to modify the final queryset after all other filters have been applied. -
Clear Cookies and Session data when user logs out from Django web app when using built-in logout url
I am having a problem with me Django web application. Every now and then I get Request Header Or Cookie Too Large nginx error message when I get the site. This is solved by me deleting cookies in inspect element > application > cookies > clear. Obviously I dont want nor expect users of the app to do that whenever this issue pops up. I am using the built-in logout url in the template of my Django application: <a href="{% url 'logout' %}">Log Out</a> And I want to clear the cookies created including some session data I added before when a user logs out. Session data added like : session = request.session session['claim'] = a_url Whether from within Django or using some onclick jquery event in the template that's fine. I prefer it to be done from Django as then I can also clear the cookies if a logged out users requets the page (as a user might simply close the app without logging in). If a logout function (ie path) needs to be created to clear cookies, then please include that in your answer. But JQuery is fine as well. Thanks in advance. -
With docker compose, how do I access a service internally and externally using the same address?
My problem boils down to this: I have two services in docker compose: app and storage. I'm looking for a way to access the storage service (port 9000) from inside app and from outside using the same address. app is a Django app using django-storages with S3 backend. storage is a minio server (S3 compatible, used only for development). From app, I can access storage using http://storage:9000. From outside docker, I can access storage at http://localhost:9000, or http://0.0.0.0:9000, or even at http://192.168.xxx.yyy (using a different device on the network). No surprises there. However, when the URL is generated, I don't know whether it's going to be used internally or externally (or both). docker-compose.yml services: app: build: backend/ ports: - "8000:8000" volumes: - ./backend/src:/app/src command: /usr/local/bin/python src/manage.py runserver 0.0.0.0:8000 storage: image: minio/minio:RELEASE.2019-06-19T18-24-42Z volumes: - storage:/data environment: MINIO_ACCESS_KEY: "DevelopmentAccessKey" MINIO_SECRET_KEY: "DevelopmentSecretKey" ports: - "9000:9000" command: minio server /data volumes: storage: I've looked into changing the backend to yield endpoint urls depending on the context, but that is far from trivial (and would only be for development, production uses external S3 storage, I like to keep them as similar as possible). I've played around with docker-compose network configs but I cannot seem to … -
How to use ModelChoiceField in DRF?
I am trying to convert my form that was written earlier to django rest serializer but it does't work. Could you help me to solve this problem please? this is my form: class TripSearchForm(forms.Form): departure = ModelChoiceField( queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete") ) destination = ModelChoiceField( queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete") ) How to built proper serializer? -
How to avoid repeating query in loop for fetching data
I am sending site list with some its fields. Where some fields (three types payment amount with different statuses) we are fetching from other tables. Right now for each iteration of loop three queries are executing. I have mentioned below lines which are executing for each iteration In below code I am trying to get all main payment amount and summing that amount. Also there are some statuses of payment like payment raised, payment approved, payment completed. main_payment_raised = sum(mainPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Waiting').values_list('quotation',flat=True)) main_payment_approved = sum(mainPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Approved',paymentStatus='Waiting').values_list('quotation',flat=True)) main_payment_paid = sum(mainPaymentVendor.objects.filter(systemId=site['systemId'],paymentStatus='Confirm',approvalStatus='Approved').values_list('quotation',flat=True)) partial_payment_raised = sum(partialPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Waiting').values_list('amount',flat=True)) partial_payment_approved = sum(partialPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Approved',paymentStatus='Waiting').values_list('amount',flat=True)) partial_payment_paid = sum(partialPaymentVendor.objects.filter(systemId=site['systemId'],paymentStatus='Confirm',approvalStatus='Approved').values_list('amount',flat=True)) extra_payment_raised = sum(extraPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Waiting').values_list('amount',flat=True)) extra_payment_approved = sum(extraPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Approved',paymentStatus='Waiting').values_list('amount',flat=True)) extra_payment_paid = sum(extraPaymentVendor.objects.filter(systemId=site['systemId'],paymentStatus='Confirm',approvalStatus='Approved').values_list('amount',flat=True)) This entire functionality is consuming more time. Is there any optimized way to get result in minimum complexity P.S. I am using Django 1.11 and Python 2.7 -
Django Channels 2 sending knowing only the channel name
In Channels 1, easy enough to send a message to the client knowing the channel name, like: WebsocketMultiplexer(stream, Channel(reply_channel)).send(payload) How is this done in Channels 2? -
Saleor's `completeCheckout` graphql API completes checkout-id even if payment is invalid
I use Razorpay payment gateway in saleor and once an invalid payment_id is passed to checkoutPaymentCreate it creates a payment in payment_payment table. There's no way to validate payment before hitting completeCheckout API. Because of which completeCheckout API completes the checkout even though payment is invalid. I believe the checkout-id should be active if payment is invalid. This helps us to recover from an erroneous state. -
null value in column "job_id" violates not-null constraint
i'm trying to upload a pdf file but i keep getting an integrity error,when i try to submit the pdf file,it looks like i have some blank space in the db which i don't know,may someone please help me! The error is: IntegrityError at /posts/resume/ null value in column "job_id" violates not-null constraint models.py class Jobs(models.Model): title = models.CharField(max_length=80) jobs_type = models.CharField(max_length=80, choices=JOB_CHOICES) description = models.TextField() requirements = models.TextField() posted_date = models.DateTimeField(auto_now_add=True) start_date = models.DateField() deadline = models.DateField() link = models.URLField() slug = models.SlugField(max_length=150) contacts = models.CharField(max_length=80) tags = TaggableManager() class Meta: ordering = ('-posted_date',) class Application(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="application", on_delete=models.CASCADE) job = models.ForeignKey(Jobs, on_delete=models.CASCADE) professional_summary = models.TextField() resume = models.CharField(max_length=150) uploaded_at = models.DateTimeField(auto_now_add=True) form.py class ApplicationForm(forms.ModelForm): resume = forms.FileField(widget=forms.FileInput(attrs={'onchange': 'uploadPreview(this)'})) oss_resume = forms.CharField (widget=forms.HiddenInput(), required=False) class Meta: model = Application fields = ('professional_summary', 'resume', ) views.py class CreateApplicationView(LoginRequiredMixin, CreateView): form_class = ApplicationForm model = Application message = _("Your Event has been created.") success_url = reverse_lazy('posts:list_jobs') def __init__(self, **kwargs): self.object=None super().__init__(**kwargs) def form_valid(self, form): resume = form.cleaned_data['oss_resume'] form.instance.user = self.request.user submit = form.save() submit.user= self.request.user if not resume: return ('posts/no_resume.html') else: submit.save() def get_success_url(self): messages.success(self.request, self.message) return reverse('posts:list_events') def get_object(self): resume = kwargs.get('resume') return Application.objects.get(resume=resume) urls.py url(r'^list-jobs/$', JobsListView.as_view(), … -
How to Model a Matrix Table in Django
Modeling this simple table in Django ORM has plagued me for a while. My desired output is like the following. item_a item_b item_d item_d ----------------------------------------------- item_a 0 2 4 2.2 item_b 1 0 3.5 0.3 item_c 2 4 0 2 item_d 3.2 1 1 0 My requirements: The relationship of the items is a matrix-like table like above. Each row of the above table can be edited. There must be also the possibility of adding new items. The closest thing I've came across is using a manytomany relationship. But in this model my items have a relationship with themselves which makes it puzzling for me. What is the way to model such a relationship in Django models? -
Django images in template through FK
I am using a detail view to show data and I have 2 models. The problem is that one is FK of another and that ones storing pics and I need to show them, HOW?. Can't find the solution. Because of the Detail view. Please HELP file.html <img src="{{object.HallProperties.HallPictures.hall_pic0.url}}" class="w3-circle" style="width:400px" alt=""><hr width="15%"> </div><div class="zoom1"> <img src="{{object.HallProperties.hall_pic1.url}}" class="w3-round" style="width:400px" alt=""><hr width="15%"> </div><div class="zoom2"> <img src="{{object.HallProperties.hall_pic2.url}}" class="w3-round" style="width:400px" alt=""><hr width="15%"> </div><div class="zoom3"> <img src="{{object.HallProperties.hall_pic3.url}}" class="w3-round" style="width:400px" alt=""><br></div> view.py class HallDetail(DetailView): model = HallProperties template_name='hallfiles/hall-details.html' models.py class HallProperties(models.Model): hall_name = models.CharField(max_length = 128) hall_city = models.ForeignKey(CityModel.City, max_length=512) hall_owner = models.ForeignKey( HallOwnerData, on_delete=models.CASCADE, verbose_name="Hall Owner") parking_capacity = models.PositiveSmallIntegerField("Parking Capacity") class HallPictures(models.Model): hall_properties = models.ForeignKey( HallProperties, on_delete=models.CASCADE, verbose_name="Hall link") hall_pic0 = models.ImageField( "Hall Picture 1", upload_to='media/hallpics', blank=True, null=True) hall_pic1 = models.ImageField( "Hall Picture 2", upload_to='media/hallpics', blank=True, null=True) hall_pic2 = models.ImageField( "Hall Picture 3", upload_to='media/hallpics', blank=True, null=True) hall_pic3 = models.ImageField( "Hall Picture 4", upload_to='media/hallpics', blank=True, null=True) -
VS Code doesn't use pipenv .env file
Working with VS Code 1.35.1 on ubuntu 16.04 with a Python 3.7.3 pipenv virtual environment, I am trying to set environment variables in a .env file, but for some reason the file doesn't seem to be recognized. Can someone help me understand what I can do to give my (Django) app access to the environment variables, without needing to manually run pipenv shell. Steps taken: So, this is what I am doing exactly: 1 - I have set the Python interpreter for my project like so: ctrl + shift + p > Python: Select interpreter > Python 3.7.3 64-bit ('environment_name': pipenv) 2 - Created a .env file inside the project root directory: # Django SECRET_KEY="some key here" DEBUG=True ... 3 - Made sure the VS Code Python extension is installed and enabled 4 - Adjusted my Django settings file to get the SECRET_KEY from the environment variables: SECRET_KEY = os.getenv('SECRET_KEY') 5 - Running the Django development server from the VS Code terminal (with pipenv environment activated through ctrl + shift + ~): (environment-name) user@system-name:~/projects/my-project$ python manage.py runserver 6 - No other settings changed I haven't changed any settings, like the python.envFile setting. Settings are left to their defaults. How I … -
How to implement a search function in django
I am a kind of new to Django. And I am setting up a project that can display quotes based on a specific author or writer. I am having trouble creating the search function to display quotes based on the author's name. How do I create a search view function and display it on the template. For example, the user searches the author name from author_name in class Author, then it displays a list of quotes by the author Below is a sample of my models.py file class Author(models.Model): author_name = models.CharField(max_length=50) id = models.AutoField(primary_key=True) description = models.TextField(max_length=500) portrait = models.ImageField() def __str__(self): return self.author_name class Quote(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) quote = models.TextField(max_length=500) def __str__(self): return self.quote -
How to access ManyToMany Fields in Django If Mediator Class is used in relation?
I am beginner for django. I had already tried several times to solve this problem. Please consider my mistake if question is not asked properly. I don't know where I am going wrong. models.py class Participant(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=255,blank=True,null=True) last_name = models.CharField(max_length=255,blank=True,null=True) class Assessment(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(blank=True) created = models.DateTimeField(auto_now_add=True,editable=False) modified = models.DateTimeField(auto_now=True) class Seminar(models.Model): topic = models.CharField(max_length=255) date = models.DateField(null=True,blank=True) time = models.TimeField(null=True,blank=True) assessment = models.ManyToManyField(Assessment,blank=True,through='SeminarParticipant') participant = models.ManyToManyField(Participant,blank=True,through='SeminarParticipant') created = models.DateTimeField(auto_now_add=True,editable=False) modified = models.DateTimeField(auto_now=True) class SeminarParticipant(models.Model): assessment = models.ForeignKey(Assessment,blank=True,on_delete=models.CASCADE) seminar = models.ForeignKey(Seminar,blank=True,on_delete=models.CASCADE) participant = models.ForeignKey(Participant,blank=True,on_delete=models.CASCADE) request_time = models.PositiveIntegerField(default=0,validators=[MinValueValidator(0),]) is_survey_completed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True,editable=False) modified = models.DateTimeField(auto_now=True) Already try to figure this out too: many-to-many select_related in django class-based list view How to Access Many to many field in class based views in Django? views.py class SeminarListView(ListView): template_name = 'show_seminar.html' model = Seminar context_object_name = 'seminar' def get_queryset(self): queryset = Seminar.objects.prefetch_related('assessment_set').filter(participant__user=self.request.user).order_by('created') return queryset show_seminar.html <div class="row mt-5"> {% for obj in seminar %} <div class="col-sm-6"> <div class="card mt-2"> <div class="card-header"> <h4 class="text-center">{{obj.topic}}</h4> </div> <div class="card-body"> <a href="{%url 'seminar:question' 1 %}"><button>Go For Seminar</button></a> </div> <div class="card-footer"> </div> </div> </div> {% endfor %} </div> <div> {% for obj in seminar.seminarparticipant_set.all %} <p>{{obj}}</p> {% endfor … -
How to send whatsapp messages when data is inserted into database using django
I want to send a Whatsapp number to the number inserted into the sqlite. I am new to python and Django. class Invoice (models.Model): product_name = models.CharField(max_length=255) product_description = models.CharField(max_length=255) quantity = models.PositiveIntegerField() unit_price = models.PositiveIntegerField() total_price = models.PositiveIntegerField() buyer_name = models.CharField(max_length=100) buyer_phone_number = models.CharField( validators=[phone_regex], max_length=17) date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): client = Client(account_sid, auth_token) from_whatsapp_number = 'whatsapp:+14155238886' to_whatsapp_number = 'whatsapp:%d' % buyer_phone_number client.messages.create(body='Invoice created', from_=from_whatsapp_number, to=to_whatsapp_number) super(Invoice, self).save(*args, **kwargs) def __str__(self): return self.product_name It seems it cannot read the variable. -
Should I use djang.contrib.users for federated sigins?
I plan to use it for singing iin though Fb and google I also want to store additional info like whether they are signed in through google or fb. -
Pinax Stripe not validating webhook messages
I've hooked up Stripe webhooks with my Django server running pinax stripe. My Stripe dashboard indicates the webhooks are be successfully handled, but when I look in my site admin page, all webhook messages show validated=Unknown. Also, the webhook payload has not been parsed. As a side note, I've also noticed that running manage.py sync_plans syncs all plan fields except metadata. I am using pinax version 4.4.0 -
How to manually fill a form field after being submitted using a value passed to the URL in Django?
I have this form where the user has to upload a file(receipt) and then connect that file with a foreign key. I have created a simple form which takes the file, and it is working fine too. But, I have to save that file in the database, along with a foreign key to another model. Right now my model just has the file as relation and the foreign key. My form has just the field for the file upload because I obviously do not want the user to select what foreign key it is supposed to be. I want that foreign key to be filled automatically with the value given in the URL. I am calling the function like so: href="{% url 'suppliers:model_form_upload' quiz.id %}" where I am getting the quiz.id correctly. This is my model: class Uploaded_pod(models.Model): document = models.FileField(upload_to='pods/') lr_connected = models.ForeignKey(LR, on_delete=models.CASCADE, related_name='lr_pod') What I Tried This is my views.py function: def pod_upload (request, pk): lr_object = get_object_or_404(LR, id=pk) if request.method == 'POST': form = UploadPODform(request.POST, request.FILES) form.lr_connected = lr_object form.save() if form.is_valid(): form.lr_connected = lr_object form.save() return redirect('home') else: form = UploadPODform() form.lr_connected = lr_object return render(request, 'classroom/suppliers/model_form_upload.html', {'form': form}) As you can see, I am …