Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dockerized django build : how to run only once createsuperuser
I have a django docker container for the backend on my website. There is a volume for the database so i can save the database even if i change the backend configuration. I have tried to put the createsuperuser in my Dockerfile and in a script launched with "command" in docker-compose. But it seems the command is re-run each time the container starts or is rebuilt. I would like this command to be run only once, but i dont know how to proceed. The problem is the container is rebuilt in my ci/cd pipeline if i change the configuration files, and so the command is re-run in the Dockerfile in that case. I have seen this post Run command in Docker Container only on the first start but that also works only if the container is not rebuilt. A workaround with a createsuperuser command that would fail would work and that seemed to be the case with django previous versions (before version 4) but i now have "django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username" error which tells me the command seems to be run multiple times and gives me errors in the database... -
I want to make my own Gmail using Django, how can I?
My question is about creating my own Gmail using Django. I have no idea about that and need your suggestions and advices. -
Django Framework "User has no userprofile." Error
Was trying to replicate the code of this lesson https://jnpnote.com/following-django-tutorial-crm-part11/ Here is the text of the error: RelatedObjectDoesNotExist at /agents/create/ User has no userprofile. Got error while replicating the following code. Could you please help me to avoid the error class AgentCreateView(LoginRequiredMixin, generic.CreateView): template_name = "agent_create.html" form_class = AgentModelForm def get_success_url(self): return reverse("agents:agent-list") def form_valid(self, form): agent = form.save(commit=False) agent.organisation = self.request.user.userprofile agent.save() return super(AgentCreateView, self).form_valid(form) As i guess i can't get the userprofile parameters properly. -
How can I remove a many to many relashionship from javascript?
If I need to add a reference between two objects I can do post.likes.add(user) but what shoudl I do if I wanted to remove it? -
How to add custom CSS for form labels to dynamically built Django forms?
I have a django form for which I need to increase the font size of the labels. Based on this StackOverflow discussion, what I need to do is add a CSS class and apply it to the control-label. How do I actually go about doing that? My form is populated like so: class MyForm(forms.Form): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) fields_to_add = { # many fields here, but all in this format. Removed for brevity. 'purchase_order_number': forms.ChoiceField( label="Purchase Order", choices=purchase_order_numbers), } self.fields.update(fields_to_add) self = add_classes(self) The add_classes code is as follows: def add_classes(self): """Add styling to form inputs.""" for key, value in self.fields.items(): self.fields[key].widget.attrs.update( {'class': 'form-control', # <- this is what I expect to change 'style': 'font-size: large',} ) return(self) I assume I need to modify add_classes to add some form of label-control or a custom class, but I don't really know how to actually make that change. -
Respuesta de Django se pierde y no llega la promesa al fetch
Tengo un formulario el cual recibe js para realizar una serie de validaciones y enseguida por fetch envió la información al servidor (una api sencilla). La verdad no tengo muy entendido en sí por qué se da el error, cabe recalcar que en desarrollo funcionaba perfecto pero ahora que está en producción alojado en heroku se produce dicho problema, el código fetch es el siguiente. formulario.addEventListener('submit', (e) => { e.preventDefault(); fetch('https://portafolioadrian.herokuapp.com/contacto', { method: 'POST', body: JSON.stringify({ nombre: document.querySelector('#nombre').value, correo: document.querySelector('#correo').value, telefono: document.querySelector('#telefono').value, mensaje: document.querySelector('#form__message').value, terminos : document.getElementById('terminos').checked, }), headers: { 'X-CSRFToken': getCookie('csrftoken'), "Accept": "application/json", 'Content-Type': 'application/json'} }) .then(res => res.json()) .then(res => { if (res.success) { formulario.reset(); document.getElementById('form__message-success').classList.add('form__message-success-active'); setTimeout(() => { document.getElementById('form__message-success').classList.remove('form__message-success-active'); }, 5000); document.querySelectorAll('.form__group-correct').forEach((icono) => { icono.classList.remove('form__group-correct'); }); }else{ document.getElementById('form__message').classList.add('form__message-active'); } }) }); Al momento de enviarlo, por consola me sale el siguiente error Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Y en la sección de network el estatus al momento de realizar el POST es 301 Moved Permanently, he investigado algo y trata hacerca de redirecciones pero no encontré solución. El urls.py de la app es esta: urlpatterns = [ path('', views.contacto, name='contacto'), path('mensajes/', views.mensajes, name='mensajes'), ] Y la view es la siguiente: … -
How can I get my html page to refresh upon completion of a django function?
I keep getting an error related to the csrf token when I try to employ consecutive submissions, and refreshing the page seems to work. The purpose of the program is to create zip files, so I figured the easiest solution would be to have the web page automatically reloaded once the zip file is done being created from the function in the views.py file and available for the user to open. The main issue I'm having is how to actually do that. Here is the code for my HTML file: {% load static %} <html> <head> <link rel="stylesheet" href="{% static '/styleSheet.css' %}"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edstore"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--BOOTSTRAP ASSETS--> <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@400;700&display=swap" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} <div class="main_Body"> <div class="section"> <h1>Fileconverter</h1> <br> <label for="file_field" class="custom-file-upload"> <i class="fa fa-cloud-upload"></i>Updload File(s)</label> <input type="FILE" id="file_field" name="file_field" class="file-upload_button" multiple> <label id="file_name"></label> <br> <br><br><br> <br> <input type="submit" class="file-submit__button" id="submitButton"> <!--onclick="formDisableButton"--> </div> </form> </body> <footer> <p>Click "Choose File(s)" and select the files you want to convert.</p> <p>Once you click "Submit" the job will start.</p> <p>Upon completion, a zip folder will be downloaded in your browser.</p> <p>Do not click the submit buttons multiple times. If the … -
django : which files are modified by migrate and makemigration?
I am having this issue of "django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username" on a brand new deployed django app. I have no prreviously existant database, i have no files in my "migrations" folder. But I had done previous migrate and makemigrations on the source files for the deployment. So i'm wondering which files are affected by migrate and makemigrations commands? I have deleted all the files in the migrations folder, but it seems some traces of a preceding user remain... If you could provide me with some hints on the files where a trace of a preceding user exist, it would help me a lot. -
Django Errno 30: Read-only file system deploying to Heroku
I consistently get the following error when Deploying my Django app to Heroku. Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/app/my-app/settings.py", line 292, in <module> django_heroku.settings(locals()) File "/app/.heroku/python/lib/python3.9/site-packages/django_heroku/core.py", line 93, in settings os.makedirs(config['STATIC_ROOT'], exist_ok=True) File "/app/.heroku/python/lib/python3.9/os.py", line 225, in makedirs mkdir(name, mode) OSError: [Errno 30] Read-only file system: '/staticfiles' I tried other solutions on SO such as this one with no luck. Here are the relevant versions and settings python==3.9.7 django==3.2.13 django-heroku==0.3.1 whitenoise==6.2.0 From settings.py: import os from decouple import config import django_heroku PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = "/static/" … -
Dajngo all migrations are doubled
I just started my django project and after running the migrations I was trying to create superuser. Then the error popped out that I have unapplied migrations (even though I just did it). When I checked the "showmigrations" it turned out that all the migrations are doubled. I have deleted migration file so does the db (because it was empty anyway). The problem has not disappeared. Does anyone know what may be the problem? admin [ ] 0001_initial 2 [ ] 0001_initial [ ] 0002_logentry_remove_auto_add 2 [ ] 0002_logentry_remove_auto_add [ ] 0003_logentry_add_action_flag_choices [ ] 0003_logentry_add_action_flag_choices 2 auth [ ] 0001_initial 2 [ ] 0001_initial [ ] 0002_alter_permission_name_max_length 2 [ ] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length 2 [ ] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts 2 [ ] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null 2 [ ] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 2 [ ] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages 2 [ ] 0007_alter_validators_add_error_messages [ ] 0008_alter_user_username_max_length 2 [ ] 0008_alter_user_username_max_length [ ] 0009_alter_user_last_name_max_length 2 [ ] 0009_alter_user_last_name_max_length [ ] 0010_alter_group_name_max_length 2 [ ] 0010_alter_group_name_max_length [ ] 0011_update_proxy_permissions 2 [ ] 0011_update_proxy_permissions [ ] 0012_alter_user_first_name_max_length [ ] 0012_alter_user_first_name_max_length 2 contenttypes [ ] 0001_initial 2 [ ] 0001_initial [ ] 0002_remove_content_type_name [ ] 0002_remove_content_type_name 2 sessions [ ] 0001_initial … -
Check for a list the elements of which all contain only whitespaces in HTML
I'm building an app in Flask. I'm extracting a variable items (which is a list) and displaying each of its elements in a separate cell. <tr> <th>Some heading</th> {% for item in items %} <td>{{ item }}</td> {% endfor %} </tr> However, some items lists only contain elements consisting of whitespaces only, for example: items = [' ', ' ', ' ', ' '] I want to check that this is NOT the case and create a table row only if at least one element of items contains more than whitespaces. {% if items %} doesn't help because the list has elements. Is there any other way? I don't know JavaScript, but I would be glad to look into that too if there is a way. -
Django - pass multiple HTML form inputs into a view
I have 3 form inputs that will be submitted when one master button is clicked to then be passed into a view as the request parameter. I would like to get the values of first_name, last_name and email inside my view using request.get(). When the button is clicked the values inside my form appear as None HTML: <div id="form_content"> <form action="" method="post"> <section class="form_inputs"> <label for="first_name">First Name:</label> <input type="text" id="first_name"> </section> <section class="form_inputs"> <label for="last_name">Last Name:</label> <input type="text" id="last_name"> </section> <section class="form_inputs"> <label for="email">Email:</label> <input type="text" id="email"> </section> <input type="submit" value="Submit"> </form> </div> views.py def home(request): form_response = request.GET.get("form_content") print(form_response) context = {"title": "Home"} return render(request, "myApp/home.html", context) -
Error during installing requirements.txt in Django (metadata generation failed)
I tried installing requirements.txt in Django. Virtual env is activated. This error is showing after I tried pip install -r requirements.txt After that I also tried to migrate but still not working. This is github fork I downloaded, it has a pickle file as well as its based on ML model. -
Django is redirecting me to sublime text and the last raises import error
Have chosen Sublime as core git editor. And now after every move I do in Django virtual project, i'm being redirecting to sublime text with such error: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" -
Django: how to save data to database in django when a condition is met?
i am writing a logic to allow user pay for items using thier debit card, the logic is working fine. Now i want to save some data to the database when the status=successful. When a user purchase a course i want to add the course and the user who purchased the course to a model that i have created called UserCourse. I have tried adding slug to the process_payment view that i created but it seems not to be working. I also have another view called payment_response that checks if a payment was success or not. How do i add the purchased course and the user that purchase the course in the db? views.py # The course detail view def course_details(request, course_slug): if request.user.is_authenticated: user = request.user course = Course.objects.get(slug=course_slug) @login_required def course_checkout(request, slug): course = Course.objects.get(slug=slug) user = request.user # form to get the student's name, email, amount of course if request.method == "POST": course = Course.objects.get(slug=slug) name = request.POST.get("name") email = request.POST.get("email") amount = request.POST.get("amount") return redirect(str(process_payment(name,email,amount, course))) else: pass # how to handle courses that are free if amount == 0: course = Course.objects.get(slug=slug) userCourse = UserCourse(user=user, course=course) userCourse.save() return redirect('course:course-content', course.slug) # View that processes the … -
Django-postgress: Partial Index on timestamp
Consider queryset = queryset.filter( Q(enabled=False) | Q(expires_at__isnull=False) & Q(expires_at__lte=timezone.now()) | ) I would like to have a partial index to support this query. AFAIK, this index will not be used during the execution of the above query because the value of timezone.now() changes. On the other hand, if I just index enabled that is also not useful because the query planner has to go through the second condition anyway. -
Heroku Deployment: Failed to load resource: the server responded with a status of 404 (Not Found)
I initially deployed my app successfully to heroku but then I edited some text and redeployed it to heroku yesterday only for the js file not to load completely. It tells me failed to load resource on the chrome developer console (It was built using next.js, django and postgresql). I have checked everything and can't seem to find the error, Please I'm really confused and would be some help? favourndubuisi.herokuapp.com -
How to serialize a model with many to maany relashionship?
I have this function in my model, def serialize(self): return { 'id': self.id, 'author': self.author.username, 'text': self.text, 'timestamp': self.timestamp.strftime("%b %d %Y, %I:%M %p"), 'likes': self.likes.all(), 'likes_number': len(self.likes.all()), } but likes is actualy a many to many relashionship with User. How can I serialize it to get something like this? def serialize(self): return { 'id': self.id, 'author': self.author.username, 'text': self.text, 'timestamp': self.timestamp.strftime("%b %d %Y, %I:%M %p"), 'likes': [ user1, user2, etc. ], } So that I can also get rid of the 'likes number' property. -
Handling images via REST API
I'm trying to create a REST API with django-rest-framework which will be handling a few things, the one being sending and receiving images from the frontend. I found this article which tries to explain the idea, but it uses class-based approach in its' views.py and ideally I'd like to stick to a function-based one as I've already done some work that way (not including JWT authorization) and I'd prefer it to stay. I have no clue how to make my backend legible of receiving and sending images, could you please try to provide me with some code snippets (or better yet, articles) on how to do so? Thanks in advance! One thing to mention is that ideally I want to have an endpoint which will handle creating a new object which will come with an image (a plant to be specific) and an endpoint which would handle updating (changing) the object's image. My models.py: class Plant(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=150) date_added = models.DateField(auto_now_add=True) description = models.TextField() img = models.ImageField(blank=True, null=True, upload_to=upload_path) plant_species = models.CharField(max_length=150) last_watered = models.IntegerField(default=0) how_often = models.IntegerField(default=0) tracked=models.BooleanField(default=True) My views.py: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username return … -
Django is treating same field which are lowercase and upper case as 2 different entities
I am creating models in django and then entering data in admin panel class Song(models.Model): name = models.CharField(max_length=30,validators=[alphanumeric]).title() slug=models.SlugField(default="",blank=True,null=False,db_index=True) artist = models.CharField(max_length=30,validators=[alphanumeric]) genre = models.CharField(max_length=30,validators=[alphanumeric]) language = models.CharField(max_length=30,validators=[alphanumeric]) image = models.ImageField(null=True,blank=True) But the issue is when I am entering "AceHunter" or "acehunter" as artist it is treating as different artists although I want them as one.... Please can someone help me what error I am making? -
Efficient Way to Search Complex Database
I have a database with 2 data tables: Messages and Annotations. A summary of the models is below. Only the important fields are included. message text = models.CharField(max_length=250, blank=False) accepted_annotation = models.OneToOneField( to='Annotation', related_name='original_msg', on_delete=models.SET_DEFAULT, default=None, null=True ) ...other fields annotation message = models.ForeignKey(to=Message, on_delete=models.CASCADE) user = models.ForeignKey(to=User, to_field='username', on_delete=models.SET_NULL, null=True) text = models.CharField(max_length=249, blank=False) reviewed = models.BooleanField(default=False) ...other fields I would like to search by text and also by the other fields. The complication is that, depending on who requested the data, different information is returned for each message in the database. The following pieces of information determine what is returned: users privilege whether the annotation is marked as reviewed whether there is an accepted annotation whether the user made an annotation Therefore when I search by text, I can't simply search the message text because the logic may determine that an annotation should be displayed for this user instead with completely different text. Currently what I am doing is using prefetch and annotations on the queryset to run through the logic and populate a field called "text_to_search" for each message before sorting and filtering. However, these require subqueries and will be very slow once there are millions of … -
Django Paginator is not giving output
Hope you are doing great. So there is a projects page where there are different number of projects on that page. Currently I am displaying 3 projects per page. Now I want to display number of pages that I have right now. Like there are 9 projects so there should be 3 pages. But My paginator is not displaying any number button on the bottom of the page. Here is the code(Sorry For the bad English I tried my best to explain) View.PY def projects(request): page = request.GET.get('page') results = 3 paginator = Paginator(obj, results) try: obj = paginator.page(page) except PageNotAnInteger: page = 1 obj = paginator.page(page) except EmptyPage: page = paginator.num_pages obj = paginator.page(page) return render(request, 'projects/projects.html',{'list': obj}) Projects.html <div class="pagination"> <ul class="container"> <li><a href="#" class="btn btn--disabled">&#10094; Prev</a></li> {% for page in paginator.page_range %} <li><a href="?page={{page}}" class="btn btn--sub">{{ page }}</a></li> {% endfor %} <li><a href="#" class="btn">Next &#10095;</a></li> </ul> </div> Can you guys tell what could be the issue? -
how to filter columns for each in the same model in Django admin
I have a model called Product. I am using StackedInline to display ProductCostCalculator in my admin panel. The problem that I have is that I will have 20+ columns in my ProductCostCalculator model. Some columns from ProductCostCalculator are not needed in every item in the Product model so I want to exclude all columns that are not needed. I know that I could just put 0 or '-' as default and insert values in proper columns in the admin panel but I would like to make it more dynamic so the user echo will be adding calculator components will not have to do it manually. For example, I want to add 2 items to my Product model. Let's call them Item 1 and Item 2. In Item 1 I will need to insert values in field_1, field_2, and field_3. In Item 2 in my Product model, I will need to insert values only for field_3, field_4 and field_5. Question: How can I assign a column from ProductCostCalculator to an item in the Product model or how can I filter all columns that are not needed in the specific item in the Product model. I am not sure if something like … -
React - How to login a user through Django backend?
Backstory as a learning exercise, I first built a website using only Django; then, I learned React (still in the process) and I was moving the frontend part in it and using Django only as backend. I have them on 2 different addresses 127.0.0.1:3000 and 8000. Now, I created all sort of API where React can fetch and send data to Django in order to read and manipulate the DB, the Login it is mainly the only thing that I'm still missing. I think this is probably due to the fact that I let Django handle all the things for the login, doing minimal work. The situation So, at the moment, in Django the login works this way: settings.py: LOGIN_URL = '/users/login/' LOGIN_REDIRECT_URL = '/users/' url.py: path('login/', auth_views.LoginView.as_view(template_name='registration/user_login.html'), name='user_login'), user_login.html (shorted): {% block body %} {% if form.errors %} <p> Your username and password didn't match. Please try again. </p> {% endif %} <form method="post"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> {% if next %} <input type="hidden" name="next" value="{{ next }}" /> {% else %} <input type="hidden" name="next" value="{% url 'registration:main_page' … -
AttributeError: 'RedisChannelLayer' object has no attribute 'group_disgard'
traceback File "/Applications/MAMP/htdocs/canvas/src/zzd/env/lib/python3.7/site-packages/channels/generic/websocket.py", line 238, in websocket_disconnect await self.disconnect(message["code"]) File "/Applications/MAMP/htdocs/canvas/src/zzd/zzd/notes/consumers.py", line 20, in disconnect await self.channel_layer.group_disgard( AttributeError: 'RedisChannelLayer' object has no attribute 'group_disgard' consumer class NoteConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['pk'] self.room_group_name = 'note_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name, ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_disgard( self.room_group_name, self.channel_name, ) async def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'system_message', 'message': message, } ) async def system_message(self, event): # print(event) message = event['message'] await self.send(text_data=json.dumps({ 'message': message, })) versions (env) 🌹 python Python 3.7.11 (default, Jul 27 2021, 07:03:16) [Clang 10.0.0 ] :: Anaconda, Inc. on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> import channels >>> import asgiref >>> django.__version__ '3.2.8' >>> channels.__version__ '3.0.5' >>> asgiref.__version__ '3.3.4' config CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } Why the method is undefined, how can I dismiss the bug?