Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: CI/CD, BitBucket Pipelines and VPS
Is it possible to have CD set up for BitBucket repo, so that once the code is commited/merged into dev branch, tests are run in BitBucket(or other) cloud, and if tests pass, git pull is triggered on VPS as well as python manage.py commands? -
Django Forms - Is 'readonly' safe to use?
I created a form in Django. In this form, there is a field that must not be edited by the user, because the default value of the form must be sent to my database as it is. I come up with the following solution, but after making some research, i've come to find that using readOnly is generally not a good idea. Can someone clarify me on this? Should i go with another solution? tst = forms.CharField( initial='//value to be sent to the db without being touched', widget=forms.TextInput(attrs={'readonly':'readonly'})) -
PostgreSQL database design for Django real estate website
I'm working on a real estate website, and am struggling to define a design for my DB. Database needs to store Properties, attributes, property category/subcategory, and have them be linked all together. I could easily solve said problem by hard-coding property categories/subcategories in code, but would like to have it be more dynamic. Now, I want to have categories table having ID and category title, then subcategories table having ID, title and ID of a category it belongs to, so a rather basic manytoone relationship. I also need a more dynamic approach to attributes, so that I have one table, with ID, title and subcategory_id, where I'll limit attributes so that they can only be used for properties in certain subcategories. With this said, I'm having an issue figuring out how would I form a table for properties, so that it stores all the properties and its attribute/value pairs. NOTE: I'm doing this in Django. -
Service unavailable django rest framework api
I am trying to build a Django Restframework API. The endgame of this API is to calcualte indicators againt a Vectorwise database and return them to the user. The user gives a date and a store number and the response of the API would be the gross sales for that particular date, the comparable date of the previous year and the progression of sales between the two dates. The store number is of type DECIMAL in the database and the date is of type ANSIDATE. I calculate the comparable date from one table and then use the value of the date and date_comparable to calculate the sales for the entered store number from another table. The code for my views is as follows: class WebIndicators(APIView): """ Use to calculate indicators relevant to gross sales indicators for comparable dates """ serializer_class = DateInputSerializer @swagger_auto_schema(query_serializer=serializer_class, operation_id="Retrieve gross sales web indicators.", responses={200: WdcOutputSerializer, 204: "No Content", 400: "Bad Request"} ) @cache_response(key_func=calculate_cache_key_get) def get(self, request, *args, **kwargs): input_serializer = self.serializer_class(data=request.query_params) input_serializer.is_valid(raise_exception=True) sql = "select dat_refprev from dtm.dim_time where dat_ref = '" + input_serializer.data['date'] + "'" store = input_serializer.data['store'] try: df = select_vector(sql, DB_CONNECTOR) except Exception: raise ServiceUnavailable() if df is None: raise ServiceUnavailable() if … -
How to change slug if same string is stored in it?
I am working with slug on my model. Although, the entries for slug are not unique. When I try to go to a url containing slug, it says get() returned more than one object and I understand that it is because the entries are not unique. How am I supposed to change the slug a bit, if identical entries occur? model class Cabin(models.Model): centre_name = models.ForeignKey(Centre, on_delete=models.CASCADE ) code = models.CharField(max_length=8, unique=True, default=unique_rand) total_seats = models.IntegerField(blank='False') category=models.CharField(max_length=100, default=False) booked_date=models.DateField(blank='False') released_date=models.DateField(blank='False') price=models.IntegerField(blank=False, default=None) slug = models.SlugField(unique=False,default=None,blank=True) objects = UserManager() def save(self, *args, **kwargs): self.slug = slugify(self.category) super(Client, self).save(*args, **kwargs) -
How to test class method which use class object
I want to mock only part of class methods and assert result with call_args_list but I'm struggling with mock in this case. I tried many different approaches but still I'havent figured how I can write this unittest.od. I'm aware that my current solution at this moment this test doesn't check anything except PASSED status. from unittest import mock from unittest.mock import call from django.db import models, transaction class MyModel(models.Model): @classmethod def my_method(cls, arg1, arg2): with transaction.atomic(): my_model, _ = cls.objects.get_or_create(arg1=arg1, defaults={'arg1': arg1, 'arg2': arg2}) my_model.save() def test_my_method(): MyModel = mock.MagicMock() MyModel.objects.return_value.get_or_create.return_value = MyModel(arg1='arg1', arg2='arg2') MyModel.my_method('arg1', 'arg2') assert MyModel.call_args_list == [call(arg1='arg1', arg2='arg2')] I'll be very glad if someone could tell how I can test this function it correctly. -
Why to not delete your Django project and clone it back from Github again?
I have been working on a Django project for a few days. I made the most recent commit to Github just a couple of days ago. Up until this point, everything in my project was working great. After that, I made a few unnecessary changes to my project and nothing was running fine. So, I moved the entire project to some other folder on my computer and cloned it again from my Github repository. I thought everything would run fine but I couldn't be more wrong. Now, whatever changes I would make to the models.py file wouldn't show in the database at all. Why did this happen? How did I solve the problem? I deleted the Github cloned version and brought my old project back to the same directory on my computer. I deleted the database completely and re created it and then used these commands-"python manage.py makemigrations" and "python manage.py migrate". -
Behave-django - UNIQUE constraint failed when trying to load users in fixtures
I'm trying to behave with django, thanks to the behave-django integration. That's pretty great, and I'm using Selenium too, tu run my test cases. But I can't figure how fixtures really works. It failed when I have many scenarios. I've created a fixtures files with everything I need, including two users, with the django dumpdata command line. I load it on the behave environment file. Here is my environment.py file from behave import register_type from selenium import webdriver from django.core.management import call_command register_type(String=lambda text: str(text)) register_type(Int=lambda text: int(text)) register_type(List=lambda text: [w.strip() for w in text.split(',')]) def before_all(context): context.fixtures = ['data/fixtures.json'] context.browser = webdriver.Chrome() def after_all(context): context.browser.quit() def django_ready(context): context.django = True For the first Scenario, everything works fine, but when it try to run the second scenario, it fail with a UNIQUE constraint failed : python manage.py behave --lang=fr Creating test database for alias 'default'... Feature: Workflow management # features/workflow.feature:1 @fast Scenario: Do something # features/workflow.feature:4 Given an authenticated user # features/steps/users.py:4 0.620s And the object "1" # features/steps/context.py:4 0.000s And the page "settings" is displayed # features/steps/navigation.py:8 3.070s Then the trash icon is displayed # features/steps/workflow.py:4 0.036s When he click on the trash icon # features/steps/workflow.py:14 0.052s And he … -
Djago files are appear if i write in browser
i have a problem if i write sitename.com/manage.py in browser manage.py will be download. I'm trying to setup on plesk panel not only specific files but also every files such templates/xx.html it will appear {{code}} code. My guide is; https://www.plesk.com/blog/guides/django-hosting-latest-plesk-onyx/. where am I making a mistake -
Filebased caching in Django is not working
I have a django app up and running. The app connects to an s3 bucket and creates an imprint of the objects in s3 onto a psql db. Using some forms i am able to download relevant objects to a single folder called queried_data. I want to cache this folder to retain contents for a certain time etc. etc. This is my settings.py file. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/home/clyde/Downloads/new/automatic_annotator_tool/queried_data', 'TIMEOUT': '30', 'OPTIONS': { 'MAX_ENTRIES': 5 } } } CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_SECONDS = 60 CACHE_MIDDLEWARE_KEY_PREFIX = 'uvlearn' MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ..... ] I expect the cached folder to: a. sync with the db after certain time b. purge all data if it is stale. Any help would be appreciated.... TIA -
Problem in displaying objects from ForiegnKey in Django
I am having two models Patient and Ipd, Patient can have multiple Ipd. I am trying to get Patient Info in IpdForm but don't know where I am getting wrong I have already tried "qs = Ipd.objects.get(patient__id=patient_id)" , "qs = Ipd.objects.filter(patient__id=patient_id)" but nothing worked models.py : class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender= models.CharField(choices=GENDER,max_length=10) consultant = models.CharField(choices=CONSULTANT,max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient,on_delete=models.CASCADE,blank=False,default = " ") def __str__(self): return self.patient.name forms.py : class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','Patient_id','consultant','Gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient','reason_admission','presenting_complaints', 'rooms','date_of_admission'] views.py: @login_required def ipd (request,patient_id): formtwo = IpdForm() qs = Ipd.objects.filter(patient__Patient_id=patient_id) if request.method=="POST": formtwo = IpdForm(request.POST) if formtwo.is_valid() : instance = formtwo.save(commit=False) instance.save else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'a':qs,'form2':formtwo}) urls.py : url(r'^order/ipd/(?P<patient_id>\d+)/$', my_order.ipd, name='ipd'), html : <div class="card-panel"> <span class="blue-text text-darken-2">Name : {{ab.name}}</span> <br> <span class="blue-text text-darken-2">Phone : {{ a.phone }}</span><br> <span class="blue-text text-darken-2">Address : {{ a.address }}</span><br> <span class="blue-text text-darken-2">Gender : {{ a.Gender }}</span><br> </div> -
How To Clear self.add_error in Django if user clicks on browser back button?
I have a FORMVIEW where a user selects a value from a dropdown, and if they select the value, and click submit, it performs an HTTPResponseRedirect to a URL and all is well. If they forget to enter a value and click submit, they get an error message telling them to choose a value. I do a clean on the form to figure this out. This all works just fine. The issue is if the user gets an error message, then adds a value and then displays the desired output. If they then click the back button on the browser window after viewing the output, the error message is still displayed. I have been able to work around this by including a NeverCacheMixin to the form, but when the user clicks on the back button, they get an ugly Confirm Form Resubmission page. The user is just looking up a value, so maybe there is a better way to approach this? There are no updates or deletes involved, it's strictly a lookup on one page that does an HttpResponseRedirect to another. Here is my FORMVIEW... class AuthorLookupView(LoginRequiredMixin,FormView): form_class = AuthorLookup template_name = 'author_lookup.html' def form_valid(self, form): authorbyname = form.cleaned_data['dropdown'] return … -
Django Import Export export pk instead of name after using ForeignKeyWidget?
I am using django-import-export for exporting and importing data in csv. I have used example according to given doc of django-import-export. I have used: Python - version 3.7 django -version 2.2 django-import-export - 1.2.0 https://django-import-export.readthedocs.io/en/latest/api_widgets.html#widgets Django import-export display manytomany as a name instead of ids when exporting to csv models.py: class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): name = models.CharField('Book Name', max_length=100) author = models.ForeignKey(Author, blank=True, null=True, on_delete=models.CASCADE) author_email = models.EmailField('Author Email', max_length=75, blank=True) imported = models.BooleanField(default=False) published = models.BooleanField('Published', blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) categories = models.ManyToManyField(Category, blank=True) def __str__(self): return self.name resources.py from import_export import resources, fields from import_export.widgets import ForeignKeyWidget from .models import Person, Book, Author class PersonResource(resources.ModelResource): class Meta: model = Person class BookResource(resources.ModelResource): author = fields.Field( column_name='author', attribute='author', widget=ForeignKeyWidget(Author, 'name')) class Meta: model = Book fields = ('author__name', ) admin.py from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import Book, Author, Category @admin.register(Book) class BookAdmin(ImportExportModelAdmin): pass @admin.register(Author) class AuthorAdmin(ImportExportModelAdmin): pass @admin.register(Category) class CategoryAdmin(ImportExportModelAdmin): pass I expect that while exporting data of books in csv, I will get name of author in author column but got pk. And … -
django-tables2 not displaying column titles
I'm generating a leaderboard using django-tables2 based on this model (in users/models.py): class CustomUser(AbstractUser): points = models.DecimalField( max_digits=20, decimal_places=2, default=Decimal('1000.00'), verbose_name='User points') In tables.py, I select username and points, and order by the latter: class UserTable(tables.Table): class Meta: model = CustomUser fields = ('username','points') order_by = '-points' template_name = 'django_tables2/bootstrap.html' In views.py, I have def leaderboard_list(request): table = UserTable(CustomUser.objects.all()) RequestConfig(request).configure(table) return render(request, 'leaderboard.html', { 'table': table }) Finally, this gets rendered in the leaderboard.html template with {% load render_table from django_tables2 %} and {% render_table table %}. The table renders fine, but without any column headers. I added the verbose_name to the points field of the CustomUser model in light of this suggestion, under the assumption that this should show by default (as per this), but to no avail. What am I doing wrong here? -
Processing JSON with AJAX from a search
I have: {% extends 'base.html' %} {% block content %} <form method="GET" action="{% url 'libros:buscar' %}" id="buscador-libros"> <div> <input type="text" , name="titulo" /> <input type="submit" value="Buscar" /> </div> </form> <script type="text/javascript"> $(document).ready(function() { $("#buscador-libros").submit(function(e) { e.preventDefault(); $.ajax({ url: $(this).attr("action"), type: $(this).attr("method"), data: $(this).serialize(), success: function(json) { console.log(json); } }); }); }); } </script> {% endblock content %} I get the json response from the server side fine but don't know why I can not show it in console or why is this still redirecting me. What am I doing wrong? Edit: I add jquery in 'base.html' -
Python Django autocomplete light the results could not be loaded
I am trying to add autocomplete light to my project, but I am not able to. If I want to find anything in the form it says: The results could not be loaded, TypeError: 'bool' object is not callable. I am using Python version 3.7 and django-autocomplete-light version 3.3.5 The project is web app to track orders which are assigned to the users. to the mysite/settings.py I added: INSTALLED_APPS = [ 'dal', 'dal_select2', 'crispy_forms', 'myapp', to the mysite/myapp/urls.py I added: path('autocomplete/', login_required(views.OrderAutocomplete.as_view()), name="autocomplete"), to the base.html: <head> {% load staticfiles %} ... <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> and to the new_order.HTML: <form method="POST"> {% csrf_token %} {{ form|crispy }} {{ form.media }} <input type="submit"> </form> To the mysite/myapp/views.py I added: class ObjednavkaAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Objednavka.objects.none() qs = Order.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs and to the mysite/myapp/forms.py I added: class OrderForm(forms.ModelForm): user_auto = forms.ModelChoiceField(queryset=Order.objects.all(), widget = autocomplete.ModelSelect2(url='autocomplete')) class Meta: model = Order fields = ["user_auto"] mysite/myapp/models.py: from dal import autocomplete class Order(models.Model): ... user = models.ForeignKey(MyUser, on_delete=models.CASCADE) class MyUser(models.Model): eid = models.CharField(max_length=7) I am sorry for posting so much code. If I try … -
what is wrong with the update function?
i have an update function that is written in django views and that must edit or update the data in the database based on the selected ID and display the data in the form in update page once the user finish the update and click edit it must take him to the list page where it shows the updated data. views.py def update(request,pk): #deny anonymouse user to enter the create page if not request.user.is_authenticated: return redirect("login") else: # dbEntry = suspect.objects.filter(pk =pk) dbEntry = suspect.objects.get(pk =pk) print( "db entry : ",dbEntry) if request.method == 'POST': fname = request.POST['FName'] dbEntry = suspect.objects.filter(pk = pk).update(suspect_name = fName) #INSERT INTO TABLE VALUES ....... dbEntry.save() #to save into DB return render(request,'blog/update.html', {"dbEntry":dbEntry}) update.html {% extends "base.html" %} {% load static %} {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/meta-Input.css' %}"> <meta name= "viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js'%}"></script> <title>Welcome</title> </head> <body> <div class="lines"> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div><div class="line"></div> </div> <form method = "POST" enctype="multipart/form-data"> {% csrf_token … -
How to link guest and user checkout together?
I'm very new to Django and I'm confused with the checkout. I have the "accounts" app for user to enter their profile and I want to link it with the checkout but also include guest checkout. Right now I'm good to the guest-checkout but I cant link the user info from "accounts" app to the checkout. The error says " IntegrityError at /usercheckout/ NOT NULL constraint failed: accounts_profile.user_id " accounts/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=255, default='') last_name = models.CharField(max_length=255, default='') email = models.EmailField(default='none@email.com') birth_date = models.DateField(default='1999-12-31') address = models.TextField(default='') mobile = models.CharField(max_length=255, default='') def __str__(self): return self.user.username def __str__(self): return 'Order {}'.format(self.id) def create_profile(sender, **kwargs): if kwargs['created']: profile = Profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) orders/models.py class Order(models.Model): first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) email = models.EmailField() address = models.CharField(max_length=150) postal_code = models.CharField(max_length=30) city = models.CharField(max_length=100) mobile = models.IntegerField(default=0) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created', ) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) orderu = models.OneToOneField(Profile, on_delete=models.CASCADE) product = models.ForeignKey(Product_info, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * … -
How to change the url password_reset link in django?
I have a users app and I have links in urlpatterns but the problem is whenever I click on the Forgot Password link, instead of going to password_reset which I have set it leads me userspassword_reset/ url. userspassword_reset/ is a password reset page in admin page but I want it to be in custom page. path('users', include('django.contrib.auth.urls')), path('password_reset/',auth_views.PasswordResetView. as_view(template_name='users/password_reset.html') path('password_reset_done/', password_reset_done, name='password_reset_done') It should send me to this page {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {%csrf_token%} <fieldset class="form-group"> <legend class="border-bottom mb-4" style="font-size: 50px"> Reset Password</legend><br> {{form|crispy}} </fieldset><br> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Send Confirmation Link</button> </div> </form> </div> <br> {% endblock %} -
Server Error (500) when change database user password
i changed database user password and I got this error "Server Error (500)" what should i do ? [debug=False] in production -
How to pass detail url inside the list in DRF
Here i am trying to do CRUD operations with the django-rest framework and the following code works fine also but the one thing i want to change is i want to give the detail url inside the list..How can i do it ? urls.py path('create/',CategoryCreateAPIView.as_view(),name='category-create'), path('list/',CategoryListAPIView.as_view(),name='category-list'), path('detail/<int:pk>/',CategoryDetailAPIView.as_view(),name='category-detail') views.py class CategoryCreateAPIView(generics.CreateAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer permission_classes = [IsAdminUser] class CategoryListAPIView(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer permission_classes = [IsAdminUser] class CategoryDetailAPIView(generics.RetrieveUpdateDestroyAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer permission_classes = [IsAdminUser] with the list url it displays the data like this.which is fine. HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 3, "next": null, "previous": null, "results": [ { "id": 1, "name": "category1", "description": "description", }, { "id": 2, "name": "category2", "description": "description", ...................... But when i have to go for the details of id 2 then i have to enter /category/detail/1/ and then i can view the deatils of that id.Is there any solution so that i can pass my detail url inside the every id in the list? The result i want is : HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 3, "next": null, "previous": null, "results": … -
Sessions are destroying when user redirect from cc avenue payment page in python
when user click on pay user navigate to payment page integrated payment page using html post request. when user back to my application from payment page sessions are destroyed Please Help If any one know Solutions Thank you -
Filtering through two querysets with a many to many relationship in between
I have 3 different models, activity, category and sector. There's a many to many relationship between category and activity, and a one to many relationship between category and sector (a category to one sector). In a form I am getting the sector (mandatory) and I can also get the category (non mandatory field). I stock that into the session then I want to select every activities that are either in the category selected (if any selected) or in the sector. When a category is selected it's fine I just filter activities on activities_have_category. But for the case where only sector I can't filter it properly. I tried the solution to a quite similar problem but it didn't work... Solution tried: activity.objects.filter(category__sector__sector_name =request.session['sector']['sector_name']) Result: Cannot resolve keyword 'category' into field. Choices are: activities_have_category, activities_have_countries, activities_have_output_outcome_impact, activity_name, description, outcome_impact, output_outcome, product_service What I would like to get in SQL: SELECT activity_name FROM activity WHERE activities_have_category IN (SELECT category_name FROM category WHERE category_sector = "sector selected") class sector(models.Model): sector_name = models.CharField(max_length=255, primary_key=True) description = models.TextField() def __str__(self): return self.sector_name class category(models.Model): category_name = models.CharField(max_length=255, primary_key=True) description = models.TextField() category_sector = models.ManyToManyField('sector') def __str__(self): return self.category_name class activity(models.Model): activity_name = models.CharField(max_length=255, primary_key=True) description = … -
How to define an in-store cash-payment-method in django-oscar 2.0
I would like to implement cash payments, wherein the customer picks up his order in store, and pays the same there. There will also be an option later on for customers to pay cash upon delivery of their orders (note: I understand that there is an oscar cash on delivery app, but I am asking regardless). What is oscar's new recommended way to define cash payment methods in version 2.0? Previously, (though I can no longer find the documentation), payment methods were defined by expanding a base payment method like so: # mystore/forked_apps/payment/methods.py class Base(object): """ Payment method base class """ code = '__default__' name = 'Default payment' description = '' enabled = False default = False class CashOnPickup(Base): code = 'cash_on_pickup' name = 'Cash on Pickup' description = 'Pay when you pick up your items' enabled = True default = True However, the new documentation mentions the use of the SourceType, Source, and Transaction models, and I can no longer find the previous documentation regarding defining methods like above. As such, what is the recommended manner to define an in-store cash payment method in django-oscar 2.0? Is defining methods in a methods.py file no longer the way to go? … -
Slack API ConnextionError but still working
I want to post a message to Slack using a bot, so I created a service to do that (in Flask). Now I call this service using requests (Django). data = json.loads(json.dumps(_data)) headers = { 'Content-Type': "application/json", 'cache-control': "no-cache", } r = requests.post(url, json=data, auth=(username, password), headers=headers) While the bot is posting on Slack and everything is working like expected, I'm having an error message and this is confusing: ('Connection aborted.', BadStatusLine("HTTP/1.0 0{ 'ok':True, 'channel':'xxxxxxxxxxx', 'ts':'1563789414.000600', 'message':{ 'type':'message', 'subtype':'bot_message', 'text':'xxxxxxxxxxx', 'ts':'1563789414.000600', 'username':'xxxxxxxxxx', 'bot_id':'xxxxxxxxxxx' }, 'headers':{ 'Content-Type':'application/json; charset=utf-8', 'Content-Length':'220', 'Connection':'keep-alive', 'Date':'Mon, 22 Jul 2019 09:56:54 GMT', 'Server':'Apache', 'X-Content-Type-Options':'nosniff', 'X-Slack-Req-Id':'1851de9e-59ec-45a7-be61-107a092e6371', 'X-OAuth-Scopes':'admin,identify,bot,groups:read,usergroups:read,chat:write:user,chat:write:bot,groups:write', 'Expires':'Mon, 26 Jul 1997 05:00:00 GMT', 'Cache-Control':'private, no-cache, no-store, must-revalidate', 'Access-Control-Expose-Headers':'x-slack-req-id, retry-after', 'X-XSS-Protection':'0', 'X-Accepted-OAuth-Scopes':'chat:write:bot', 'Vary':'Accept-Encoding', 'Pragma':'no-cache', 'Access-Control-Allow-Headers':'slack-route, x-slack-version-ts', 'Strict-Transport-Security':'max-age=31536000; includeSubDomains; preload', 'Referrer-Policy':'no-referrer', 'Content-Encoding':'gzip', 'Access-Control-Allow-Origin':'*', 'X-Via':'haproxy-www-n3u5', 'X-Cache':'Miss from cloudfront', 'Via':'1.1 d6561aeeccb210202cf78b99f07c5235.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop':'CDG3-C2', 'X-Amz-Cf-Id':'Y4CJp-NBWSkdNYXm8bfTCdhuFPL1sn6johYZqkmv_wsXfaq0kcA7TQ==' } }\r\n")) Calling the service using a simple curl works fine without any error: curl -d "@data.json" -H "Content-Type: application/json" -X POST http://0.0.0.0:8004/ --user xxxxx:xxxxx Do you see the problem ?