Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NLTK: TypeError: must be str, not list
I'm using newspaper3k in a docker container. I downloaded all the needed nltk data, however I'm having this problem when I run article.nlp() then article.nlp() and article.summary. When I used the same code in a Flask app it worked, now I'm testing it on a Django (+ DRF), and I'm having this errors: web_1 | File "/usr/local/lib/python3.6/site-packages/newspaper/article.py", line 361, in nlp web_1 | summary_sents = nlp.summarize(title=self.title, text=self.text, max_sents=max_sents) web_1 | File "/usr/local/lib/python3.6/site-packages/newspaper/nlp.py", line 45, in summarize web_1 | sentences = split_sentences(text) web_1 | File "/usr/local/lib/python3.6/site-packages/newspaper/nlp.py", line 157, in split_sentences web_1 | tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') web_1 | File "/usr/local/lib/python3.6/site-packages/nltk/data.py", line 752, in load web_1 | opened_resource = _open(resource_url) web_1 | File "/usr/local/lib/python3.6/site-packages/nltk/data.py", line 877, in _open web_1 | return find(path_, path + [""]).open() web_1 | TypeError: must be str, not list It seems that there's a problem finding tokenizers/punkt/english.pickle, but when I check the nltk_data, it's there. Do you have any idea, from where this may come? Update: The code is very simple. This is my Django view: article = Article(url, language=LANG) article.download() article.parse() article.nlp() <---- The problem happens here most probably article.summary Since I'm using Django Rest Framwork, I'm serializing using this field: summary = serializers.CharField(max_length=5000, required=False) -
update not working in django rest framework in transaction
I am facing a very weird issue here. My viewset is supposed to update two models together so I am using transaction.atomic(): Here is my partial_update of viewset: def partial_update(self, request, *args, **kwargs): with transaction.atomic(): # To update product object request.data['last_modified_by'] = request.user.id super(ProductViewSet, self).partial_update(request, *args, **kwargs) product_detail = ProductUpdateSerializer().update_detail(request) return Response(data=product_detail.json(), status=status.HTTP_200_OK) and here is my update_detail function of ProductUpdateSerializer which updates my other model and internally calls another api: class ProductUpdateSerializer(serializers.ModelSerializer): def update_detail(self, request): # To update product detail object product = ProductModel.objects.get(id=request.parser_context['kwargs']['pk']) request.data.update({'last_modified_by': request.user}) ProductDetailUpdateSerializer().update(product.product_detail, request.data) # Internal call to product retrieve api to generate response body product_detail = requests.get( url=settings.USERS_SERVICE_BASE_URL + reverse( 'product_detail', kwargs={ 'pk': request.parser_context['kwargs']['pk'] } ), headers={ 'content_type': 'applicatiion/json', 'authorization': '{}'.format( request.headers["Authorization"] ) }, ) return product_detail Now when I hit the api on postman, it is working fine without transaction.atomic() But on adding transaction, I have to hit the api twice to update my object. Why is that happening? Any leads would be appreciated! -
javascript files are not working in django template
I have done all the static file settings but javascript and other javascript libraries are still not working whereas CSS is working perfectly if I attach a jquery file it works but source code doesn`t. <script src="{% static 'assets/js/custom.js"></script> <script src="{% static 'assets/js/config.navbar-vertical.min.js' %}"></script> <script src="{% static 'assets/js/popper.min.js' %}"></script> <script src="{% static 'assets/js/bootstrap.min.js' %}"></script> -
How do I test Sentry tags that are sent from a Django app exception?
Our Django application is configured to send all logger.errors and logger.exceptions to Sentry. I'm trying to implement something where in some cases, I can assign a custom tag to the event in question before the exception hits and have that event be tagged appropriately. Since I'm using it in more than one place, I want to make a function like this: from sentry_sdk import push_scope def set_sentry_custom_tag(key: str, value: str) -> None: with push_scope() as scope: scope.set_tag(key, value) logger.info(f'Set sentry custom tag -> {key}:{value}') ...and use it like so: try: check_widget_factory() except Exception as e: set_sentry_custom_tag('my-tag-key', 'my-tag-value') logger.exception(f'Widget check failed: {e}') I think this will work but not sure if the push_scope needs to be directly in the method where the exception happens-- I'm a little fuzzy on how the Scope works for Sentry and if it is in some context in the immediate frame before getting passed on to the logger handling which sends the event to Sentry. I'm trying to write some tests to ensure that this tag is set appropriately and attached to the event when an exception is raised, but coming up empty so far as to how to get the local scope and verify that … -
Ajax request not showing in my django template even though getting json from request
I am trying to display search result for Youtube videos while user are typing their search terms. I am using Django, jquery and ajax. Here are the important information from my different files (I am just showing the relevant info and cutting the other stuff) : -> Urls.py file : urlpatterns = [ path('video/search/', views.video_search, name="video_search"),] -> add_video.html file : <form method="post"> {% for field in search_form %} <div class="form-group"> {{ field.errors }} {{ field.label_tag }} {% render_field field class="form-control" %} </div> {% endfor %} </form> <div id="search_result"></div> -> forms.py file : class SearchForm(forms.Form): search_term = forms.CharField(max_length=255, label="Search for videos") -> firstajax.js file : $(function() { var DelayTimer; $('#id_search_term').keyup(function() { clearTimeout(DelayTimer); $('#search_result').text('Loading...'); DelayTimer = setTimeout(function() { var text = $('#id_search_term').val(); $.ajax({ url: 'video/search/', data: { 'search_term': text }, dataType: 'json', success: function(data) { var results = ''; $('#search_result').text(''); data['items'].forEach(function(video){ results += video['snippet']['title'] }); $('#search_result').append(results); } }); }, 1000); }); }); -> views.py file : def video_search(request): search_form = SearchForm(request.GET) if search_form.is_valid(): encoded_search_term = parse.quote(search_form.cleaned_data["search_term"]) response = requests.get(f'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=5&q={encoded_search_term}&key={YOUTUBE_API_KEY}') return JsonResponse(response.json()) return JsonResponse({'error': 'Not able to validate form'}) Whenever I am typing in my search bar, I get just the "Loading" displaying in search_result div... And nothing else is happening. However, I … -
Support needed for Django app deployment on Heroku
I have an app I'd like to deploy on Heroku. Not finished yet but it's now a requirement from my teacher. I created an account and app on heroku and use the GitHub deployment method but when I click on deploy branch I have the following type of error: -----> Python app detected -----> Installing python-3.6.10 -----> Installing pip -----> Installing SQLite3 -----> Installing requirements with pip ERROR: Could not find a version that satisfies the requirement dj-database-url==version (from -r /tmp/build_ec8d1380c8c763b0e4f17f12a2ddb669/requirements.txt (line 1)) (from versions: 0.1.2, 0.1.3, 0.1.4, 0.2.0, 0.2.1, 0.2.2, 0.3.0, 0.4.0, 0.4.1, 0.4.2, 0.5.0) ERROR: No matching distribution found for dj-database-url==version (from -r /tmp/build_ec8d1380c8c763b0e4f17f12a2ddb669/requirements.txt (line 1)) ! Push rejected, failed to compile Python app. ! Push failed I've seen somewhere here that it could be because Django isn't installed, however I am not sure. Can you help me understand the error and solve it? I'd like to use this deployment method if possible as I am very much a begginer in git too and I'd like to avoid doing it with CLI for now. Thanks, -
TypeError: 'Player' object is not callable Django
Ok guys I have such problem. Django returns me Type Error for such view. It is meant to be a turns system for a game: @login_required def game_end_turn(request, id): game = Game.objects.get(id=id) player = Player.objects.get(parent=request.user) if player == game.turn_of_player: game.turn_of_player = game.next_player() game.save() return redirect('detail', id=game.id) else: return redirect('detail',id=game.id) model: class Game(models.Model): name = models.CharField(max_length=150) host = models.CharField(max_length=10) is_played = models.BooleanField(default = False) max_players = models.IntegerField(default=4) who_is_ready = models.ManyToManyField(Player, related_name="guys_ready", blank=True) who_is_playing = models.ManyToManyField(Player, related_name="guys_playing", blank=True) turn = models.IntegerField(default=1) turn_of_player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='czyja_tura', blank=True, null=True) ... and it's methods: @property def how_many_players_playing(self): return self.who_is_playing.count() @property def players_playing(self): return list(self.who_is_playing.all()) @property def next_player(self): x = self.players_playing.index(self.turn_of_player) nast= x+1 if nast > self.how_many_players_playing: self.turn +=1 self.save() return self.players_playing[0] else: return self.players_playing[x+1] And it ends with such error: TypeError: 'Player' object is not callable: pointing here: game.turn_of_player = game.next_player() Why I can't to assign that Player? Please help me. Thanks -
I keep getting this Error when writing my Django code: 'WSGIRequest' object has no attribute 'profile'
def edit(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.profile) if form.is_valid(): form.save() return redirect(reverse('/profile')) else: form = EditProfileForm(instance=request.profile) args = {'form': form} This is my code for the view and it always gives me an error when I go to this URL -
'server error please contact administrator' when i try to run python manage.py runserver
When i run python manage.py runserver i receive a server error. I have tried for several days now to resolve this problem on my own. I have followed several tutorials to no avail. How I am a beginner so i am new to django and python. I'm hoping that its just something that i'm overlooking. Can anyone please help me with this? Thank you so much in advance. Alex Here is the return i'm receiving when i runserver. (Django_Tutorial) Alexanders-MBP:Django_Tutorial alexanderbodiford$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 14, 2020 - 11:58:56 Django version 3.0.6, using settings None Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/alexanderbodiford/Django_Tutorial/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 133, in call response = self.get_response(request) File "/Users/alexanderbodiford/Django_Tutorial/lib/python3.7/site-packages/django/core/handlers/base.py", line 74, in get_response set_urlconf(settings.ROOT_URLCONF) File "/Users/alexanderbodiford/Django_Tutorial/lib/python3.7/site-packages/django/conf/init.py", line 77, in getattr val = getattr(self._wrapped, name) File "/Users/alexanderbodiford/Django_Tutorial/lib/python3.7/site-packages/django/conf/init.py", line 205, in getattr return getattr(self.default_settings, name) AttributeError: module 'django.conf.global_settings' has no attribute 'ROOT_URLCONF' [14/May/2020 11:59:02] "GET / HTTP/1.1" 500 59 Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) … -
how to see hidden data in django admin?
I am trying to make a signup interface in Django. at first, I have created a form using Django user creation form along with two extra fields. but whenever I submit the form I can not find the data of extra field. here is the code for form creation: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserSignUp(UserCreationForm): email=forms.EmailField() age=forms.CharField() adress=forms.CharField() class meta: model=User fields=['username','password1','password2','email','age','adress'] and here is the view for signup validation def signupuser(request): if request.method=="POST": form=UserSignUp(request.POST) if form.is_valid(): form.save() return render(request,'diabetes/home.html') else: form=UserSignUp() return render(request,"diabetes/signupuser.html",{'form':form}) now, what should I do? -
Compile httpd from source for django
I want compile httpd from source for django application. Also, I want to enable ssl and ldap in that. How can I achieve? -
Append data to Django form with JavaScript after its submission
I'd like to append a key/value field to the data sent via XHR from a Django form: forms.py: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['first_name', 'surname', 'role'] # do I need the 'role' here? It's not an input which should be available to the users def save(self, commit=True): profile = super(ProfileForm, self).save(commit=False) first_name = self.cleaned_data['first_name'] surname = self.cleaned_data['surname'] role = self.cleaned_data['role'] if Profile.objects.filter(first_nameUnregistered=self.cleaned_data['first_nameUnregistered'], surnameUnregistered=self.cleaned_data['surnameUnregistered']).exists(): raise forms.ValidationError("This profile already exists") elif commit: profile.save() return profile And in my template I grab the form data (name and surname) and add a 'role' to them: var oReq = new XMLHttpRequest(); var formData = new FormData(oFormElement) formData.append("role", 10); var data = formData The data gets sent correctly and even the response I see in the console shows that the role has been assigned. Nevertheless when I go to my django/admin site I see that the profile has been created without the 'role' recorded. Is there some extra step I need to be doing it, or something completely wrong? I don't want to and cannot assign the 'role' in the form and put the field as hidden/read only. -
Can't Parse Client Side JSON Object Created with Python/Django
I'm passing an object of data from a Python/Django App to the front end using AJAX in JSON form. Everything is working correctly, except that I cannot parse the JSON object once in Javascript. I keep getting undefined. I've tried every approach I could think of and I am super stuck so I wanted to see if someone might be able to point out what I hope is a super simple oversight! Snippet of Python/Django: data = serializers.serialize('json', products) response = {'product_data': data, 'product_count': product_count} return HttpResponse(json.dumps(response), content_type='application/json') Snippet of AJAX Callback: .done(function(data){ console.log(data.product_count) console.log(data.product_data) console.log(data.product_data["model"]) console.log(data.product_data[0]) console.log(data.product_data[0]["model"]) }) Console Logs Response Snippet: >1 >[{"model": "seller.product", "pk": 11048, "fields": {"seller": 132, "width": 211, "height": 3, "length": 350, "weight": 18600, "price": 11077, "color_id": null, "po_number": null, "po_sub_number": null, "custom_order_id": null, "active_at": "2019-08-02T01:27:23.410Z", "deactive_at": null, "in_holding": false, "approved_at": "2019-08-04T15:34:08.318Z", "sold_at": "2020-02-07T20:07:54.675Z", "slug": "colored-beni-ourain-rug", "created_at": "2019-08-02T01:23:51.650Z", "updated_at": "2020-02-07T20:07:54.675Z", "assets": [3567, 3581, 3585, 3572, 3573, 3574, 3577, 3582, 3583, 3584, 3586, 3587, 3589, 3594, 3596], "colors": [1, 2, 3, 4, 12], "shipping_options": [1]}}] > undefined > [ > undefined The first console log of 1 is correct and in the second line the data I want is all there. But any time I try … -
Laravel OAuth2 authentication for Django Site
I am building a Django application and I need to connect to an existing external Laravel site to authenticate users. Basically to have two different platforms, but users only have one set of credentials. Also - users should be able to sign up on the Django, and their user is created in the Laravel DB. The Laravel site has Laravel Passport (OAuth2 based) installed because it uses it for a Flutter app. I know that REMOTE_USER is "the Django way" of achieving external auth but, I don't know where to go from there. If it makes a difference, the Django app will be a full REST application using DRF because its frontend will be ReactJS. Can anyone explain how to achieve external auth with Django, particularly when the authentication server is OAuth2 based? Or better yet, how it can work with Laravel Passport in particular. Thanks -
Heroku unable to load static files, django, using whitenoise
I'm trying to deploy my django site to heroku, unfortunately none of the static css files were showing. I've been looking through a bunch of solutions but to no avail. Really frustrating because the rest of the site is working perfectly! By the way the bootstrap classes are loading, which is pretty obvious, just thought I'd mention it. I've already tried solutions from heroku & django: server doesn't load staticfiles and later took application = DjangoWhiteNoise(application) out form wsgi.py because of "The WSGI integration option for Django (which involved editing wsgi.py) has been removed." according to http://whitenoise.evans.io/en/stable/changelog.html#v4-0. Also tried this Django Heroku Debug = False, Static files cause Internal Server Error, worth mentioning when I turn debug to False, I get ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'Viewshop/main.css', looked around for this error (https://groups.google.com/forum/#!topic/django-users/CWpTDpkaIlA, https://www.tfzx.net/article/2712598.html, also checking the http://whitenoise.evans.io/en/stable/django.html). None of these solutions worked either! (or maybe I'm really messing something up) Anyway Here is my settings.py file """ Django settings for Project1 project. Generated by 'django-admin startproject' using Django 3.0.3. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import … -
Django unexpectedly stores only password hash, not algorithm parameters
I have a Django app which works as expected locally. It creates a user in a migration: superuser = User.objects.create_superuser( username=username, email=email, password=password ) superuser.save() Locally it creates a password structure exactly as I'd expect: MySQL [XXXX]> select * from auth_user; +----+---------------------------------------------------------------------------+----------------------------+--------------+----------+------------+-----------+-------------------+----------+-----------+----------------------------+ | id | password | last_login | is_superuser | username | first_name | last_name | email | is_staff | is_active | date_joined | +----+---------------------------------------------------------------------------+----------------------------+--------------+----------+------------+-----------+-------------------+----------+-----------+----------------------------+ | 5 | argon2$argon2i$v=19$m=512,t=2,p=2$SXXXXXXXXXX2eVFl$KZdVItv/XXXXXXXXXXXuRg | 2020-05-15 16:26:01.713174 | 1 | internal | | | XXX@XXX.org | 1 | 1 | 2020-05-15 16:25:12.438746 | +----+---------------------------------------------------------------------------+----------------------------+--------------+----------+------------+-----------+-------------------+----------+-----------+----------------------------+ In production it did something very odd, storing the hash but not any algorithm data: MySQL [XXXX]> select * from auth_user; +----+-------------------------------------------+------------+--------------+----------+------------+-----------+-------------------+----------+-----------+----------------------------+ | id | password | last_login | is_superuser | username | first_name | last_name | email | is_staff | is_active | date_joined| +----+-------------------------------------------+------------+--------------+----------+------------+-----------+-------------------+----------+-----------+----------------------------+ | 1 | !rbx7XXXXXXXXXXXXXXXXu7o84FNI3tZcQc5Lgkqt | NULL | 1 | internal | | | XXX@XXX.org | 1 | 1 | 2020-05-15 09:43:49.955879| +----+-------------------------------------------+------------+--------------+----------+------------+-----------+-------------------+----------+-----------+----------------------------+ As far as I'm aware, the docker containers are exactly the same and have the same dependencies. What could cause this? -
Migrating existing related fields to another model in Django
I have these models: class Office(models.Model): name = models.CharField(max_length=100) class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) is_admin = models.BooleanField(default=False) office = models.ManyToManyField(Office) class Basic(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name="basic_profile" ) first_name = models.CharField(max_length=300, blank=True, null=True) last_name = models.CharField(max_length=300, blank=True, null=True) class Administrator(models.Model): user = models.OneToOneField( User, models.CASCADE, related_name="admin_profile") first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) At the moment, each user is either attached to an Administrator or Basic instance. Each user can be part of many Office. I want to have it so that the user can manage multiple Basic objects while those Basic objects can be part of separate offices. To do this, I believe I would need to migrate the office = models.ManyToManyField(Office) over to the Basic and Administrator objects. Keep in mind that the Basic model will be seen by Administrators within the Office model. That's why I want to have some separation. -
Django and Nginx - Invalid HTTP_HOST header
I'm struggling to find out whats wrong with my Nginx config that is allowing this to happen. I believe it has something to do with me trying to force "www." in front of the domain name. I have the code for it to deny the illegal host headers that i've found in previous forums. heres my current config file for nginx: upstream app_server { server 127.0.0.1:9000 fail_timeout=0; } limit_req_zone $binary_remote_addr zone=allsite:10m rate=1r/s; server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; server_name _; return 301 http://www.example.com$request_uri; } server { listen 80; listen [::]:80; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name www.example.com; keepalive_timeout 5; # Your Django project's media files - amend as required location /media/ { alias /home/django/myproject/static/media/; } # your Django project's static files - amend as required location /static/ { alias /home/django/myproject/static/static-only/; } location /favicon.ico { alias /home/django/myproject/static/static-only/img/favicon.ico; } ## Deny illegal Host headers if ($host !~* ^(example.com|www.example.com)$ ) { return 444; } location / { # apply rate limiting limit_req zone=allsite burst=15 nodelay; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } -
Django write a get_form() function
I have an app that creates modelForms dynamically based on models. These forms must be dynamically loaded on the template. I need to write a function in my view that gets all the forms from forms.py or gets a specific form by it's name. Something similar to get_models(appName) and get_model(AppName, modelName) but for forms instead of models. How can I write it and where should I write it? in Registery or in forms or somewhere else? Here is my code: Models.py class PrimaryInfo(models.Model): Name = models.CharField(max_length=200, blank=False, null=True) #required. Must be filled by user Surname = models.CharField(max_length=200, blank=False, null=True) DateOfBirth = models.DateField('date of birth', blank=False, null=True) <Some Other fields> ... def calculateAge(self): if not self.DateOfBirth is None: thisYear = timezone.now().date().year return thisYear - self.DateOfBirth.year pass <some other functions> ... #Here come all the related tables class Jobs(models.Model): Rel = models.ForeignKey(PrimaryInfo, on_delete=models.CASCADE) Job = models.CharField(max_length=200) Age = models.IntegerField(default=0) Country = models.CharField(max_length=200) def __str__(self): return self.Job <some other related models> .... My View: def detail(request, personId): appName = urls.app_name tablesPrefix = appName + '_' person = PrimaryInfo.objects.get(pk = personId) peopledbModels = apps.get_models(appName) fieldsList = [] relatedModels = [] relationshipsDic = {} formsFileName = "write.py" parentModelForms = [] # identify which models are … -
Checking Ansible version(ansible --version) but getting following error
And Jinja2 modules Requirement already satisfied Traceback (most recent call last): File "/usr/bin/ansible", line 60, in import ansible.constants as C File "/usr/lib/python3.7/site-packages/ansible/constants.py", line 12, in from jinja2 import Template ModuleNotFoundError: No module named 'jinja2' -
SyntaxError when trying to use celery server [duplicate]
I'm trying to set up a celery server for my django project, but I'm getting a SyntaxError from one of the modules, Kombu. This is the traceback Traceback (most recent call last): File "c:\programdata\anaconda3\envs\themsclub\lib\runpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\programdata\anaconda3\envs\themsclub\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\ProgramData\Anaconda3\envs\themsclub\Scripts\celery.exe\__main__.py", line 7, in <module> File "c:\programdata\anaconda3\envs\themsclub\lib\site-packages\celery\__main__.py", line 30, in main main() File "c:\programdata\anaconda3\envs\themsclub\lib\site-packages\celery\bin\celery.py", line 81, in main cmd.execute_from_commandline(argv) File "c:\programdata\anaconda3\envs\themsclub\lib\site-packages\celery\bin\celery.py", line 793, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "c:\programdata\anaconda3\envs\themsclub\lib\site-packages\celery\bin\base.py", line 311, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "c:\programdata\anaconda3\envs\themsclub\lib\site-packages\celery\bin\celery.py", line 785, in handle_argv return self.execute(command, argv) File "c:\programdata\anaconda3\envs\themsclub\lib\site-packages\celery\bin\celery.py", line 713, in execute return cls( File "c:\programdata\anaconda3\envs\themsclub\lib\site-packages\celery\bin\worker.py", line 179, in run_from_argv return self(*args, **options) File "c:\programdata\anaconda3\envs\themsclub\lib\site-packages\celery\bin\base.py", line 274, in __call__ ret = self.run(*args, **kwargs) File "c:\programdata\anaconda3\envs\themsclub\lib\site-packages\celery\bin\worker.py", line 194, in run pool_cls = (concurrency.get_implementation(pool_cls) or File "c:\programdata\anaconda3\envs\themsclub\lib\site-packages\celery\concurrency\__init__.py", line 29, in get_implementation return symbol_by_name(cls, ALIASES) File "c:\programdata\anaconda3\envs\themsclub\lib\site-packages\kombu\utils\__init__.py", line 96, in symbol_by_name module = imp(module_name, package=package, **kwargs) File "c:\programdata\anaconda3\envs\themsclub\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen … -
Django admin inheritance, referencing child model id in parent model
I have a base model and 2 child models inheriting from base model class Module(models.Model): name = models.CharField(max_length=200, null=False) def __str__(self): return self.name class A(Module): title = models.CharField(max_length=300, null=False, verbose_name='Title') image = models.FileField(upload_to='uploads/', null=True) class B(Module): title = models.CharField(max_length=300, null=False, verbose_name='Title') sub_title = models.CharField(max_length=300, null=False, verbose_name='Title') image = models.FileField(upload_to='uploads/', null=True) This is working fine, Django creates table inside child model table that references to parent. Now, where I struggle is that there is an additional app with its own model that needs to query related parent model with its all child models. Lets assume this is my app referencing to module class class Page(models.Model): title = models.CharField(max_length=300, null=False) slug = models.SlugField(max_length=300, null=False, db_index = True) modules = models.ManyToManyField('modules.module') By this current setup, Django stores parent model id in child model table, I'm not using django on client side hence in my sql query I'd like to get the child module attached to parent, by having a reference to what child model is referencing to. Please have in mind, Parent is linked to only one model. I've looked at abstract, proxy models as well as model_utils.managers InheritenceManager but none stored child model information in parent. How do I achieve that? Thanks -
Django Template firstof + filter
I am using a Django template in my webapp, and am displaying values that are one of two things: Numbers (up to 2 digits float) The string "None" What I'd like to do is: Change "None" to 0, if value is "None". Use Float Format to ensure value is displayed as 2nd digit float Right now, I can do those separately: {% firstof myValue 0.00 %} (this outputs either the value or 0.00 if myValue = "None") {{ myValue | floatformat:2 }} (this formats the number to something like 2.70 for example, but doesn't change "None" to 0.00) Is there a way to combine the functionality of those two? -
Handling payments with paystack
I am trying to integrate paystack payment option into my project and i have been coming across so many errors on how the API works. Can anyone help me? i am kind of new in developing something that uses payments -
Django how to concatenate form data before saving to the database
I am building a budgeting web app for many users. The user creates accounts to track different values. The problem is that I cannot make a composite key and need the AccountName to be the primary key. This poses a challenge. What if users make the same account name? This will happen as some users may make a "Cash" account. My solution to this problem is to name the account in the database the AccountName + the userid. How can I modify the users AccountName in the form to be AccountName + userid? Desired AccountName examples in the database: Cash1, Cash2 models.py class Account(models.Model): DateCreated = models.DateTimeField() AccountName = models.CharField(max_length= 100, primary_key=True) UserID = models.ForeignKey(MyUser, on_delete=models.CASCADE) Type = models.CharField(max_length= 20) Balance = models.DecimalField(max_digits=19, decimal_places=8) Value = models.DecimalField(max_digits=19, decimal_places=8) Views.py @login_required def func_AccountsView(request): # This filters users accounts so they can only see their own accounts user_accounts = Account.objects.filter(UserID_id=request.user).all() if request.method == 'POST': form = AddAccount(request.POST) if form.is_valid(): account = form.save(commit=False) account.UserID = request.user account.AccountName = AccountName + str(request.user) # WHY DOES THIS NOT WORK? account.save() return redirect('accounts') else: form = AddAccount() else: form = AddAccount() data = { 'form':form, 'data': user_accounts } return render(request, 'NetWorth/accounts.html', data) forms.py class AddAccount(forms.ModelForm): ''' …