Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 = … -
CommentForm design question about Django-comments package
In Django's own comment framework, django-contrib-comments, it has below class defined: In models.py, class Comment (CommentAbstractModel): is defined. In forms.py, class CommentForm (CommentDetailsForm): is defined. Q: since the comment framework is a comment-db-table driven package, why not we use ModelForm to create forms from models, instead of redundantly create another CommentForm class ? -
Issue Pre-populating form in Django
I'm trying to get the user profile name to populate the form field 'user' from AgendaForm but what I get "'user': None". And the prints I get from the views are: {'user': None, 'date': datetime.date(2021, 9, 24), 'time': datetime.time(4, 0), 'comment': 'some comment', 'mode': 'ONLINE'} {'user': <Profile: Jhon Doe>} views.py @login_required(login_url='login') @allowed_users(allowed_roles=['user] def agenda(request): user = request.user.profile initial_data = { 'user': user } form = AgendaForm(initial=initial_data) if request.method == 'POST': form = AgendaForm(request.POST, initial=initial_data) if form.is_valid(): form.save() print(form.cleaned_data) print(initial_data) context = {'form': form} return render(request, 'agenda.html', context) agenda.models.py class Agenda(models.Model): user = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) date = models.DateField(null=True, blank=True, default="1900-01-11") ... def __str__(self): return '%s' % (self.user) main.models.py #(The OneToOneField 'User' comes from the UserCreationForm Django function) class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) id = models.AutoField(primary_key=True, null=False, blank=True) first_name = models.CharField(max_length=50, null=True, blank=True) ... def __str__(self): return '%s %s' % (self.first_name, self.last_name) -
Sending notification to a specific type of user and save the notification in the database using django channels
I want to send notification to a specific group of users. Let's say the specific group is Admin. When an user register on my site after admin approval the user will be activate. For this admin needs to be notified. The main problem was with the database design. I need to save the notification. class Notification(models.Model): view_name = models.CharField(max_length=255) notification_type = models.CharField(max_length=255) sender = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='notification_sender') recipient = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='notification_receiver') title = models.CharField(max_length=255) redirect_url = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_read = models.BooleanField(default=False) Here is the model. Here recipient will be the admin. Now main problem is there will be more than 1 admin. If i want to save the notification the solution came to in my mind is that to iterate through the User model find the admin and send each admin notification which is not a good solutions. Django channels doc shows there is a way to send multiple user using gruop_send() yes I can use that but how can I save the notification in the db with multiple recipient? -
Why won't cmd recognize the from command?
The code that I tried to run. The instructions for said code. I am not sure how my code was any different from what the instructions said to run, does anyone know what I am doing wrong or have any suggestions? -
How to fix 'guni:gunicorn STARTING' error when deploying django project on ec2 ubuntu
I'm hosting a django project on aws EC2 and I have the following content in gunicorn.conf file: [program:gunicorn] Directory=/var/www/html/myapp command=/usr/local/bin/gunicorn --workers 3 --bind unix:/var/www/html/myapp/app.sock myproject.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn.out.log [group:guni] programs:gunicorn After configuring gunicorn I ran the command sudo supervisorctl status. I expected the output to show RUNNING but that is not the case, instead what I'm seeng is guni:gunicorn STARTING: ubuntu@ip-172-31-17-212:/etc/supervisor/conf.d$ sudo supervisorctl status guni:gunicorn STARTING I ran the command whereis gunicorn to know the directory of gunicorn and I got the following output: ubuntu@ip-172-31-17-212:/etc/supervisor/conf.d$ whereis gunicorn gunicorn: /usr/local/bin/gunicorn I want to know where I'm getting it wrong. Also, if the gunicorn.conf file seems accurate, how do I locate the source of the error? With gunicorn status showing STARTING instead of RUNNING, all the web pages are showing 404. Though I'm not very sure whether the gunicorn issue is the cause of404 ERROR on web page. But I want to get the gunicorn running first. -
Python thread breaks down silently when run in the background
In django i am using thread to read xlsx file in the background using thread but after sometimes it breaks down silently withoutgiving any error. thread_obj = threading.Thread( target=bulk_xlsx_obj.copy_bulk_xlsx ) thread_obj.start() -
Canada Post Shipping Cost - Django/Python [API]
I am developing an E-Commerce site with Django and for the shipping, we want to use Canada Post to estimate and show the shipping cost. Unfortunately, their API documentation doesn't have any python guidelines to perform this task. Can anyone please suggest how to use their API to do this? -
Using Stream Field in WagTail throws an error in block content
I followed this official tutorial for WagTail. Now I want to change my BlogPage body column from RichText to StreamField in models.py. I follow this manual to make it works. I changed BlogPage class to look like this class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) categories = ParentalManyToManyField('blog_app.BlogCategory', blank=True) body = StreamField([ ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ]) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('date'), FieldPanel('tags'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ], heading="Blog information"), FieldPanel('intro'), StreamFieldPanel('body', classname="full"), InlinePanel('gallery_images', label="Gallery images"), ] Now I'm able to edit StreamField in Admin page of Wegtail. I changed content of base.html from {% block content %}{% endblock %} to {% include_block page.body %} to not throwing an error. Now I'm able to see content of StreamField in my post. But because I replaced {% block content %} I'm not able to see anything else (like all posts on blog_index_page.html). But because blog_index_page is looping posts I have to include {% include_block page.body %} in base to properly render content of StramField and not throwing an error that the block … -
how to generate barcode once
i have a problem, i generate barcode for field barcode in model Article barcode On first insert of new object it saved normally but when i update it, the application generate new barcode, how can i make drop it just once? models.py from django.db import models import random from django.contrib.auth.models import User import barcode from barcode.writer import ImageWriter from io import BytesIO from django.core.files import File `Status=(('0','Non'),('1','Oui')) class Article(models.Model): user= models.ForeignKey(User,blank=True,null=True,on_delete=models.CASCADE) numero=models.IntegerField(blank=True) barcode=models.ImageField(upload_to='article/codes',blank=True) nom = models.CharField(max_length=20) quantity=models.IntegerField(null=True) categorie=models.ForeignKey(Categorie,on_delete=models.CASCADE) date_entree=models.DateField(null=True) prix_achat=models.IntegerField(null=True) statut=models.CharField(max_length=2,null=True,default='0',choices=Status) def __str__(self): return self.nom def save(self,*args, **kwargs): EAN =barcode.get_barcode_class('upc') # rend=str(random.randint(2055,99999)) # print(r) r=self.categorie.id+self.user.id rr=self.categorie.id+self.date_entree.day+self.prix_achat ean=EAN(str(self.categorie.id)+str(self.user.id)+str(r)+str(self.date_entree.year)+str(self.date_entree.month)+str(self.date_entree.day)+'34',writer=ImageWriter()) buffer =BytesIO() ean.write(buffer) self.numero=ean.__str__() self.barcode.save(str({self.nom})+'.png',File(buffer),save=False) return super().save(*args, **kwargs)