Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dgango + Nginx + Docker no static data in admin pannel
I am trying to run django app in docker (nginx, gunicorn ...) on local machine It's ok, but I don't see static data. In docker logs I see error: nginx_1 | 2022/01/06 00:52:32 [error] 28#28: *5 open() "/var/www/html/static/admin/css/responsive.css" failed (2: No such file or directory), client: 172.24.0.1, server: localhost, request: "GET /static/admin/css/responsive.css HTTP/1.1", host: "0.0.0.0", referrer: "http://0.0.0.0/admin/login/?next=/admin/" How can I solve the problem? My code settings.py (I use standard tools to work with static data) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') nginx-conf.conf upstream app { server django:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://django:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /var/www/html/static/; } } docker-compose.yml version: '3.9' services: django: build: . # path to Dockerfile command: sh -c "gunicorn --bind 0.0.0.0:8000 potok.wsgi:application" volumes: - .:/project - static:/project/static expose: - 8000 environment: - DATABASE_URL=XXXX - DEBUG=1 db: ... nginx: image: nginx:1.19.8-alpine depends_on: - django ports: - "80:80" volumes: - static:/var/www/html/static - ./nginx-conf.d/:/etc/nginx/conf.d volumes: pg_data: static: -
how to auto-populate slug field in django forms
i want to allow users of a website create blog post from a form that i made, but the slug field does not get populated automatically from the frontend but from the backend (admin page) it does get populated, and that is not what i want. I want the slug field to get populated with the title when the users want to create a post e.g this-is-an-example please how do i go about it models.py class Blog(models.Model): title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title") slug = models.SlugField(unique=True) content = RichTextField() image = models.ImageField(upload_to="blog-images/%Y/%m/%d/", verbose_name="Post Thumbnail") def get_absolute_url(self): return reverse("blog:blog-details", args=[self.slug]) def __str__(self): return self.title views.py @login_required def new_post(request): info = Announcements.objects.filter(active=True) categories = Category.objects.all() if request.method == "POST": form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): form.instance.creator = request.user form.save() # ← no commit=False messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!') return redirect('blog:home') else: form = BlogPostForm() context = { 'form': form, 'info': info, 'categories': categories } return render(request, 'blog/newpost.html', context) forms.py NOTE if i remove the 'slug' from the field it throws an error saying that slug is needed class BlogPostForm(forms.ModelForm): class Meta: model = Blog fields = ('title', 'slug', 'content', 'image', 'category') newpost.html <form … -
Heroku Django Deployment Static Files
I have never deployed a Django app on Heroku, and I have followed the guide, but for some reason, the error persists. Please see the error from Heroku -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_c294883a/manage.py", line 22, in <module> main() File "/tmp/build_c294883a/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 323, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_c294883a/static' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ****** Collectstatic environment variables: PYTHONUNBUFFERED=1 PKG_CONFIG_PATH=/app/.heroku/vendor/lib/pkg-config:/app/.heroku/python/lib/pkg-config: DEBUG_COLLECTSTATIC=1 BPLOG_PREFIX=buildpack.python PWD=/tmp/build_c294883a HOME=/app LANG=en_US.UTF-8 SOURCE_VERSION=4c146a486e7f836f8812c8895e52aab3dcd55a6f REQUEST_ID=8b6dfaf2-5d01-8e0b-c2cd-2e8220c2bf89 ENV_DIR=/tmp/d20220105-49-m5bl0u PYTHONPATH=. CPLUS_INCLUDE_PATH=/app/.heroku/vendor/include:/app/.heroku/python/include: BIN_DIR=/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin … -
SMTp Django email reminder for expired drugs
I would like to have a function on my app where people are notified when the expiry date of a drug is approaching. Like 2 months before it expires. I am currently using smtp for my emails but I would need help writing a view for this and signals.py -
Using fetch results to return element to component - React
I have a web app built with python/django and I'm trying to use React for the front-end. The app has a template with an empty div (#profile) that is populated via React. There is an attribute on the template that is used to fetch data from the back-end. The data is passed as props to the main function/component (Profile) to instantiate the state. let username = document.getElementById('profile').getAttribute('data-profile'); fetch(`/getFollow/${username}`) .then(response => response.json()) .then(results => { ReactDOM.render(<Profile profile={username} followers={results.follower_count} following={results.following_count}/>, document.querySelector("#profile")); }) The Profile component returns the html elements and contains another function/component (FollowButton) function Profile(props) { const [state, setState] = React.useState({ follower_count: props.followers, following_count: props.following, profile: props.profile }); return ( <div> <br></br> <div class="row justify-content-center"> <h2 id="profile">{state.profile}</h2> <span> <FollowButton profile={state.profile}/> </span> </div> <div class="row justify-content-center"> followers: {state.follower_count} | following: {state.following_count} </div> <br></br> </div> ); } The FollowButton used the passed in prop to make another fetch and based on the results dynamically return a button element. function FollowButton(props){ fetch(`/getFollow/${props.profile}`) .then(response => response.json()) .then(results => { if (results.isFollowing == "True"){ //Return Following button //console.log('following'); <button class="badge badge-pill ml-2 btn-primary">Following</button> } else if (results.isFollowing == "False"){ //Return Follow button //console.log('follow'); <button class="badge badge-pill ml-2 btn-secondary">Follow</button> } else if (results.isFollowing == "Self"){ //No button … -
form.is_valid() on templateview in create case
I have a Product which looks like this: class Product(models.Model): data = models.JSONField() number = models.PositiveIntegerField() store = models.ForeignKey(Store, on_delete = models.CASCADE) and I create a form dynamically that I fill with the values from the database in the update case like this: class ProductUpdateView(TemplateView): def post(self, request, *args, **kwargs): obj = Product.objects.get(pk = kwargs["pk"]) form = ProductForm(request.POST or None, request.FILES, product = obj) if form.is_valid(): for key in form.cleaned_data: ... so far so good, I can use the forms clean method this way to validate my data and save updated data. But now for the create case: I create an empty form first (this works well) and enter some data, then I post it: class ProductCreateView(TemplateView): template_name = "store/new_product.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) store = Store.objects.get(user = self.request.user) tmp_product = Product.objects.filter(store = store).last() product_data = {"number": tmp_product.number + 1} for key, value in tmp_product.data.items(): product_data[key] = None context["form"] = ProductForm(product = tmp_product, initial = product_data) return context def post(self, request, *args, **kwargs): obj = Product.objects.create(number = request.POST["number"], data = {}) form = ProductForm(request.POST, request.FILES, product = obj) if form.is_valid() ... in above ProductCreateView the get_context_data() method works well. But in the post() method the ouptut of form.is_valid() … -
Python RegEx: How to conditionally match multiple optional ending characters in a URL
I have to match URLs in my Django re_path function. The structures to be matched are as follows: Any URL must start with either /profile or /user/profile Any URL must end with either profile , or profile/ or profile/blabla Here below the examples for allowed URLs: /profile /profile/ /profile/asd /profile/asd/ /user/profile /user/profile/ /user/profile/asd /user/profile/asd/ I tried the following, but it fails: re_path(r'^profile/?.*$', views.my_view) Any help is appreciated, thanks! -
Application Error while my Django app successfully deployed
I am leaving a question of why I got an application error after deploying Django successfully. It seems like I could deploy my Django app to Heroku, but I got an error when I wanted to see my app by pressing the "open app" button on the Heroku dashboard. I am ignoring the database, which is Postgres, now. If I only care about the app without any data, I think I should be able to run the code on the Internet. Here is my source code on github, so I want you to check this out. Thanks so much in advance. -
Access domain name inside model function
I have this model class ArticleWithLinks containing method bodyWithLinks(). It returns article's body(text) + strictly formatted string of links formated like: '[3]: http://my.doma.in/articles/some-slug "Good article!"' joined by '\r\n'. For sure, it could be done in more elegant manner but... anyway ;-) It has to be done this way because body+links will be later together processed by markdown while rendering template. Referenced link details like [id] or some-slug or "Title" (packed in other class) I can easily obtain within models.py and even dynamically add /articles/ using get_absolute_url() method. However, as you probably know, this method returns URL without the domain name. I fully understand the concept that models shall not know about context of their usage (request) but I have to inject it before I pass it to markdown processor called in view's template. What is the best way to do that? Pass request (or even better - domain only) to model's bodyWithLinks() as a parameter and join it inside. I've googled it and found something like simple template tag Somehow retreive it inside model function - I've seen Site class from contrib, that contains domain as well Somehow wrap bodyWithLinks() model's method inside views.py and pass it to template with … -
Django post api call autofill request.user to user field
serializer.save(user=request.user.profile, post=post) is not taking effect. works in a different view. I have no idea why its not working. Could you please help me out. Thank you //This works class CurrentUserPostList(generics.ListAPIView): serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] search_fields = ['title', 'content'] filter_backends = (filters.SearchFilter,) def get_queryset(self): user = self.request.user return Post.objects.filter(user=user.profile) def post(self, request, *args, **kwargs): serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=request.user.profile) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) // This doesn't work class CommentList(generics.ListAPIView): serializer_class = CommentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_queryset(self): return Post.objects.get(id=self.kwargs.get('pk')).comments.all() def post(self, request, pk, format=None): post = get_object_or_404(Post, pk=pk) serializer = CommentSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=request.user.profile, post=post) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) // models.py class Comment(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) user = models.ForeignKey(Profile, on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) content = models.TextField(null=True, blank=True) last_modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.author) -
How to save an abstractuser using multiple forms
I have 2 forms: 1 usercreation form and one that contains the verified file. I want to add 2 fields(verified,is_doctor) with the first form and save it to create a abstractuser. I have tried the following but it ends up blank in my db. {'verified': <UploadedFile: app.jpg (image/jpeg)>} userCreate.verified=form_list[1].cleaned_data.get('verified') userCreate.is_doctor=True views.py from django.core.files.storage import FileSystemStorage import os from django.conf import settings class DoctorWizard(SessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, '/doctor/')) template_name = "registration/signup.html" form_list = [SignUpForm,verify] def done(self, form_list, **kwargs): process_data(form_list) userCreate = form_list[0] userCreate.verified=form_list[1].cleaned_data.get('verified') userCreate.is_doctor=True userCreate.save() username = userCreate.cleaned_data.get('username') raw_password = userCreate.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) if user: auth_login(self.request, user) return redirect('home') forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) class verify(forms.Form): verified = forms.ImageField(required=True) class Meta: model = Profile fields = ('verified',) models.py class Profile(AbstractUser): bio = models.TextField(max_length=100, blank=True) phone_number = PhoneNumberField(max_length=25, region="US") birth_date = models.DateField(blank = True, null = True) is_doctor = models.BooleanField(default=False) verified = models.ImageField(upload_to='media/doctor') date_created = models.DateTimeField(auto_now_add=True) avatar = models.ImageField(default='default.png', upload_to='') #status = models.BooleanField(default=False) -
When sorting a Django queryset against fields on the related model, the rows go missing. Any idea why?
When trying to sort by related model date field, some of the queryset rows go missing. cur_objs=Currency.objects.all().order_by('fxrates__date') cur_objs=Currency.objects.all().order_by('-fxrates__date') FYI date is not unique in FxRates model. But it should still work right? -
Filtering by ForeignKey field in DRF
I have a few models: class Page(models.Model): date = models.DateField("Post date") title = models.CharField(max_length=255) chinese = models.TextField() base = models.TextField() published = models.BooleanField() premium = models.BooleanField() json = JSONField(default=dict, null=True, ) category = models.ManyToManyField( Category) calculated_hsk = models.DecimalField( default=1, max_digits=3, decimal_places=2) display_hsk = models.ForeignKey(HSKLevels, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to=imageFile, null=True, max_length=255) sound = models.FileField(null=True, max_length=255) url = models.URLField(max_length = 255, null=True) class Sentence(models.Model): sentence = JSONField(default=dict, null=True, ) article = models.ForeignKey( Page, on_delete=models.SET_NULL, null=True ) language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True) class Translation(models.Model): translation = models.TextField() sentence = models.ForeignKey( Sentence, on_delete=models.SET_NULL, null=True ) language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True) I want to be able to filter by sentence language, so that I only get the current sentence languages that I want. I have a DRF endpoint setup like this: class ArticleView(generics.ListAPIView): queryset = Page.objects.select_related().all() serializer_class = ArticleSerializer filter_backends = (filters.DjangoFilterBackend,) pagination_class = LimitOffsetPagination ordering_fields = ['date'] filter_class = MultiValue And a filter like this: class MultiValue(filters.FilterSet): published = filters.BooleanFilter(field_name='published') premium = filters.BooleanFilter(field_name='premium') category = NumberInFilter(field_name='category', lookup_expr='in') calculated_hsk = NumberInFilter(field_name='calculated_hsk', lookup_expr='in') display_hsk = NumberInFilter(field_name='display_hsk', lookup_expr='in') start = filters.IsoDateTimeFilter(field_name="date", lookup_expr='gte') end = filters.IsoDateTimeFilter(field_name="date", lookup_expr='lte') language = filters.CharFilter(field_name="sentence.language.lang_code", lookup_expr='in') And serializers like this: class SentenceSerializer(serializers.ModelSerializer): class Meta: model = Sentence depth = 1 fields = … -
'member_descriptor' object cannot be interpreted as an integer when looping through the timedelta.day
Am trying to filter through the number of days a users birthday is coming up. but whenever i filter through users upcoming birthdays for some reason I keep hitting this error 'member_descriptor' object cannot be interpreted as an integer, I have looked on stack overflow to find a solution but so far all seems not to fix my current challenge. I think the error stems from the for loop with deltatime.days, How best can i loop through the days in deltatime.days ? def upcoming_birthdays(request): birthdays_today = [] friend_list = FriendList.objects.get(user=request.user) #get all people with birthday today for p in friend_list.friends.all(): if p.isBirthdayToday(): birthdays_today.append(p) #get and format today's date today = date.today() suffix = _getSuffix(today) today_date = '{}{} {}'.format(today.day, suffix, today.strftime("%B")) # All upcoming birthdays friend_list = FriendList.objects.get(user=request.user) birth_list = friend_list.friends.all().distinct() today = date.today() upcoming_date_list = [] upcoming_date_list.extend(list(birth_list.filter(birth_date__month=today.month, birth_date__day=today.day))) next_day = today + timedelta(days=1) # this where am looping through the days for upcoming birthdays for day in range(0, (timedelta.days)): upcoming_date_list.extend(list(birth_list.filter(birth_date__month=next_day.month, birth_date__day=next_day.day, birth_date__isnull=True))) next_day = next_day + timedelta(days=1) #return template plus context context = { 'birthdays_today': birthdays_today, 'today_date': today_date, 'upcoming_date_list': upcoming_date_list, } return render(request, 'account/birthdays.html',context) here is the traceback exception Traceback (most recent call last): File "C:\Users\Umar\Desktop\dreams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner … -
how to change width of list rows in django admin
I'm using Django Grappelli for my Django admin theme, it works great but when I open a list of objects inside some modules it only takes about 25% of the width of the screen. check the screenshot what ti need is to make it 100% width and remove this unused space -
django-social-auth not redirecting to provided next query param for SAML login
I have a django application that uses django-social-auth and allows for three types of SSO authentication, Google, Office 365, and SAML2.0. In the case of SAML2.0, the application allows the end user to specify their own IdP, and to enable that, we have a custom Database SAML Auth class, that allows us to store the users IdP information in the database, and log the user in. This works as expected, and users can sign in with SAML, Google, or Office 365, no problem. The challenge is when I need to be redirected to a specific URL once the login has completed. This is working as expected for Google and Office 365, but not for SAML login. As an example, I have a mobile application that authenticates via OAUTH to the django web application. When that mobile application starts its oauth flow, it goes to the authorization URL, and the gets forwarded to login. The path looks something like this: https://myapp.com/oauth/authorize/?client_id=something https://myapp.com/login/?next=/oauth/authorize/?client_id=something (after selecting sign in with SAML login method) https://myapp.com/login/subdomain/?next=/oauth/authorize/?client_id=something Redirect to IdP Redirect back to assertion consumer url https://myapp.com/login/sso/saml/complete/ Redirect to account page https://myapp.com/manage/ (not https://myapp.com/oauth/authorize/?client_id=something as expected) The frustration of course is that this breaks the oauth flow … -
Nginx + Django: ModuleNotFoundError: No module named 'app'
I am trying to run my Django application with Nginx and Gunicorn in Docker In docker compose logs i have the following error: (full log: https://pastebin.com/EXd3Bsii) File "/usr/local/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app django_1 | mod = importlib.import_module(module) django_1 | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module django_1 | return _bootstrap._gcd_import(name[level:], package, level) django_1 | File "<frozen importlib._bootstrap>", line 1030, in _gcd_import ... django_1 | File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked django_1 | ModuleNotFoundError: No module named 'app' How can I solve the problem? Should I specify wsgi configuration? My code wsgi,py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'potok.settings') application = get_wsgi_application() nginx-conf.conf upstream app { server django:8000; } server { listen:80; server_name: localhost; location / { proxy_pass http://app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect_off; } location /staticfiles/ { alias /var/www/html/staticfiles/; } } docker-compose.yml version: '3.9' services: django: build: . # path to Dockerfile command: sh -c "gunicorn --bind 0.0.0.0:8000 app.wsgi" volumes: - .:/project - static_data:/project/static expose: - 8000 environment: - DATABASE_URL=postgres://postgres:XXXXXXXXX@localhost:5432/lk_potok_2" - DEBUG=1 ... nginx: image: nginx:1.19.8-alpine depends_on: - django ports: - "80:80" volumes: - static_data:/var/www/html/static - ./nginx-conf.d:/etc/nginx/conf.d volumes: pg_data: static_data: -
Twitter Follwers post to database
Im trying to capture daily and record the number of Twitter followers a handle has and add the date and number to the data base. I have a simple function that gets the numbers but I'm not sure how I update the database def get_twitter_followers(request,twitter_handle): today = now().date() consumer_key = "#######################" consumer_secret = "###########################" access_token = "#####################" access_token_secret = "####################" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) user = api.get_user(screen_name=twitter_handle) count = (user.followers_count) return count,today class SocialMedia(models.Model): project_name = models.ForeignKey(Project, on_delete=models.CASCADE) capture_date = models.DateTimeField(blank=True, null=True) twitter_count = models.IntegerField() def __str__(self): return str(self.project_name) I want to set this up to run on a schedule, but for now, I just want to capture and POST to the database may be just using a button on my app. I'm not sure how to save() to the model? Thanks -
React connection to Django
There is a built React project with the following file structure: structure How can I include it to my django app? -
select all columns from a table where the combination of 3 fields is unique
i'm trying to select all entries in a table with multiple columns where the combination of 3 specific columns are distinct using django ORM with MySql backend. id first_name last_name n_children some_stuff other_stuff date 1 john silver 2 any any 2021-01-01 2 john silver 3 any any 2021-01-01 3 john white 2 some some 2021-01-01 4 john silver 2 some some 2021-01-02 I need to select all rows where the combination of "first_name", "last_name" and "n_children" is unique, prioritizing the most recent entries. In this example, the result should be rows with id [2,3,4]. what i've tried qs = Table.objects.all().order_by('-date').annotate( unique_value=Concat('first_name','last_name','n_children', output_field=TextField()) ).distinct('unique_value') But this does not work because i'm using mysql and i get this error django.db.utils.NotSupportedError: DISTINCT ON fields is not supported by this database backend Also tried Table.objects.all().order_by('-date').values( 'first_name','last_name','n_children' ).distinct() But this returns only the unique fields, and i need all of them. -
Disable button until on-demand Celery task runs
Continuation question to my previous problem. I have a button in the Django template that triggers a Celery task. I want to disable the button after the button is clicked. It is a resource-heavy task, and definitely clicking multiple times must be prevented. My initial idea was to have two buttons, and conditionally show one or the other, depending on if the task is running or not. I would somehow (not figured out how yet), using AsyncResult(str(task)).status = "SUCCESS" pass the resulting boolean to the template. Then show the disabled button if False, otherwise the original clickable button. template.html {% if importEnabled == True %} <a class="btn btn-primary btn--full" id="id_import_data_btn" href=" {% url "import_data" company.company_id %}">Import Data</a> {% else %} <a class="btn btn-primary btn--full" disabled="True">Importing Data (button disabled)...</a> views.py def trigger_import_data(request, company_id): task = import_data_for_company.delay(company_id) importEnabled = AsyncResult(str(task)).status == "SUCCESS" return HttpResponseRedirect(reverse_lazy("edit-company-profile")) My second idea was to use JS in the template and disable the button after clicking it. Here I could make the button not function (but not disabled) after click, but it also didn't trigger the celery task, which is bad. Then I tried setting the boolean to session storage, so I could determine the button showing in … -
I can't install psycopg2 in my virtual environment
I bought a book Django for professionals and I am currently on 2. chapter PostgreSQL. I have django installed in my virtual environment and my project is in docker as you can see from code below. When I try to install psycopg I get an error: Warning: Python 3.10 was not found on your system... Neither 'pyenv' nor 'asdf' could be found to install Python. You can specify specific versions of Python with: $ pipenv --python path/to/python. I run command: docker-compose exec web pipenv install psycopg2-binary==2.8.5 My Dockerfile is ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system COPY . /code/ My docker-compose.yml file is version: "3.9" services: web: build: . command: python3 /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 environment: - "POSTGRES_HOST_AUTH_METHOD=trust" -
Django-admin command error Unable to start project
I am trying to start a project in a virtual environment using the django-admin command. The error I get for django-admin startproject [name] [path] is Traceback (most recent call last): File "C:\Program Files\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Program Files\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\%CurrentUser%\Documents\Dev\Django\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\management\__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\management\base.py", line 417, in execute output = self.handle(*args, **options) File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\management\commands\check.py", line 63, in handle self.check( File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\management\base.py", line 438, in check all_issues = checks.run_checks( File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\core\checks\templates.py", line 29, in check_string_if_invalid_is_string for conf in settings.TEMPLATES: File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\conf\__init__.py", line 84, in __getattr__ self._setup(name) File "C:\Users\%CurrentUser%\Documents\Dev\Django\lib\site-packages\django\conf\__init__.py", line 65, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This just started after I had deleted my old project to start again using a comprehensive tutorial. Thanks. -
Django update other user account fields through Model Form (when logged in as admin)
I am building a django project that allows users to singup and then post projects. Apps include a 'users' app and a 'projects' app. I am using @signals so that 'users' create/edit a Profile and the @signals ensure that the underlying django User model is always in synch with the Profile model contained in the 'users' app. I have one Profile for the superuser and this is set up to not only access its own 'user profile' and 'project posts' that it may post, but is also set up to review the projects posted by other users before they can be seen in the public feed of 'project posts'. In the Project model (within the projects app models.py) i have a field called 'is_approved' with a default value of false and 'project posts' are only visible in the public feed after the superadmin has used its template view of a model form to update 'is_approved' from False to True. Each 'project post' includes a Profile field as a foreign key (one-to-many) The above is working very well - as the superuser can be the sessionid authenticated user and yet update the 'project posts' that belong to a different profile. My … -
AttributeError: 'set' object has no attribute 'items' Error (Djngo Rest Api)
The following code has been written but still, the following error will happen: VIEWS PAGE from django.http.response import HttpResponse from django.shortcuts import render from rest_framework import serializers,status from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import AccountSerializer import requests, json # Create your views here. def home(request): return render(request,'register.html') def register(request): return render(request,'register.html') def login(request): return render(request,'login.html') @api_view(['POST']) def registeruser(request): if request.method == "POST": SaveSerialize = AccountSerializer(data=request.data) if SaveSerialize.is_valid(): SaveSerialize.save() return Response(SaveSerialize.data,status=status.HTTP_201_CREATED) return Response(SaveSerialize.data,status=status.HTTP_404_BAD_REQUEST) def insertemp(request): if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') gender = request.POST.get('gender') pass1 = request.POST.get('password1') pass2 = request.POST.get('password2') if pass1 == pass2: password = pass1 address1 = request.POST.get('address1') address2 = request.POST.get('address2') city = request.POST.get('city') branch = request.POST.get('branch') address = f'{address1} {address2} {city} {branch}' data = { 'name':name, 'email':email, 'gender':gender, 'password':password, 'address':address, } headers={'Content-Type: application/json'} read = requests.post('http://127.0.0.1:8000/registeruser', json=data, headers=headers) return render(request,'register.html') else: return render(request,'register.html') This is the serializer page: SERIALIZER PAGE: from rest_framework import serializers from .models import Account class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = "__all__" MODELS PAGE: from django.db import models from django.db.models.base import Model # Create your models here. class Account(models.Model): name=models.CharField(max_length=500) email=models.EmailField(max_length=254) gender=models.CharField(max_length=20) password=models.CharField(max_length=100) address=models.TextField() def __str__(self): return self.name URLS PAGE: from django.contrib import admin …