Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery chord callback isn't always launched
I'm trying to use a chord to launch a report update after the update is completed. @shared_task(autoretry_for=(Exception,), retry_backoff=True, retry_kwargs {'max_retries': 5}) def upload(df: pd.DataFrame, **kwargs): ed = EntityDataPoint(df, **kwargs) uploadtasks, source, subtype = ed.upload_database() chord(uploadtasks)(final_report.si(logger=ed.logger, source=source, subtype=subtype, index=ed.index)) With uploadtask being : g = group(unwrap_upload_bulk.s(obj = self, data = self.data.iloc[i:i+chunk_size]) for i in range(0, len(self.data), chunk_size)) When the header of the chord has more than 2 elements, the first two subtasks succeed, and the rest of the tasks in the group and the callback are not launched, without any error being sent anywhere, and without any information in the celery workers logs. After inspecting the workers, with celery inspect active, scheduled, there doesn't seem to be any waiting task in the queue. If the header (the group) has 2 or less elements, there is no problem, the group tasks finishes, the callback is called. It does not seem depend on the size of the elements (if each subtask in the group is sending 100 rows, we still have the same behavior for 1000 rows). If I just launch the group tasks, without the chord and the callback, the tasks succeed without any error. I tried using different syntaxes for the … -
Can we add a method like create_user_with_permission just like create_user in django?
I'm making a django website and I had made groups for the admin page access(Admin, Content Writer, Users). What I want is when a user signs up they should be assigned the specific group based on from which form they are signing in/up. Here is my models.py file for accounts app models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager # Custom User Manager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name=None, **extra_fields): if (not email): raise ValueError("Email Must Be Provided") if (not password): raise ValueError("Password is not Provided") user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_active', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, first_name, last_name, **extra_fields) def create_superuser(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, first_name, last_name, **extra_fields) # Custom user Model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255, null=True, blank=True) mobile = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=250, null=True, blank=True) # profile_pic = models.ImageField(null=True, blank=True) is_staff = models.BooleanField(default=True) is_active … -
Upload image to S3 bucket with django-ckeditor
I have got an Article model with "content" textarea I decided to replace this textarea(i needed an option to insert images inside form) with CK-Editor so I used django-ckeditor package So now I got an issue - when I upload the image with CKEditorUploadingWidget() form, it saves data to local storage, however, S3 storage has been configured, so I have no clue why it doesn't work Here my code: Form: <form method="POST"> {{ form.media }} {{ form|crispy }} {% csrf_token %} <button type="submit" class="btn btn-primary my-3">Add</button> </form> Settings related to this topic: CKEDITOR_CONFIGS = { "default": { 'toolbar': 'full', 'width': 'auto' } } CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_ALLOW_NONIMAGE_FILES = False AWS_QUERYSTRING_AUTH = False S3_ACCESS_KEY_ID = 'secret' S3_SECRET_ACCESS_KEY = 'secret' S3_FILE_UPLOAD_BUCKET_NAME = 'bucket-name' S3_FILE_UPLOAD_BUCKET_URL = 'some url' -
Python3 Magic for a Django project
I need the python-magic package for a Django project. However, I found out that since I am using python3, I need the python3-magic package, which I can either get using pip3 or using apt-get. I am a macOS user, so I don't have an apt-get, and I cannot install the package using pip3. It gives me the following error when I type: pip3 install python3-magic. ERROR: Could not find a version that satisfies the requirement python3-magic (from versions: none) ERROR: No matching distribution found for python3-magic Is there any way I can get this package for my Django project? No matter what I do, the package appears uninstalled on my VS Code. Any helpful information will be greatly appreciated. -
Way to display user adjustable shapes on webpage in Django
I'm new to Python, and am currently working on web development in Django. I need to have an interface on this website that allows a user to dynamically adjust a rectangular shape that displays this adjustment to them on the website in real time. Does anyone know how I can integrate this using Django or Bootstrap. Pretty much I need a way to display to the user a rectangle that they can drag and drop the lengths of on the screen as they desire. Very similar to the MS Word shape drawing tools where the user can pick the edge of and expand or collapse. -
Django Model unsupported type for timedelta days component: datetime.timedelta
I am facing an error within my Django project, this is a model method that should allow me to increase costs based on inflationary rates stored in my database (this code was largely provided by a reddit user) def calculateCurrentCost(self): """Calculates the cost of a project in current value""" base_cost = self.total_cost today = date.today() time_difference = timedelta(today - self.date_added_to_database).days # get the timediff in days from the timediff object days_since_costing = time_difference inflation = days_since_costing * 0.01 cost_with_inflation = Decimal(base_cost) * Decimal((1 + inflation)) location_adjustment = self.location_premium[self.location] region_adjusted_cost = cost_with_inflation * location_adjustment return region_adjusted_cost however I am running into an issue with the timedelta portion and I am unsure as to what is causing this issue? unsupported type for timedelta days component: datetime.timedelta -
django postgres database in Amazon s3 service
In our company we have 5 services that stores our backend django codes and one front end service that holds react codes and these services communicate with each other in microservice api . we use docker to run projects on each service and in each build two containers are made which one is for the postgresql database and the other is to run the service , this is docker compose file : services: test: build: context: . dockerfile: Dockerfile env_file: - ./envs/development.env volumes: - ./:/app - /store/account/media:/app/media - /store/account/static:/app/static ports: - 8000:8000 command: gunicorn account.wsgi:application --reload --bind 0.0.0.0:8000 account-database: image: postgres:alpine env_file: - ./envs/development.db.env volumes: account-static: account-media: networks: default: name: test the problem is if the docker container is deleted we lost all our data so recently we have decided to move the database to a separated service and we have Amazon s3 in our mind accorrding this tutorial i know how to connect a django project to a live database on s3 but my question is : is it a standard way of doing it or there is a better solution to separated our databases from our source code? can i do still perform delete and update on database … -
How to have a permission-based user system in Django?
I want the build a REST API where user can do operations on objects, based on their permissions. Consider a record that represents a car - it contains the license number, the type of the car and extra information. Also consider the following user system: Owners - Who owns the car object. Can modify it and delete it. Editors - Who can only modify the object properties. Viewers - Can only view the object properties. Each record can contain multi owners/editors/viewers (The user who created the object should be automatically the owner). Also, owners can add or remove editors/viewers. So in case of a GET request, I want to be able to return all objects that the user has permissions for, separated into those three categories. So under my api app, I have the following code: The models.py file contains: class CarRecord(models.Model): type = models.CharField(max_length=50) license = models.CharField(max_length=50) The serializers.py file contains: class CarRecordSerializer(serializers.ModelSerializer): type = models.CharField(max_length=50) license = models.CharField(max_length=50) class Meta: model = CarRecord fields = ('__all__') In view.py I have: class CarRecordViews(APIView): def get(self, request): if not request.user.is_authenticated: user = authenticate(username=request.data.username, password=request.data.password) if user is not None: return Response(data={"error": "invalid username/password"}, status=status.HTTP_401_UNAUTHORIZED) # return all records of cars … -
Easy Problem: CSS in DMs on a social media site not displaying correctly
Within the DM function on my social media platform I would like the received messages to appear on the left hand side and the sent messages to appear on the right hand side. Currently it is the other way round: https://i.stack.imgur.com/qGDDP.png (Sent messages (light pink) = #D7A5EB, received messages (dark pink) = #CC64C3) Ì have been trial-and-erroring this for a while now, but it simply refuses to allow sent messages (I.e. the ones that the currently logged-in user sent) on the right hand side. thread.html: {% extends 'landing/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="row"> <div class="card col-md-12 mt-5 p-3 shadow-sm"> {% if thread.receiver == request.user %} <h5><a href="{% url 'profile' thread.user.profile.pk %}"><img class="rounded-circle post-img" height="50" width="50" src="{{ thread.user.profile.picture.url }}" /></a> @{{ thread.user }}</h5> {% else %} <h5>@{{ thread.receiver }}</h5> {% endif %} </div> </div> {% if message_list.all.count == 0 %} <div class="row my-5"> <div class="col-md-12"> <p class="empty-text">No messages yet.</p> </div> </div> {% endif %} {% for message in message_list %} <div class="row"> {% if message.sender_user == request.user %} <div class="col-md-12 my-1"> {% if message.image %} <div class="message-sender-container ms-auto"> <img src="{{ message.image.url }}" class="message-image" /> </div> {% endif %} <div class="sent-message my-3"> <p>{{ message.body … -
Preserve image metadata in Django upload form
I want to extract metadata from images that are uploaded using a form. Right now it seems that metadata is overwritten/removed. I have already checked this question, but the answer provided in that thread is lacking in where that code should be and why. Using that in my view gave nothing. Here's my current model: class signUp(models.Model): name = models.CharField(max_length=20) sex = models.CharField(max_length=1) dob = models.CharField(max_length=10) image = models.FileField(upload_to='images') -
How to write .set() for this error? To update m2m field?
I'm trying to edit the M2m field. Gives an error: Direct assignment to the forward side of a many-to-many set is prohibited. Use analog.set() instead. How to solve this problem (I don’t understand where to put set()) def editpart(request, id, **kwargs): added = '' error = '' PartAllView = Part.objects.order_by('-id') part = Part.objects.get(id=id) form = PartForm(request.POST, request.FILES) if request.method == 'POST': part.brand = request.POST.get("brand") part.number = request.POST.get("number") part.name = request.POST.get("name") part.description = request.POST.get("description") part.images = request.FILES.get("images") part.images0 = request.FILES.get("images0") part.images1 = request.FILES.get("images1") part.images2 = request.FILES.get("images2") part.analog = request.POST.get("analog") part.save() added = 'Запчасть успешно отредактирована' form = PartForm() data = { 'added': added, 'error': error, 'form': form, 'PartAllView': PartAllView, 'part': part, } context_object_name = "part" return render(request, 'kross/editpart.html', data) -
Django ordering by date_created with ManyToMany using Through
Having trouble figuring out how to order by date created. I've looked at some similar problems on here and no fix. I need the dates to order by ascending so that the most recent object created is on the top of the list. I've tried different things even using JS to revert the list and still no luck. I have class Info(models.Model): detail = models.CharField(max_length=50) text = models.TextField(max_length=2000) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, related_name='cb_section') updated_by = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, related_name='up_section') date_created = models.DateField('Date created', auto_now_add=True) date_updated = models.DateField('Date updated', auto_now=True) class Section(models.Model): name = models.CharField(max_length=20) section_infos = models.ManyToManyField(Info, through='SectionInfo') date_created = models.DateField('Date created', auto_now_add=True) date_updated = models.DateField('Date updated', auto_now=True) def __str__(self): return self.name def get_section_info(self): return self.section_infos.order_by('-date_created') class SectionInfo(models.Model): info = models.ForeignKey(Info, on_delete=models.CASCADE) section = models.ForeignKey(Section, on_delete=models.CASCADE) class Meta: ordering = ('info__date_created',) and in my template I have <div class="row"> {% for object in object_list %} <div class="col-sm-4"> <div class="card"> <div class="card-header"> <h1><strong>{{ object.name }}</strong></h1> <hr> </div> <div class="card-body"> <div class="row"> {% for info in object.section_infos.all %} <ul id="list"> <li>{{ info.date_created }}</li> | <li><a href="{% url 'manufacturing:section_info_detail' info.id %}">{{ info.detail }}</a></li> <hr> </ul> {% endfor %} </div> </div> </div> </div> {% endfor %} </div> View for this is … -
Django new WebSocket(url)
I am trying to do a chat app in django with channels. I try to do it from this video. But when I run it I get in console (index):16 WebSocket connection to 'ws://127.0.0.1//8000/ws/socket-server/' failed: . The moment in video is 8:31 and the program is working. Please help. Thanks. -
django.db.utils.IntegrityError: NOT NULL constraint failed: userapp_resume.last_updated
I get that error when I try to save data for a resume I'm creating. "The above exception (NOT NULL constraint failed: userapp_resume.last_updated) was the direct cause of the following exception:" This is the error message that the browser throws. I'm not sure what I'm missing here. userapp is the name of my app models.py ```user = models.OneToOneField(User, on_delete = models.CASCADE) uniqueId = models.CharField(null=True, blank=True, max_length=200) image = models.ImageField(default = 'default.jpg', upload_to='profile_images') email_confirmed = models.BooleanField(default=False) date_birth = models.DateField(blank=True, null=True) sex = models.CharField(choices=SEX_CHOICES, default=OTHER, max_length=200) marital_status = models.CharField(choices=MARITAL_CHOICES, default=SINGLE, max_length=200) addressLine1 = models.CharField(null=True, blank=True, max_length=200) addressLine2 = models.CharField(null=True, blank=True, max_length=200) village = models.CharField(null=True,blank=True, max_length=200) city = models.CharField(null=True, blank=True, choices=DISTRICT_CHOICES, default=KAMPALA, max_length=200) district = models.CharField(choices=DISTRICT_CHOICES, default=KAMPALA, max_length=100) phoneNumber = models.CharField(null=True, blank=True, max_length=200) slug = models.SlugField(max_length=500, unique=True, blank=True, null=True) date_created = models.DateTimeField(default= timezone.now) last_updated = models.DateTimeField(blank=True, null=True) cover_letter = models.FileField(upload_to='resumes', null=True, blank=True,) cv = models.FileField(upload_to='resumes', null=True, blank=True,)``` Url patterns ```urlpatterns = [ path('admin/', admin.site.urls), path('home/', job_views.index, name='home_page'), path('register/', user_views.register, name='register_page'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login_page'), path('logout/', auth_views.LogoutView.as_view(template_name='logout.html'), name='logout_user'), path('terms-and-conditions/', job_views.terms, name='terms'), path('create-resume/', user_views.create_resume, name='create-resume'), path('<slug:slug>/', user_views.ResumeDetailView.as_view(template_name='resume-detail.html'), name='resume-detail'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` these are the apps ```INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jobapp', 'userapp', ]``` -
relationship primaryjoin in django.db
how to implement primaryjoin through django.db as in the example below with sqlalchemy.orm relationship primaryjoin Class Account(Base): name = Column(String(64), primary_key=True) data = relationship( "AccountData", primaryjoin="AccountData.name == Account.name", uselist = False ) ... Class AccountData(Base): name = Column(String(64), ForeignKey('account.name'), primary_key=True) ... -
How to pass a parameter in the string in python using format
There as a url link which i have in settings.py file : KAVENEGAR_URL = "https://api.kavenegar.com/v1/{key}/verify/lookup.json?receptor={phone}&token={otp}".format(key,phone,otp) I want to use it in service.py file inside send_otp_sms method I dont know how to pass key, phone, otp variables in it from django.conf import settings def send_otp_sms(key, phone, otp): kavenegar_url = settings.KAVENEGAR_URL.format({key}, {phone}, {otp}) response = requests.post(kavenegar_url) if response.status_code != 200: raise APICallError return response I used .format as you see in the codes but it pass error in settings.py which Unresolved reference 'key' Unresolved reference 'phone' Unresolved reference 'otp' -
Django admin navigate through self referring Foreign Key
I have a Folder model with a self-referring Foreign Key. The folders represent the structure of a root folder on my computer, and this structure can only be modified in the admin panel. With the number of folders rising, this could be quite hard to clearly look for a folder from inside the admin panel. My goal is to add a View children link that allows the admins to navigate through the folders by filtering them and displaying only the children of the folder : However, I didn't find how to implement it. I supposed I had to use a filter in order to get all children of the folder that was clicked, however I couldn't find a way of doing it. I only found the SimpleListFilter but that doesn't do the job since I need to set values for the side filter panel. What I want would be to have a view_children like that in my list_display : def view_children(self): return format_html('<a href="?children_of={}">View Children</a>', self.pk) And then be able to filter the folders with the pk that was passed to the url. How could I do something like that ? -
Related Field got invalid lookup: icontains ( when using foreignKey
I am trying to search blogs by blog author name where author is a foreignkey. models.py class Blog(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE,related_name='post_author') blog_title=models.CharField(max_length=264,verbose_name='Put a Title') category=models.ForeignKey(Category,on_delete=models.CASCADE,related_name='category',default=None) slug= models.SlugField(max_length=264,unique=True,null=True,allow_unicode=True) blog_content=models.TextField(verbose_name='what is on your mind?') here's the views.py logic if request.method == "GET": search= request.GET.get('search',' ') if not search == ' ': result = Blog.objects.filter(Q(blog_title__icontains=search) | Q(author__icontains=search)) i know it's happening because author is a foreignkey. But I have went through many questions but couldn't find the answer. Thanks i advance -
how to make call to aws api gateway and a lambda function real time and update a database table
I have the following script, which make a call to a lambda function via an API Gateway. The lambda function, when it is called, retrieve some data from the database (RDS), which is inside of a AWS VPC, then update some value. snippet lambda def handler(event, context): ... conn = pg2.connect( host=DATABASE_HOST, database=DATABASE_NAME, user=DATABASE_USER, password=DATABASE_PASSWORD, ) try: cur = conn.cursor(cursor_factory=pg2extras.DictCursor) cur.execute(""" SELECT users_user.id FROM users_user WHERE users_user.username = (%s) """, [username]) ... cur.execute(""" UPDATE person SET first_name = 'john' WHERE id = (%s) """) ... conn.commit() except (Exception, pg2.DatabaseError) as e: if conn: conn.rollback() print("Error: {}".format(e)) sys.exit((1)) finally: if conn: response = {} response["statusCode"] = 200 response["body"] = "OK" conn.close() return response the calls to the lambda and api gateway are stored in the aws cloudwatch log streams. Now i have noticed that when the first call is made to this api gateway, for some reason, i have to wait until the second call is made for the update to show when i query the data from the database, the same thing happen when i look at the log stream , i am not able to see the real time log. When i make call 1 to the api gateway, … -
How to use multiple {% block content %} {% endblock%} in the same HTML file
I want to use multiple block contents on the same html file to create a layout template. The actual layout.html body looks lije this: <body> <main role="main" class="container"> <div class="row"> <div class="col-md-8"> {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-{{ category }}"> {{ message }} </div> {% endfor %} {% endif%} {% endwith %} **{% block content %}{% endblock %}** </div> </div> </main> </body> How can i implement another block content but with certain specific id so i can refer it from another html file? -
deploying Django project on AWS lambda without using Zappa [closed]
I have created my complete django app and I want to deploy it on lambda . I am not willing to deploy via zappa . I will have my zip generated of the project using zappa and I want to put this in another bucket in AWS but this time I dont want to use zappa as it will not give me control to certain properties if any i want in future. -
Is there anyone can help me with a task of Django [closed]
Now I need to implement a project of Django (add a new tab in company website). Can anyone help me to look into it together, to help me with outline the step? Since I am totally new beginner and I feel a little confused about this. I can share the screen to express the problem. Thank you so much. -
Template Tag - Get class variables
I need to get information in template tag from a custom class This is the class class EmpleadoSiradig: def __init__(self, cuit, nro_presentacion, fecha, deducciones={}, cargasFamilia={}, ganLiqOtrosEmpEnt={}, retPerPagos={}): self.cuit = cuit self.nro_presentacion = nro_presentacion self.fecha = fecha self.deducciones = deducciones self.cargasFamilia = cargasFamilia self.ganLiqOtrosEmpEnt = ganLiqOtrosEmpEnt self.retPerPagos = retPerPagos def get_cuit(self): return self.cuit Views @login_required def archivo_solo_view(request, slug): dd = os.path.join(get_carpeta(), slug) siradig_empleado = formulas.leeXML3(dd) context = { 'siradigEmpleado': siradig_empleado, } return render(request, 'reader/soloxml2.html', context) HTML {% block title %} Siradig Individual - CUIT: {{ siradigEmpleado.cuit }}{% endblock title%} "siradig_empleado" is an EmpleadoSiradig object type, but I'm not getting a result in {{ siradigEmpleado.cuit }}. Thanks in advance. -
How to set is_staff field to False when user is created by logging in from google using alluth package
I am building a django website and I wanted to know how can I set is_staff of my custom user model to false when some user logs in from their google account. When someone logs in from their email and password their is_staff is set to false(implemented by me), but I can't find nor figure out a way to do so when someone logs in from their google account. I am using allauth package for google login. Here is my models.py for accounts app models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager # Custom User Manager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name=None, **extra_fields): if (not email): raise ValueError("Email Must Be Provided") if (not password): raise ValueError("Password is not Provided") user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_active', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, first_name, last_name, **extra_fields) def create_superuser(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, first_name, last_name, **extra_fields) # Custom user Model class User(AbstractBaseUser, … -
Container commands for Elastic Beanstalk
I'm upgrading to Linux 2 on Elastic Beanstalk and I'm having trouble with command 02. commands 01 and 03 are confirmed to be working. when 02 is introduced, the deployment fails. container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 myapp/manage.py migrate --noinput" leader_only: true 02_makesuper: command: "python3 myapp/manage.py makesuper" leader_only: true 03_collectstatic: command: "source /var/app/venv/*/bin/activate && python3 myapp/manage.py collectstatic --noinput" leader_only: true the makesuper.py file exists within the following path myapp/useraccounts/management/commands/makesuper.py Under linux 1, the following command worked 02_makesuper: command: "python3.6 myapp/manage.py makesuper" leader_only: true Thanks!