Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error with docker container in bitbucket pipelines
I'm deploying my dockerized Django app using bitbucket pipelines but unfortunately, the pipeline already creates two containers but not the last one the error and my files are attached below. error ERROR: for db Cannot create container for service db: authorization denied by plugin pipelines: -v only supports $BITBUCKET_CLONE_DIR and its subdirectories Encountered errors while bringing up the project. docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - postgres-data:/var/lib/postgresql/data/ app: container_name: app build: context: . restart: always volumes: - static-data:/vol/web depends_on: - db proxy: container_name: proxy build: context: ./proxy restart: always depends_on: - app ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: bitbucket-pipelines.yml image: python:3.7.2 pipelines: default: - step: services: - docker caches: - docker - pip script: - pip install docker-compose - docker-compose -f docker-compose-deploy.yml up --build - pipe: atlassian/aws-code-deploy:0.2.5 variables: AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY COMMAND: 'upload' APPLICATION_NAME: $APPLICATION_NAME ZIP_FILE: 'application.zip' S3_BUCKET: $S3_BUCKET VERSION_LABEL: 'my-app-2.0.0' - pipe: atlassian/aws-code-deploy:0.2.5 variables: AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY COMMAND: 'deploy' APPLICATION_NAME: $APPLICATION_NAME DEPLOYMENT_GROUP: $DEPLOYMENT_GROUP WAIT: 'true' S3_BUCKET: $S3_BUCKET VERSION_LABEL: 'my-app-2.0.0' IGNORE_APPLICATION_STOP_FAILURES: 'true' FILE_EXISTS_BEHAVIOR: 'OVERWRITE' definitions: services: docker: memory: 3072 `` -
Pass variable to tables2?
In trying to follow the DRY principle for python, I am attempting to define some information about a column in tables2 with a variable. I can see that the variable is being passed to my init function, but I can't see it in the main body of my class. Is there a better way to do this? Below is a simplified version of the table that I am trying to use. class StuffTable(tables.Table): input(self.FontClass) # the variable is not showing up here columnAttributes = {"style": "font-size: 12px; max-width:120px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"} columnHeaderAttributes = {"class": f"mb3 { self.FontClass }"} columnFooterAttributes = {"style": "font-size: 12px; font-weight: bold; max-width:120px; overflow: hidden; text-overflow: ellipsis;"} Type = tables.Column(verbose_name="", attrs={"th": columnHeaderAttributes, "td": columnAttributes}) TypeDescription = tables.Column(verbose_name="Type", attrs={"th": columnHeaderAttributes, "td": columnAttributes}) Column3= tables.Column(attrs={"th": columnHeaderAttributes, "td": columnAttributes}) Column4= tables.Column(attrs={"th": columnHeaderAttributes, "td": columnAttributes}) def __init__(self, *args, **kwargs): temp_fontclass = kwargs.pop("FontClass") super(StuffTable, self).__init__(*args, **kwargs) self.FontClass = temp_fontclass input(self.FontClass) # this does show that the variable is being passed -
Hot Reload with django template and react?
Is hot reloading possible while mounting react components into our Django template? As part of improving our UX, we are adding react component to our page to bring dynamic content on every customer interaction. I have successfully set up the react inside our Django and placed bundle.js into a static path using Webpack. Now using Webpack watch we are able to load the latest changes on the page. In this setup, we can't bring hot reloading and source in the browser devtools console to debug and speed up our development. Note: The application is not a SPA also not a Restful design for now. -
How to set initial value for all students to present in College management system | django admin inline
I am building College management system in django including features such as quiz, lms and attendance and so on. I want to set All students default attendance status to Present in django admin inline. So teacher dont have to hammer the status checkbox for every student, every student should be present by default and teacher only have to uncheck the status for whom who are absent. I have googled a lot but having hard time figuring out the solution. This is what I want: My model: class Attendance(models.Model): course = models.ForeignKey(settings.COURSE_MODEL, on_delete=models.CASCADE) date = models.DateField(default=datetime.now) class AttendanceStatus(models.Model): attendance = models.ForeignKey(Attendance, on_delete=models.CASCADE) student = models.ForeignKey(settings.STUDENT_MODEL, on_delete=models.CASCADE) status = models.BooleanField() And here is the admin. class AttendanceStatusInline(admin.TabularInline): model = AttendanceStatus can_delete = False fields = [ 'student', 'status' ] autocomplete_fields = [ 'student' ] @admin.register(Attendance) class AttendanceAdmin(admin.ModelAdmin): list_display = [ 'course', 'date'] autocomplete_fields = ['course'] inlines = [ AttendanceStatusInline ] Thanks in advance. -
envrionment variables with dokcer-compose in bitbucket pipelines
I have a Django app that is dockerized and I want it to deploy it using bitbucket pipelines, but the error is I use env file in docker-compose.yml which I can't put in my repo, so how can I overcome it. docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - postgres-data:/var/lib/postgresql/data/ env_file: - prod.env app: container_name: app build: context: . restart: always volumes: - static-data:/vol/web env_file: - prod.env depends_on: - db proxy: container_name: proxy build: context: ./proxy restart: always depends_on: - app ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: settings.py EMAIL_HOST = os.environ.get('EMAIL_HOST') bitbucket-pipelines.yml image: python:3.7.2 pipelines: default: - step: services: - docker caches: - docker - pip script: - pip install docker-compose - docker-compose -f docker-compose-deploy.yml up --build - pipe: atlassian/aws-code-deploy:0.2.5 variables: AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY COMMAND: 'upload' APPLICATION_NAME: $APPLICATION_NAME ZIP_FILE: 'application.zip' S3_BUCKET: $S3_BUCKET VERSION_LABEL: 'my-app-2.0.0' - pipe: atlassian/aws-code-deploy:0.2.5 variables: AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY COMMAND: 'deploy' APPLICATION_NAME: $APPLICATION_NAME DEPLOYMENT_GROUP: $DEPLOYMENT_GROUP WAIT: 'true' S3_BUCKET: $S3_BUCKET VERSION_LABEL: 'my-app-2.0.0' IGNORE_APPLICATION_STOP_FAILURES: 'true' FILE_EXISTS_BEHAVIOR: 'OVERWRITE' definitions: services: docker: memory: 3072 -
Django structure vs Clean archirecture
We want to create a new project in python language(out project is in digital advertising), we choose the Django framework for developing it, BUT we have a problem for choosing architecture. Some of us want to use the Django default structure for file naming, project structure and etc, but another is like to use a clean architecture structure. We are very happy to know your opinion Django strcture advantage: simple, have a good document, Writing code is much less Clean Architecture advantage: top programmer use this, other python developers(flask/fatapi) comfortable with it -
How to start publish or use my django project that i made on Blogger or wordpress?
I Develop and design Django project , chat site for desktop and mobile app - its my first time! Q - ist possible to use it in blog-spot ? ot word-press ? the files i code it by python and HTML for front-end. -
Sort by nested Embedded Document List
obj = self.get_object() # Need to add sorting here submited_talents_page = paginator.paginate_queryset( obj.doc_list, request ) the list lloks like this: obj.doc_list = [{ "user": ObjectId("12123124"), "viewers": [], "application": ObjectId("34322") } ] application: "timestamp": "<timestamp>", "code": "DEF" } I need to sort the application.timestamp inside obj.doc_list. -
Set id inside filter on serializer automatically
I'm trying to get the total count from specific Model inside a Serialization. "results": [ { "event_id": 24, "unique_visitors": 1, "returned_visitors": 2 }, ] The two value that i retrive in unique_visitors and returned_visitors come from one other module. What i did in serializer.py: unique_visitors = EventCounter.objects.filter(is_unique=True).filter(event_id=24).count() returned_visitors = EventCounter.objects.filter(is_unique=False).filter(event_id=24).count() def get_unique_visitors(self, obj): return self.test1 def get_returned_visitors(self, obj): return self.test2 What i try to do is to have inside the filter(event_id=24) the id of current object automatically. Can you help me please? -
How to have a Save draft option for profile creating form in django
I have view.py and model.py files for user creation, but I want an option for users that he/she can either submit the form and create the profile or can just hit the Save draft button to come later and submit the form. What would be the best way to achieve the above-said thing. -
Django guardian add a group to a user in the admin panel
When I create a group in django guardian's admin integration, how can I add that group to a user's groups in the admin panel -
Nginx auth could not identify password
I'm trying to deploy a Django application to a local Ubuntu server. While following the nginx docs, I encountered an issue while trying to restart nginx after updating the conf file. This is the output from journalctl -xe -- The job identifier is 154. Mar 02 10:43:38 cmac-srv03 systemd[44001]: tracker-extract.service: Succeeded. -- Subject: Unit succeeded -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- The unit UNIT has successfully entered the 'dead' state. Mar 02 10:43:40 cmac-srv03 dbus-daemon[44023]: [session uid=1001 pid=44023] Activating service name='org.freedesktop.secrets' requested by '> Mar 02 10:43:40 cmac-srv03 gnome-keyring-daemon[44513]: couldn't access control socket: /run/user/1001/keyring/control: No such file or dire> Mar 02 10:43:40 cmac-srv03 gnome-keyring-d[44513]: couldn't access control socket: /run/user/1001/keyring/control: No such file or directory Mar 02 10:43:40 cmac-srv03 dbus-daemon[44023]: [session uid=1001 pid=44023] Successfully activated service 'org.freedesktop.secrets' Mar 02 10:43:52 cmac-srv03 pulseaudio[44008]: GetManagedObjects() failed: org.freedesktop.DBus.Error.NoReply: Did not receive a reply. Possi> Mar 02 10:43:58 cmac-srv03 tracker-store[44147]: OK Mar 02 10:43:58 cmac-srv03 systemd[44001]: tracker-store.service: Succeeded. -- Subject: Unit succeeded -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- The unit UNIT has successfully entered the 'dead' state. Mar 02 10:47:56 cmac-srv03 sudo[45528]: pam_unix(sudo:auth): conversation failed Mar 02 10:47:56 cmac-srv03 sudo[45528]: pam_unix(sudo:auth): auth could not identify password for [subhaac] This is my … -
How to check the users and if the user is correct then marked the ordered section tick in Django
I want to check the user and if the user is correct then marked the order other wise make it as False on Boolen Type, I have attached the SS of output and it's code def orderList(request): order_qs = User.objects.get(username=request.user.username) if request.method == "POST": status = request.POST.get("order") if (order_qs): Order.objects.update(ordered = status) else: Order.objects.update(ordered = False) order = Order.objects.get(user = request.user) context = { 'order' : order, } return render(request, 'user_accounts/order_item.html',context) -
NameError: name '_mysql' is not defined - Django tailwind
When I run python manage.py runserver, my django server runs and I can see my webpage, however some of the tailwind doesn't work. When I then stop that server and run python manage.py tailwind start, the localhost:8000 doesn't show my webpage, but my terminal says that it is running. When I then stop the tailwind server running, and run python manage.py runserver, I get an error saying NameError: name '_mysql' is not defined. I am unsure why this is happening, here is my full stack trace: Traceback (most recent call last): File "/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so Reason: image not found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/django/apps/config.py", line 300, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen … -
Django Admin /admin two times one server different port
currently I facing an issue to create two django projects parallel working on one server system. Konfiguration: nginx ubuntu server such as 1.1.1.1 django project 1 such as 1.1.1.1/admin with Port 8000 django project 2 such as 1.1.1.1/demo/admin2 with Port 9000 Currently if I start both (django project 1 and 2) manage.py runserver successful and if I change path("admin/", django.contrib.admin.sites.urls) to path("admin2/", django.cotntrib.admin.site.urls) this gives me the Not Found Error. Is there any way to use two django projects parallel on one server in a different GitHUb folder structure and the same IP ? -
How to disallow specific character input to a CharField
I have a model in which I want to disallow the input of special characters(+,-,/,%, etc) in the title field: class Article(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title Can I accomplish this in the model itself? Or do I have to do something with the forms.py so that users arent able to post a form with special chars in the title. How exactly can I accomplish this? -
Scheduling a satutus change using celery in django
In my program, I have scheduled a task that is aimed at changing the status of insurance to Expiré if the due date is equal to the current date when I run the program. The script supposes to loop up throughout the Contract's table and fetches the rows that are corresponding to the condition we used in the script. However, it is changing the status of the whole table including rows that should not be affected by the imposed condition. Here is the jobs.py file that is scheduling the task of changing the status of the insurance to Expiré if the condition is true. from assurance_auto.models import Contrat from datetime import datetime, timedelta,date from django.conf import settings def status_schedule(): contractList = Contrat.objects.all() for contrat in contractList: if contrat.get_NbDays()<=date.today() and contrat.statut_assurance=='Encours': contractList.update(statut_assurance='Expiré') print('Numéro de contrat est :',contrat.numero_de_contrat,\ ' et le statut est: ',contrat.statut_assurance) else: break Below is the updater.py file. This function is about scheduling the execution time of the job from datetime import datetime from apscheduler.schedulers.background import BackgroundScheduler from .jobs import status_schedule def start(): scheduler = BackgroundScheduler() scheduler.add_job(status_schedule, 'interval', seconds=5) scheduler.start() In the apps.py file, I have the program below which consists of running the updater file once the program … -
Build a wizard without django-formtools in Django
Are there any django libraries to help build wizard based interfaces that are not formtools/wizard ? formtools/wizard has some properties that make it hard to test, moving forward and back between forms is tightly integrated with rendering, making it hard to unit test the forms themselves. Similarly session storage is tightly integrated. Other issues, come from the coding style of when it was written over a decade ago. So, as much as this will get voted down, I'm not asking for preferences, just any libraries that help with making wizards, I also understand this could be coded manually. -
Login with another user gives everything that is created by the superuser instead of giving an empty Album And Primary Model
I have a login page and register page where a user can create an account and login to his account, the problem is that: when i login with different user it's gives me everything that is created by the superuser or other user's instead of showing an empty page that could let me create fresh Album and Primary for the new user, Just like Facebook when you create an account and login it's will shows you an empty page in your Account. No friends no new Post and so on. how can i do this??? the login views: def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('home') else: messages.info(request, 'Invalid Credential') return redirect('login') else: return render(request, 'login.html') the register view: def register(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] if password == password2: if User.objects.filter(email=email).exists(): messages.info(request, 'Email or user name Already taking') return redirect('register') elif User.objects.filter(username=username).exists(): messages.info(request, 'username is taken') return redirect('register') else: user = User.objects.create_user(username=username, email=email, password=password) user.save(); return redirect('login') else: messages.info(request, 'Password Not Match') return redirect('register') return redirect ('/') else: return render(request, 'signup.html') … -
Django how to remove #modal from url
I have a modal for confirm the action and this modal adds #modal to url but after i submit the url it stil there in the url even after i did redirect in views.py <div class="wf-modal" aria-hidden="true" id="{{sepet.id}}"> <article class="wf-dialog-modal"> <form action="" method="post"> {% csrf_token %} <div class="wf-content-modal"> <input type="hidden" name="cancel-id" value="{{sepet.id}}"> <label for="sebep">{%if sepet.siparis_durumu.durum == "Kargoya Verildi"%}İade{%else%}İptal{%endif%} Sebebi: </label> <textarea name="sebep" style="resize: none; margin-left: 2px;" cols="40" rows="5" {%if sepet.siparis_durumu.durum == "Kargoya Verildi"%}required{%endif%}></textarea> </div> <footer class="wf-footer-modal"> <button name="gonder" value="gonder">Gönder</button> <a href=""><button name="iptal" type="button">İptal</button></a> </footer> </form> </article> </div> views.py if req.get('gonder'): if ...: return redirect('/hesabim/iptal/') but the url stil like /hesabim/iptal/#modal-id -
Django - Find missing invitations for an event
I need to pick the community's brain on django. I'm still learning and the layer abstraction is my major challenge (as compared to a PHP/SQL script) Here's an extract of my models: A very simple contact, but with a "level" (like basic, gold, ...) class customer(models.Model): created_date = models.DateTimeField(auto_now_add = True, editable = False) modified_date = models.DateTimeField(auto_now = True, editable = False) surname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) fk_level = models.ForeignKey(level, on_delete=models.CASCADE) [...] An event with customers (any number) that need to be invited to: class event(models.Model): created_date = models.DateTimeField(auto_now_add = True, editable = False) modified_date = models.DateTimeField(auto_now = True, editable = False) eventdate = models.DateField('Date de la soirée') fk_customer = models.ManyToManyField(customer, blank=True) [...] The invites to an event, for a customer. class invite(models.Model): created_date = models.DateTimeField(auto_now_add = True, editable = False) modified_date = models.DateTimeField(auto_now = True, editable = False) fk_customer = models.ForeignKey(customer, on_delete=models.CASCADE) fk_event = models.ForeignKey(event, on_delete=models.CASCADE) [...] The description of the level, with the number of invites to be sent based on the customer's level. class level(models.Model): created_date = models.DateTimeField(auto_now_add = True, editable = False) modified_date = models.DateTimeField(auto_now = True, editable = False) name = models.CharField(max_length=200) eventinvites = models.IntegerField(default=2) [...] I don't want (and probably don't know how) … -
Microsoft Graph API : Deleting/Modifying single occurrence from recurring series
i have an app which has subscription to office365 calendar. I'm trying to show the meetings in my application which are presents in outlook. My question is, if a single occurrence of the recurring booking it's modified or cancelled in outlook, how can I found out which event was that one, and what changed so I can update my app too with the changes? -
django related question querying list of won items by getting list of items then max bid from bid table for each item then check if user won it
I have a question here, I have two tables in my django models one for listings and one for bids class Listing(models.Model): class Meta: verbose_name_plural = 'Listing' title = models.CharField(max_length=64) description = models.TextField() price = models.DecimalField(max_digits=5, decimal_places=2) image = models.URLField(max_length=500, default='') category = models.CharField(max_length=32) created = models.CharField(max_length=32) addedon = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) def __str__(self): return self.title class Bid(models.Model): class Meta: verbose_name_plural = 'Bid' user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(Listing, on_delete=models.CASCADE) bid = models.DecimalField(max_digits=5, decimal_places=2) created = models.DateTimeField(auto_now_add=True) what i want is to show a page with all the user won items def won(request): listing = Listing.objects.filter(active=False) the question here how i can make list of all then check max bid of each listing, then check is the current user is the winner and display it in the template won.html like : getMaxBid = Bid.objects.filter(item_id=listing.id).aggregate(Max('bid')) maxBid = getMaxBid['bid__max'] then if the user is the winner display it return render(request, "auctions/won.html", { 'listing': listing, 'active': False }) thanks in advance -
Form to delete specific attributes in Django
Sorry for the noobish question, but I am trying to make a simple stock management website with Django and I could not get this part to work. I could not get the part where I register a certain amount of crates of soda and then when it gets taken away from the stock I want the web app to register it however amount less. My model is as follows: class Drink(models.Model): category = models.CharField(max_length=100) name = models.CharField(max_length=200, unique=True) crate = models.IntegerField() So if the stock manager registers 25 crates (crate) a certain drink (name) and then after some time takes 20 of the crates out for use, I want it to be able to register that 20 crates were taken out and that there are now 5 left. I want to do this on the front-end. I used this form to register a Drink object: class CrateForm(forms.ModelForm): class Meta: model = Drink fields = ["name", "category", "crate",] labels = {'name': "Name", "crate": "Crate",} So I guess my question is: how do I create a form that allows me to subtract whatever amount of crates I want to take out for use, and then registers the remaining amount back. It’s kind … -
Python strange import behavior [closed]
In my Django project, I've extended on the generic class based views by making my own 'base' views. These are sitting in "app/views/base/", for example 'app/views/base/base_list_view.py' which inside has a class BaseListView. I currently have 4 of these, each corresponding to a different CBV. (list, detail, update, redirect) When importing these for views that inherit from them, the import behavior seems different for 2 out of 4 classes. (Imported using pycharm intellisense shortcuts) from app.views import BaseUpdateView, BaseDetailView from app.views.base.base_list_view import BaseListView from app.views.base.base_redirect_view import BaseRedirectView example of views: class ProductListView(BaseListView): .... class ProductDetailView(BaseDetailView): .... I don't understand why 2 out of 4 base views, which have been created in exactly the same manner, have a different behavior in the import. Can anyone shed some light on this for me?