Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how create multiple choice plus with custom choice in django
i'am trying to creating model which one will be for product. it must create information for example. [Male(static)][Female(static)] [Enter how you want to describe(editable)] but when i want to add choice to charfield my choicefield is dublicated. from django.db import models class Pricetab(models.Model): choice = models.CharField(max_length=200,default='test') content = models.TextField() button = models.CharField(max_length=100,default='test') MONTH_YEAR_CHOICE = ( (True, 'male'), (False, 'female') ) gender = models.Charfield(maxl_length=100, choices=MONTH_YEAR_CHOICE,default=True) def __str__(self): return self.title -
OperationalError at / no such column:core_item.brands_id
I am having a tricky database problem. I have a set of categories that display on the nav bar, once you click on those categories, there is a filter called brand, and this brand filter is supposed to take you to a page where they have products under that category (e.g. makup) and display those items. So I tried to have two foreign keys in my items module as below. Models.py class Category(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:category", kwargs={ 'slug': self.slug }) class Brand(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:brand", kwargs={ 'slug': self.slug }) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.PROTECT, null=True, related_name='category') brands = models.ForeignKey(Brand, on_delete=models.PROTECT, null=True, related_name='brands') label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() stock_no = models.CharField(max_length=10) description_short = models.CharField(max_length=50) description_long = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def … -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' for a django project
this is my first submession here, so whenever i try to run python manage.py runserver for a django project it didn't and it give an error i never saw before Any ideas about what is this and how to fix it? it give me the following error: The Error i get Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "D:\GitHub\herafi\manage.py", line 22, in <module> main() File "D:\GitHub\herafi\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 96, in handle self.run(**options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 618, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 603, in start_django reloader.run(django_main_thread) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 318, in run self.run_loop() File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 324, in run_loop next(ticker) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 364, in tick for filepath, mtime in self.snapshot_files(): File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 380, in snapshot_files for file in self.watched_files(): File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 278, in watched_files yield from iter_all_python_module_files() File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 105, … -
How to get the result of a textfield in django?
i am making a python editor, and i have a model called NewJax. In this model, i have a field called space. The space field executes the python code i typed in there. for example, if i did print('hello') in the space field, it should take me to a detail page, and return the result. Which is hello. but when it takes me to the details page for now, it results in None. Could you someone please let me know, how this should execute? models.py class NewJax(models.Model): title = models.CharField(max_length=60) description = models.TextField(max_length=140) space = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_created'] verbose_name_plural = "New Jax" def __str__(self): return str(self.title) forms.py class CreateNewJaxForm(forms.ModelForm): class Meta: model = NewJax fields = ('title', 'description', 'space') widgets = { "title": forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'name your jax' } ), 'description': forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'add a brief description for jax', 'rows': 4, } ), 'space': forms.Textarea( attrs={ 'class': 'form-control', } ) } views.py def create_new_jax(request): if request.user.username == "Assasinator": logout(request) return redirect('banned_user') if request.method == "POST": form = CreateNewJaxForm(request.POST or None) if form.is_valid(): title = form.cleaned_data.get('title') description = form.cleaned_data.get('description') space = form.cleaned_data.get('space') obj = form.save(commit=False) … -
Django+Rest and later React without Docker?
I would like to ask an advice... I did the project with Django+Rest... But never thought about adding to them React... But I would like to do React... I did it, but it runs as a local version... So I have Django which runs as https and React which runs as http://localserver:3000... Which is not really good... I went through about 6 or 7 tutorials... But they all using Docker... To use Docker I have to restructure the project completely... When I structured project first time I didn't think about React. Now generally the structure is like this: -files and folders for Djago -frontend files and folders for React -in the root of the server: /etc... files and folders for gunicorn and nginx So the question is: Is it possible to serve React, only by tuning gunicorn and nginx, without changing the site itself... So url will be something like this: https://address/home/django_url https://address/home/React_url Similar to Rest api, which I run like so:https://address/home/api/Rest_url Or so React will be as frontend based on the Django as backend... I'm kind of confused about if I can do it and how... -
Django m2m workaround relationship reverse relation
So I have three models like this. class Member(models.Model): class Meta: constraints = [ models.UniqueConstraint( fields=('user', 'locker'), name='unique_locker_member_check' ), ] locker = models.ForeignKey( to='uploads.Locker', verbose_name=_('locker'), on_delete=models.CASCADE, editable=False ) user = models.ForeignKey( to=settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE, editable=False ) class Role(CoreModel): class Meta: ordering = ('position', 'locker') permission_flags = ( 'ADD_STARS', 'DOWNLOAD_FILES', 'SEND_UPLOADS', 'MANAGE_UPLOADS', 'MANAGE_ROLES', 'MANAGE_LOCKER', 'MANAGE_INVITES', 'KICK_MEMBERS', 'BAN_MEMBERS' ) default_flags = ( 'ADD_STARS', 'DOWNLOAD_FILES', 'SEND_UPLOADS', ) def __str__(self): return self.name is_default = models.BooleanField( verbose_name=_('default'), help_text=_("whether the role is default"), default=False ) locker = models.ForeignKey( to='uploads.Locker', verbose_name=_('locker'), on_delete=models.CASCADE ) permissions = BitField( verbose_name=_('permissions'), help_text=_("permission bit set"), flags=permission_flags, default=default_flags ) REQUIRED_FIELDS = (name, locker) class MemberRole(CoreModel): class Meta: verbose_name = _('member role') default_related_name = 'member_role_set' constraints = [ models.UniqueConstraint( fields=('user', 'role', 'locker'), name='unique_member_role_check' ), ] def __str__(self): return self.role.name role = models.ForeignKey( to='roles.Role', verbose_name=_('role'), on_delete=models.CASCADE ) user = models.ForeignKey( to='users.User', verbose_name=_('user'), on_delete=models.CASCADE ) locker = models.ForeignKey( to='uploads.Locker', verbose_name=_('locker'), on_delete=models.CASCADE ) Members can have multiple Roles of their own, with the through model being MemberRole. So normally, there would be a m2m field on Member through MemberRole. However, I want the role data to persist even after a member is created. Since locker and user are unique identifiers for the member, My model structure is … -
open_note() missing 1 required positional argument: 'docid'
I appreciate that this question has been asked multiple times before, and I have looked at basically all of the answers and the official documentation for django, but I still can not figure out why I am getting the Exception Value of: open_note() missing 1 required positional argument: 'docid'. I am trying to get the page to display the selected document from the database, when it loads it should show the title and the content, along with an edit and delete button (neither of which function yet, but they're not important right now). The request url is http://localhost:8000/notes/open-notes/?docid=1, and it leads to the error mentioned above. If I change my urls.py path to path('open-notes/<int:id>/', views.open_note, name='open-notes'), then the error I get instead is Reverse for 'open-notes' with no arguments not found. 1 pattern(s) tried: ['notes/open\\-notes/(?P<id>[0-9]+)/$'] which I assume is because the id isn't actually an int and needs converting in the views.py, or I need to use a different converter in the urls.py. Or equally entirely possible, I've misunderstood the other answers in which case I apologise for asking the same question that already has an answer I should be able to implement. I am relatively new to django and … -
How to use for loop counter with a nested if loop?
I created a for loop with a nested if statement for counting specific types of customers in my Django project. What I need is the final number of the for loop counter. I try: {% if forloop.last %} {{ forloop.counter }} {% endif %} But it displays nothing. But when try just {{ forloop.counter }} it displays 2 number. One of them is what I want but the other one is all for loops I think. How can I solve this problem? list.html {% for customer in customer_list %} {% if customer.country.country_name == country %} {% if customer.risk_rating == "Low Risk" %} {% if forloop.last %} {{ forloop.counter }} {% endif %} {% endif %} {% endif %} {% endfor %} views.py def test_customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company) countries = Customer.objects.values_list('country__country_name', flat=True).distinct() country_links = Country.objects.filter() context = { 'customer_list': customer_list, 'countries': countries, 'country_links': country_links } return render(request, 'test.html', context) -
NoReverseMatch error on password reset. The error only occurs on remote server and NOT on the local server
I am getting the following error when trying to reset a password. The error occurs only on the remote server (i.e. heroku). I can change the password just fine in my local server. Reverse for 'password_reset_confirm' with keyword arguments '{'uidb64': 'MTI', 'token': 'ak0pf1-d978cc8242a65cef3803f25c240c6996'}' not found. 1 pattern(s) tried: ['user_accounts/reset/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] from urls.py url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html'), name='password_reset_confirm'), What exactly could be causing this? If the problem is in the code then how come I can reset the password in my local environment. I am bit confused here, any help will be appreciated. -
How can I resolve this type error in my project blogpost object not iterable?
This is my views.py. I suspect that i need to create a another model to handle entries. But which i think will not neccesary. from django.shortcuts import render, redirect from . models import BlogPost def index(request): return render(request, 'blogs/index.html') def posts(request): '''displays all blogs''' all_posts = BlogPost.objects.order_by('-date_added') context = { 'posts': all_posts } return render(request, 'blogs/all_posts.html', context) def post (request, posts_id): single_post = BlogPost.objects.get(id = posts_id) context = { 'single_post':single_post } return render(request, 'blogs/post.html', context) This is my html file {% extends "blogs/base.html" %} {% block body %} <h1>Posts</h1> {% for posts in single_post %} <h3>{{posts.title}}</h3> <p>{{posts.text}}</p> <p>{{posts.date_added}}</p> {% endfor %} {% endblock body %} and this is my urls.py from django.urls import path from . import views app_name = 'blogs' urlpatterns = [ path('all_posts/<int:posts_id>/', views.post, name = 'post'), path('all_posts/', views.posts, name = 'all_posts'), path('', views.index, name = 'index'), Here is my model definition for the project. The various fields have be defined correctly from django.db import models class BlogPost(models.Model): title = models.CharField(max_length = 150) text = models.TextField() date_added = models.DateField(auto_now=False, auto_now_add=True) def __str__(self): return f'{self.title}' class Meta: db_table = 'Blog_Post' managed = True verbose_name = 'BlogPost' verbose_name_plural = 'BlogPosts' -
Order by for a method in django
I would like to show the top 10 of clients with balance from bigger to smaller. but the prob is that balance is method. class ClientsBalance(models.Model): client = models.OneToOneField('Client', on_delete=models.CASCADE,related_name='Client') def inputs(self): total = self.client.invoice_set.aggregate(sum=Sum('total_general')) return round(total[("sum")] or 0, 2) def outputs(self): total = self.client.clientpayment_set.aggregate(sum=Sum('total_paid')) return round(total[("sum")] or 0, 2) def balance(self): return self.outputs() - self.inputs() def Dashboard(request): clientsbalances = clientsbalance_set.all()[:10] context = {'clientsbalances': clientsbalances} return render(request, 'dashboard.html', context) -
Django class based views- handle redirect to the same view, add new context
After POST request I want to redirect user to the same view, adding something to the context. I have no idea how to do it. I tried using get_context_data(**kwargs) but I think I don't really understand the concept. If I do not add anything into context I simply redirect to the same view, which sounds dumb but works. Here's my code: (the class is "home.html" view) class FilteredZamTableView(LoginRequiredMixin, SingleTableMixin, FilterView): table_class = ZamTable template_name = 'home.html' paginate_by = 10 filterset_class = ZamFilter def post(self, request, *args, **kwargs): if request.POST.get('accept_zam'): try: ... return redirect('home') except Exception as e_msg: context = self.get_context_data(**kwargs) context['error'] = e_msg return render(response, "home.html", context) I get this error msg at self.get_context_data(**kwargs) django.urls.exceptions.NoReverseMatch: Reverse for 'home' with keyword arguments '{'e_msg': AttributeError("'FilteredZamTableView' object has no attribute 'object_list'")}' not found. 1 pattern(s) tried: ['$'] -
Marshmallow didn't serialize nested one-to-many Django relation
I need to serialize list of Post objects and return it as JSON in Django. For this purpose I use marshmallow. It works fine, except nested Comment model, that not serializing at all: [ { "id": 6, "created_at": "2021-03-22T13:57:24.576260+00:00", "user": { "id": 1, "username": "admin" }, "group": { "title": "Post title", "id": 2, "members": 6 }, "text": "This is post text" } ] And it should be like this: [ { "id": 6, "created_at": "2021-03-22T13:57:24.576260+00:00", "user": { "id": 1, "username": "admin" }, "group": { "title": "Post title", "id": 2, "members": 6 }, "comments": { { "id": 1, "user": { "id": 1, "username": "admin" }, "text": "This is first comment text" }, { "id": 2, "user": { "id": 1, "username": "admin" }, "text": "This is second comment text" } }, "text": "This is post text" } ] Here is a code. Models: class Post(models.Model): text = models.TextField(max_length=1600) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True,) group = models.ForeignKey(Group, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.CharField(max_length=1200) created_at = models.DateTimeField(auto_now_add=True) Marshmellow schema: class CommentSchema(Schema): id = fields.Int() user = fields.Nested(UserSchema) text = fields.Str() class PostSchema(Schema): id = fields.Int() text = fields.Str() created_at = fields.DateTime() user … -
Nepali Date-picker orientation/placement required to top
I'm using NepaliDatepicker from here: https://leapfrogtechnology.github.io/nepali-date-picker/demo/ i attached datepicker placed at the bottom of the popup page. My problem is that the datepicker appears below the screen. when when i reduce zoom only then i see this else not. -
How is the UserAttributeSimilarityValidator supposed to be used in Django?
I am testing a REST API I wrote in Django, but this validator does not work as intended. I read the docs on this, but I need more than a description; I need a working example. I have it defined in settings.py as is the default. # my_app/settings.py AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, ... ] However, when I run the test, I get an unexpected and undesired success. # api/authentication/tests.py body = { 'username': 'frank', 'email': 'frank@example.com', 'password1': 'frank@example.com', 'password2': 'frank@example.com', } response = self.client.post(url, body, format='json')) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) > ./manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_register (api.authentication.tests.AuthTests) Ensure we can register a user and test for validation errors. ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/matt/Repositories/my_app/back-end/api/authentication/tests.py", line 108, in case_password_has_email self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) AssertionError: 201 != 400 ---------------------------------------------------------------------- Ran 1 test in 0.275s FAILED (failures=1) Destroying test database for alias 'default'... Am I missing the point of this validator? Am I just using it wrong? My intended behavior is for a 400 response to be sent with an error message, like the other validators allow for. How do I accomplish this? -
String value for decimal field doesn't throw ValidationError in view but works fine in shell
I created test project to figure this out. Here is the form: class PaymentForm(forms.Form): amount = forms.DecimalField(max_digits=2, decimal_places=2, required=False) Everything works as expected in shell: >>> from testapp.forms import PaymentForm >>> f = PaymentForm({'amount': 'a'}) >>> f.errors {'amount': ['Enter a number.']} >>> f.is_valid() False But if I enter string value in a template and submit the form, it doesn't give any error messages at all and 'it is valid' is being printed. def add_payment(request): if request.method == 'POST': payment_form = PaymentForm(request.POST) if payment_form.is_valid(): print('it is valid') else: payment_form = PaymentForm() return render(request, 'testapp/add.html', {'payment_form': payment_form}) When i make the field required, the form gives the expected 'Enter a number' and the view - 'Required field' error message. Any ideas how to make it work? Is this how django forms supposed to work? Because i couldn't find anything by googling. -
Filter two models django
I have two similar models: class Boat(models.Model) name = models.CharField(max_length=140, help_text="Enter a Boat name") company = models.CharField(max_length=140) time = models.TimeField(auto_now=False, auto_now_add=True, editable=False, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ['-time'] class Car(models.Model) name = models.CharField(max_length=140, help_text="Enter a Boat name") company = models.CharField(max_length=140) time = models.TimeField(auto_now=False, auto_now_add=True, editable=False, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ['-time'] For example, there are 3 objects of the car model: Name Created Nissan Almera 02/2/2020 Renault Logan 01/9/2020 Mitsubishi L200 03/24/2021 and 1 one object of the boat model: Name Created wooden boat 01/01/2021 Is it possible to make a filter that would display the 3 most recently created objects? i.e wooden boat, mitsubishi L200 and renault Logan -
defining all columns in django values just to get foreign key value
I am working on a Django app and I have a model containing about 60 columns with few ForeignKeys For e.g. class Company(models.Model): name = models.CharField(max_length=100) city = models.CharField(max_length=100) address = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) # and many more rows I need to show all data in DataTable. Company.objects.all().values() To get the username from user column, I need to call it as Company.objects.all().values('user__username') But this doesn't makes sense to me, Just to get the username, I will have to define all columns of Company model Company.objects.all().values('name', 'city', 'address', 'user__username') I was already getting 'name', 'city', 'address' with .values() But to get username, I have to define them explicitly. This is okay with small models, but this approach becomes tidious and error-prone with bigger models. I'm sure there must be a better way to do this that I dont know. Any help would be appreciated. -
Django query sets optimization
I am having a function with some filtering logic, and returns certain levels after passing through different validations, however I would like to optimize this code so that I remove duplicates from the querysets. Its not that direct , but it's possible to see the duplicates, how best can I remove the duplicates below : def get_bo_level(self, main_company): shares = BeneficialOwnerShares.objects.filter( parent_company=self, owner_company=main_company) if shares.exists(): return 1 level_one_business = BeneficialOwnerShares.objects.filter( parent_company=self).values_list('owner_company') shares = BeneficialOwnerShares.objects.filter( parent_company__in=level_one_business, owner_company=main_company) if shares.exists(): return 2 parents = BeneficialOwnerShares.objects.filter( owner_company=self ).values_list('parent_company', flat=True) level_three_business = BeneficialOwnerShares.objects.filter( owner_company__in=parents, parent_company=main_company ).first() if level_three_business: return 3 return None -
CORS allowing jsonplaceholder
I'm learning vue and I'm experimenting with API calls with axios to my local django server. Therefore I encountered CORS errors. I already know how CORS works and why it is blocking my calls, however when I try to send a call to this fake API for testing, it works flawlessly. How is cors allowing it? Here's an example code: axios.get('https://localhost:8000/api/posts') .then( () => console.log('Local server working :)')) axios.get('https://jsonplaceholder.typicode.com/todos') .then( () => console.log('Fake api working :)')) Result: -
How retrieve Discord messages to my website?
I currently have a Python/Django platform and a Discord community. I would like to get the messages of a channel to convert them into notifications on the site. Obviously I consulted the Discord doc but I really have trouble understanding. I don't want to create a bot for this simple action, in principle by using the OAuth app with the "messages.read" scopes it would be possible. I can generate my token now: def discord_get_token(): data = { 'client_id':DISCORD_CLIENT_ID, 'client_secret':DISCORD_PRIVATE_KEY, 'grant_type': 'client_credentials', 'redirect_uri': 'http://127.0.0.1:8000', 'scope': 'identify connections messages.read' } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } r = requests.post('%s/oauth2/token' % DISCORD_BASE_URI, data=data, headers=headers) r.raise_for_status() #Token print(r.json()['access_token']) return r.json()['access_token'] Then the call to the messages with the following route /channels/{channel.id}/messages : def get_channel_messages(id_channel): route = "/channels/"+ str(id_channel) +"/messages" data,error_message = request_discord('GET',route) print(data) def request_discord(method,url_access,body={}): data ='' #Call token error_message = '' access_token = discord_get_token() #Call request headers = {'Content-Type':'application/json','Authorization':'bearer ' + access_token} body = body if method=="GET": result = requests.get(DISCORD_BASE_URI + url_access, headers=headers,data=body) else: result = requests.post(DISCORD_BASE_URI + url_access, headers=headers,data=body) #Check result if result.status_code != 200 and result.status_code != 201: error_message = "Impossible de d'obtenir un resultat erreur: " + str(result.status_code) else: data = result.json() return data,error_message A 401 error is returned. Unlike … -
Stop Celery Job to get triggered at every deployment on AWS
I am usingCelery in Docker container deployed on AWS for some asynchronous jobs scheduling withRedis as the broker. Here is my config in settings.py. All is working well. My only issue is the the job is getting triggered at every deployment even though I have set specific times for it. Otherwise after the deployment it works fine. I am scratching my head to stop the first triggering. settings.py CELERY_BROKER_URL = "redis://localhost:6379" CELERY_RESULT_BACKEND = "redis://localhost:6379" CELERY_BEAT_SCHEDULE = { "fill_db_daily": { "task": "agendanotification.tasks.fill_db_daily", "schedule": crontab(hour=0, minute=1), }, "articles_email_daily": { "task": "agendanotification.tasks.articles_email_daily_prod", "schedule": crontab(hour=0, minute=30), } } In tasks.py: @shared_task def fill_db_daily(): call_command("fill_db", ) @shared_task def articles_email_daily_prod(): call_command("articles_email_prod", ) -
500 error when deploying Django app to Heroku with no obvious error messages
I am trying to deploy my Django app via Heroku and keep receiving a 500 error. I'm new to Django so am not really sure what could be going wrong as I've followed a tutorial online pretty closely, but I've obviously mucked something up somewhere. I've looked at the logs and it doesn't really tell me anything... at least nothing that I can decipher. Thanks to anyone who's able to translate this into English. 2021-03-24T11:09:44.413513+00:00 heroku[web.1]: State changed from starting to up 2021-03-24T11:09:47.222339+00:00 heroku[router]: at=info method=GET path="/" host=thediamondseeker-2.herokuapp.com request_id=19a272b0-7efa-43d5-bbd1-8e28a70cb43a fwd="94.1.111.13" dyno=web.1 connect=1ms service=985ms status=500 bytes=410 protocol=https 2021-03-24T11:09:47.218908+00:00 app[web.1]: 10.29.126.3 - - [24/Mar/2021:11:09:47 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" This is my settings.py """ Django settings for diamonds project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path 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.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production … -
Authorization Headers is missing using c# client
I am developing a RESTFUL API using django-rest-framework. And for Authorization I choose to use Token Authorization (not JWT). Below is what I tried: Using POSTMAN (Works) headers: Authorization: Token 329367424fd30a876ccff05dbc5a18d86fe7158c Using C# Client (no working) HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", "Token 329367424fd30a876ccff05dbc5a18d86fe7158c"); await client.GetAsync(<url>) // Authentication credentials were not provided. After I debug and override TokenAuthentication function, I realize that Authorization headers is being removed if requested from C# Client. I saw a lot of question are being asked related to this problem, and the solution is adding WSGIPassAuthorization On I am not sure where should I add above line wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nusames_core.settings') application = get_wsgi_application() FYI: I am planning to use gunicorn as my webserver, also I need it work locally (I am not using venv) Question: is there any workaround for my local env in order to make it works on c# client, and is there any best practice for production env? -
AttendanceRange matching query does not exist in django
Traceback (most recent call last): File "D:\Apps\Python\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Apps\Python\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "D:\Apps\Python\lib\site-pack`enter code here`ages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) File "D:\Apps\Python\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1581, in _changeform_view self.save_related(request, form, formsets, not add) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1121, in save_related self.save_formset(request, form, formset, change=change) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1109, in save_formset formset.save() File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 673, in save return self.save_existing_objects(commit) + self.save_new_objects(commit) File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 811, in save_new_objects self.new_objects.append(self.save_new(form, commit=commit)) File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 951, in save_new return super().save_new(form, commit=commit) File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 650, in save_new return form.save(commit=commit) File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 460, in save self.instance.save() File "D:\Apps\Python\lib\site-packages\django\db\models\base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "D:\Apps\Python\lib\site-packages\django\db\models\base.py", line 801, in save_base post_save.send( File "D:\Apps\Python\lib\site-packages\django\dispatch\dispatcher.py", line 177, in …