Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I round my variable "c" (representing a random number) on PyCharm, under the template folder (so .html)?
I would like to round my variable "c" (it is a randomly chosen number from my computer) in my code on PyCharm. I am on the template folder (so .html) in PyCharm and wrote this: The computer has drawn a payoff of {{ c }}. For now, when I run this very line (written on PyCharm) it gives me a number like 10.3438740 for example. I would like it to become 10. I tried using Math.round() or round() but this does not work. -
Can't install psycopg2-binary
I'm trying to install psycopg2-binary (pip3 install psycopg2-binary) inside the virtual environment of my Django project on Centos 7 with preinstalled Postgresql 12 and have the well-known error: Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. I tried to install python3-devel postgresql-libs postgresql-server postgresql-devel postgresql-contrib, but still have this error. pip3 install psycopg2, pip install psycopg2 - the same problem. -
How are 'comments' tied to 'article' in django-comments package?
In Django's own comment framework, django-contrib-comments, if I create my own comment model as below: from django_comments.models import Comment class MyCommentModel(Comment): Q: How should I associate this new comment model (MyCommentModel) with existing Article model? using attribute content_type, object_pk or content_object ? -
How do i redirect back to the login page after 10 seconds of inactivity using django?
In my settings.py I state this and the sessionId did expire but it redirect me to some random links that I never state at all instead back to the login page and will show some error, I want it to redirect back to the login page after 10 seconds of inactivity, how do I do that? My settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] SESSION_EXPIRE_SECONDS = 10 SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True SESSION_EXPIRE_AT_BROWSER_CLOSE = True My views.py def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == 'POST': if form.is_valid(): username = form.cleaned_data.get('username') # retrieve the username password = form.cleaned_data.get('password') # retrieve the password user = authenticate(username=username, password=password) # authenticate user if user is not None and user.is_admin: # authenticated if user is an admin login(request, user) return redirect('adminpage') # redirect the user to the admin page elif user is not None and user.is_customer: # authenticated if user is a customer service login(request, user) return redirect('customer') # redirect the user to the customer service page elif user is not None and user.is_logistic: # # authenticated if user is a logistic login(request, user) return redirect('logistic') # redirect the user to the logistic page else: … -
ExecutableNotFound: failed to execute ['dot', '-Tpng', '-O', 'tmp'], make sure the Graphviz executables are on your systems' PATH [closed]
mglearn.plots.plot_animal_tree() -
getting html from filter and appending in django
hi i want to know how can i get a data from filter and append it in my html.i am getting this error Uncaught SyntaxError: Unexpected token '<' html: <span id='securedata'></span> <script> window.onscroll = () => { if (window.innerHeight + window.scrollY >= document.body.offsetHeight) { document.querySelector('body').style.background = 'purple'; <!--my problem is --> $('#securedata').append("{% recommend_community_first request.user.pk %}"); } else { document.querySelector('body').style.background = 'white'; } } </script> how can i append that data from my filter without any error .Thanks -
multiple shell commands from multiple machines in python and django in parallel
I have a django project running on an Ubuntu machine which in the backend is using some shell commands with subprocess.run() and then the commands output will be redirect to a python script to convert the output to a PDF file and after building output, the pdf file will be download for the user. If i have multiple users which are using this options, the pdf output hasn't differennce for users. For Example: User1 calls option A. User2 calls option B. script C will convert the output of A and B to PDF files. the output of A and B for each user will be redirect to script C to build the pdf file. And if User1 and User2 execute the options at the same time, the output will be the same for both users and it's wrong output. It means the project is usable for only 1 user at the same time! is there anyway to solve this problem? for example multiproccessing, multi threating or something like that? -
I am using django lts version this is code of django.1 so please convert it in to django lts version please
enter image description here I am using django-lts version this is code of django.1 so please convert it to django-lts version please -
one like button likes every post with _set lookup
I am building a Simple/Easy Group App, In which users can join group and create and like posts, So i made three models :- Group , BlogPost, 'Like` (for like the blogpost). So After joining the group , I am accessing Like model with blogposts.like_set.all so users can like posts if they didn't like. So, I created a like button for every blog post, But When request.user likes a post then every post is liking. models.py class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.CharField(max_length=300) group_of = models.ForeignKey(Group, on_delete=models.CASCADE) class LikeBlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) blog_of = models.ForeignKey(User, on_delete=models.CASCADE) views.py def group_detail_view(request, group_id): obj = get_object_or_404(Group, pk=group_id) blog_posts = obj.blogpost_set.all() likePost = LikeBlogPost.objects.filter(blog_of__in=blog_posts, user=request.user).first() context = {'obj':obj,'blog_posts':blog_posts,'likePost':likePost} return render(request, 'group_detail_view.html', context} group_detail_view.html {% for allPosts in blog_posts %} {{ allPosts.body }} {% if request.user == likePost.user %} <button name='submit' type='submit'>UnLike</button> {% else %} <button name='submit' type='submit'>Like</button> {% endif %} {% endfor %} What i am trying to do ? :- I am trying to like only one post at a time, But now if i like one post then all posts are liking. What have i tried ? :- First I … -
How to add a custom button in a registered model in django admin site
Can anyone guide me in the right direction on how to put a button next to the delete button ? I want to put a confirm and deny button next to it, that when I click it, it will send an email to the user that his/her application is accepted or denied. I've searched online for a solution and also read some similar questions here, but I am not sure whether or not those are right things to go to. -
Django crontab not running permanently on google ubuntu instance
I am using crontab in Django(3.1.8) on the google VM ubuntu instance. ### settings.py INSTALLED_APPS = [ 'django_cron', ... ] CRONJOBS = [ ('*/5 13-20 * * 1-5', 'app.cron.cron_function'), ('1 12 * * 1-5', 'app.cron.cron_function2'), ('*/1 13-20 * * 1-5', 'app.cron.cron_function3'), ('*/5 13-20 * * 1-5', 'app.cron.cron_function4'), ] ### app/cron.py def cron_function(): something doing ... def cron_function2(): something doing ... def cron_function3(): something doing ... def cron_function4(): something doing ... while I add crontab with python manage.py crontab add. so this cron job is run only once. so how to run the cron jobs functions always. -
Python - How to check wheter a crs (srid) is valid
I have a form with a crs(Coordinates Reference System) input field that user should fill. I would like to avoid wrong crs. Is there a way to test if the crs inputed is valid ? -
Add-form instead of plus sign in manytomany inline - django admin
I would like to get rid of these plus button and select and instead of this I would like to implement a form that could allow to create a new manytomany item. I've seen a lot of examples but I've no idea why it doesn't work with my code. class TargetShift(models.Model): shift = models.ForeignKey(Shift, on_delete=models.PROTECT) monday = models.PositiveIntegerField(default=0) tuesday = models.PositiveIntegerField(default=0) wednesday = models.PositiveIntegerField(default=0) thursday = models.PositiveIntegerField(default=0) friday = models.PositiveIntegerField(default=0) saturday = models.PositiveIntegerField(default=0) sunday = models.PositiveIntegerField(default=0) class ManHoursTarget(models.Model): week = models.CharField(max_length=20, unique=True) targets = models.ManyToManyField(TargetShift) class TargetShiftInline(admin.TabularInline): model = ManHoursTarget.targets.through extra = Shift.objects.count() @admin.register(ManHoursTarget) class ManHoursTargetAdmin(admin.ModelAdmin): inlines = (TargetShiftInline,) form = ManHoursTargetAdminForm @admin.register(TargetShift) class TargetShiftAdmin(admin.ModelAdmin): list_display = tuple(field.name for field in TargetShift._meta.fields)[1:] -
loading data from django api into nextjs gives cors error
data i want to load {"status": "ok", "items": ["{\"id\": 1, \"user\": \"anoushk77\", \"title\": \"My Web roadmap for 2022\", \"markdown_data\": \"# My Web dev starter resources\\r\\n---\\r\\n - [Freecodecamp](https://www.freecodecamp.org/)\\r\\n - [Frontend roadmap](https://roadmap.sh/)\", \"upvotes\": 1, \"downvotes\": 0, \"categories\": \"Web Dev\", \"cat_relation\": 1}"]} My code const [title, setTitle] = useState(""); useEffect(() => { async function getTitle() { const res = await axios.get("https://kunaikit.herokuapp.com/api/getkit/"); setTitle(JSON.parse(res.data['items'][0])['title']); } getTitle(); }, []); Ive been on this problem for the last 2 days, i'm new to next.js so any help would be appreaciated, I've seen a lot of tutorials doing exactly what i did and it seems to work for them, not sure why like this one tutorial -
DJANGO static url linked to wrong folder
I am building an app with Django but I got a problem. I am using DEBUG= True I created the folder run/static where all the static files are moved when I use the command collectstatic ( so this works well) I have this in the settings STATIC_URL = '/static/' STATIC_ROOT = join(PROJECT_ROOT, 'run', 'static') Now, for testing the connection with the static folder, I tried to add a file in the path testapp/static/testapp/testfile.css After running collect static, correctly, the file is moved to run/static/testapp/testfile.css Perfect. The problem is that I discovered that when I run the server, the URL http://127.0.0.1:8000/static/testapp/testfile.css doesn't read the files in the correct folder (/run/static...) but it reads them from /testapp/static... indeed if I change the name of the file in the run folder to testfile1.css and try the URL http://127.0.0.1:8000/static/testapp/testfile1.css it doesn't find any file, but if I change the name of the file currently in /testapp/static/testapp/ to testfile2.css and then, without running collectstatic, try the URL http://127.0.0.1:8000/static/testapp/testfile2.css it works. This means that static URL is "connected" to all the static folders of every app (like testapp/static/testapp/) instead of the static folder that I choose with STATIC_ROOT (run/static/testapp/). IS it clear my problem? What do … -
problem with incrementing like when using infinite scroll in django
i want to use infinite scroll in django and it works but for some reason when i arrive to "?page=2" when i like a post the value is not incrementing here is my views.py: @login_required def recommendation_posts(request): if request.method == 'GET': <-- skip ---> posts = list(chain(profile_posts,community_posts)) page = request.GET.get('page', 1) paginator = Paginator(posts, 5) try: numbers = paginator.page(page) except PageNotAnInteger: numbers = paginator.page(1) except EmptyPage: numbers = paginator.page(paginator.num_pages) return render(request, 'profile/load_post.html',{'posts':numbers}) load_post.html: {% extends 'profile/base.html' %} {% load static %} {% block content %} <div class="infinite-container"> {% for post in posts %} {% if post.is_community %} <br> <div class="w3-container w3-card w3-white w3-round infinite-item"> <a target="_blank" href="{{ post.community.image.url }}"> <img src="{{ post.community.image.url }}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:40px;height:40px;border-radius:50%;"></a> <a href="{% url 'show_community' post.community.pk %}">{{ post.community.name|title|truncatechars_html:"38" }}{% if post.community.is_official %} <span style="color:blue;" class="glyphicon glyphicon-ok-circle"> </span>{% endif %}</a> <br> <small class="w3-opacity">{{ post.today }}</small> <hr class="w3-clear"> {% if post.video %} {% video post.video '100% x 100%' %} {{ post.video.url }} {% endif %} {% if post.file %} <a href="{{ post.file.url }}"> <img src="{% static 'images/file-pdf.svg' %}" style="width:30px;height:20px;" class="w3-left"> <h5> {{ post.filename|truncatechars_html:"40" }} </h5> </a> <br> {% endif %} <button type="button" class="btn btn-default btn-sm"> {% with post.comment_set.count as count_comments %} <a href='{% url 'comment' … -
I successfully created superuser using django, but get this error "127.0.0.1 didn’t send any data."
I successfully created a superuser using django, but get this error "127.0.0.1 didn’t send any data." -
How to return the whole object data with Django objects.filter?
I search for a user in my views: user = User.objects.filter(id=id).first() print(user) This returns just the username of the user. I know I can access other data like the nickname with user.nickname but I need to make a json object of the user data and would like to know is there some way I can access the whole user object at once and not one by one? -
I got error (root) Additional property django is not allowed , when run django in pycharm
I got this error since this morning. (root) Additional property django is not allowed I didn't change my code since last night. The error has occured today. It seems cause by docker-compse.yaml . This is my yaml file. version: "3" services: django: container_name: image_maker image: image_maker:latest volumes: - .:/docker - ./log:/tmp/ ports: - 8003:8080 working_dir: /docker/app environment: - DEBUG=True - LOCAL_DB=True networks: - my_network networks: my_network: external: true I didn't changed it a few days. And also I run another django project. It has same error. (root) Additional property *** is not allowed So I checked my all project. It got same error. I thins this is not yaml file error. It is interpreter error on Pycharm. When I open Configure Remote Python interpreter, Service can select network and service. This is strange. The dropdown should be django. I don't no why the dropdown can't show correct services. I restarted Pycharm and my Mac. However this problem still beeing. Please help me. Pycharm 2021.1.1 MacOS 11.5.2 Docker Desktop Version 4.0.0 (4.0.0.12) Docker version 20.10.8, build 3967b7d -
from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible'
When I try to make the site live in SSH. I'm getting this error File "/home/new_env/lib/python3.6/site-packages/rest_framework/authtoken/models.py", line 6, in <module> from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' I recently changed the django version from 2.1 t0 3.0.7 -
Cannot install mammoth==1.4.17 via docker
When trying to install mammoth via docker for a django project I get the errror ERROR: Cannot install mammoth==1.4.16 and mammoth==1.4.17 because these package versions have conflicting dependencies. The conflict is caused by: The user requested mammoth==1.4.17 The user requested mammoth==1.4.16 To fix this you could try to: loosen the range of package versions you've specified remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies ERROR: Service 'app' failed to build : The command '/bin/sh -c pip install -r /requirements.txt' returned a non-zero code: 1 -
Most efficient method for "streaming" (stock) data to Web-Frontend
I'm currently working on a Stock Market Web-Application, which bascially allows users to buy / sell shares at a current rate. As the share-prices have to be updated in short intervals on the client-side, I'm in need of an efficient solution for transmitting the updated stock prices. So far I've been using Websockets for similiar functionalities requiring Real Time Updates, but before I make a too hasty decision, I'd like to know whether there's a better approach for this. -
Why no rollback hook?
A rollback hook is harder to implement robustly than a commit hook, since a variety of things can cause an implicit rollback. For instance, if your database connection is dropped because your process was killed without a chance to shut down gracefully, your rollback hook will never run. But there is a solution: instead of doing something during the atomic block (transaction) and then undoing it if the transaction fails, use on_commit() to delay doing it in the first place until after the transaction succeeds. It’s a lot easier to undo something you never did in the first place!enter code here -
How to remove slider from Django-admin panel
Yesterday I tried to upgrade all my pip packages and after that I have got the problem with this slider. Whenever I try to open or create instance of some model it appears. I have tried to rollback packages. Delete python and reinstall it. Tried to create new project, but it seems the problem is in admin templates. Slider Python: Python 3.9.7 pip freeze: appdirs==1.4.4 asgiref==3.4.0 autopep8==1.5.7 certifi==2021.5.30 cffi==1.14.6 charset-normalizer==2.0.4 cryptography==3.4.8 defusedxml==0.7.1 distlib==0.3.2 Django==3.2.5 django-allauth==0.45.0 django-cors-headers==3.8.0 django-rest-auth==0.9.5 djangorestframework==3.12.4 filelock==3.0.12 idna==3.2 mysqlclient @ file:///D:/Stol/GitHub/smotors/mysqlclient-1.4.6-cp39-cp39-win_amd64.whl oauthlib==3.1.1 Pillow==8.3.1 psycopg2==2.9.1 pycodestyle==2.7.0 pycparser==2.20 PyJWT==2.1.0 python3-openid==3.2.0 pytz==2021.1 requests==2.26.0 requests-oauthlib==1.3.0 six==1.16.0 sqlparse==0.4.1 toml==0.10.2 urllib3==1.26.6 virtualenv==20.4.7 -
How can I add a new parent to Django Content Type Model
So, I have written a library to sync the data on Django admin panel to the s3 bucket. But, to do that, the models should inherit from a BaseSyncModel that I've created. To work around it, I created a new model called BaseContentTypeModel, like that: #content_type.app class BaseSyncModel(BaseSyncModel, ContentType): pass class BasePolymorphicModel(PolymorphicModel): polymorphic_ctype = models.ForeignKey( BaseContentTypeModel, null=True, editable=False, on_delete=models.CASCADE, related_name="polymorphic_%(app_label)s.%(class)s_set+", ) class Meta: abstract = True There is only one model that inherits from the PolymorphicModel, and it is like that: class Product(BasePolymorphicModel, UUIDModel, PriceModel, AdminWriteMixin): """Product generic model.""" price_old = models.PositiveIntegerField( default=0, help_text="old price in cents", ) name = models.CharField( max_length=128, ) slug = models.SlugField( max_length=256, unique=True, ) is_active = models.BooleanField( default=True, ) But when I had run the migrate command, it returned the following error: django.db.utils.IntegrityError: insert or update on table "product_product" violates foreign key constraint "product_product_polymorphic_ctype_id_44f73554_fk_content_t" DETAIL: Key (polymorphic_ctype_id)=(8) is not present in table "content_type_basecontenttypemodel". I also tried to execute a forward function on migration file to copy every row on ContentType model to BaseContentTypeModel: def forwards_func(apps, schema_editor): old_contenttype = apps.get_model("contenttypes", "ContentType") new_contenttype = apps.get_model('content_type', "BaseContentTypeModel") db_alias = schema_editor.connection.alias old_objects = old_contenttype.objects.using(db_alias).all() for object in old_objects: nct_obj = new_contenttype(contenttype_ptr_id=object.id) nct_obj.save() class Migration(migrations.Migration): initial = True dependencies = …