Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use Visual Studio Code to debug Django with an IP address defined by myself? (By that I would test my app on an android phone)
I'm aware that when I set up my server with python manage.py runserver [my custom IP address] I can choose what IP and port will be chosen. But when I use VScode in debug mode I don't know where I can define the server other than 127.0.0.0.1:8000. Having 127.0.0.0.1:8000 I can access the page just by my pc (win 10). I need to change the address, because I'm unable to open my page on my android phone (for testing with this debugger), but I don't know where and how. -
Check either someone has clicked a post or not within the template django
I have this model struture: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=1200, blank=True) class PostLike(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) Template for post in posts ... # want to check here, something like: if post.userliked write something endif ... endfor Now what I want is to check either the current loggedin user has liked the post or not within the django template. I have tried, post.postlike_set but of course that won't work because it's for all the likes, is there anyway that I can check if the current loggedin user has liked the post or not. Please help! -
Django Messages - Debug Tag Messages Not Showing On Template
I am going through the docs for Django Messages and have set up a basic form with some error messages and a debug message. The error messages are appearing but the debug one is not. I am not sure why the debug one is not and would appreciate some guidance. I did check the settings file and all 4 lines outlined in the docs are already included. views.py def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, "Registration successfull.") return redirect("messages_test:homepage") messages.error(request, "Unsuccessful registration. Invalid information.") messages.error(request, "Unsuccessful registration. Invalid information again.") messages.debug(request, "Debug message") form = NewUserForm() return render(request=request, template_name="messages_test/register.html", context={"register_form":form}) register.html {% load static %} <link rel="stylesheet" href="{% static 'messages_test/style.css' %}"> {% load crispy_forms_tags %} <div class="container py-5"> <h1>Register</h1> <form method="POST"> {% csrf_token %} {{ register_form|crispy }} <button class="btn btn-primary" type="submit">Register</button> </form> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <p class="text-center">If you already have an account, <a href="/login">Login</a> instead.</p> </div> -
How to make sign-up in django with one-to-one model?
model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.CharField(max_length=100) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() view def register(request): if request.method == 'POST': user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) print(user_form) print(profile_form) print("에혀") if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) profile = profile_form.save(commit=False) profile.user = user profile.user.set_password(user_form.cleaned_data['password']) profile.user.department = request.POST['department'] user.save() profile.save() print(request) return render(request, 'index.html', {'new_user':user}) else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'register.html', {'form':user_form}) form class UserForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat Password', widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email'] class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['department'] urls.py urlpatterns = [ path('', IndexView.as_view(), name='index'), path('register/', views.register, name='register'), .... template {% extends "base.html" %} <div class="container my-3"> <form method="post" action=""> {% csrf_token %} <div class="mb-3"> <label for="username">ID</label> <input type="text" class="form-control" name="username" id="username" value="{{ form.username.value|default_if_none:'' }}"> </div> <div class="mb-3"> <label for="password">PASSWORD</label> <input type="password" class="form-control" name="password" id="password" value="{{ form.password.value|default_if_none:'' }}"> </div> <div class="mb-3"> <label for="password2">PASSWORD_CONFIRM</label> <input type="password" class="form-control" name="password2" id="password2" value="{{ form.password2.value|default_if_none:'' }}"> </div> <div class="mb-3"> <label for="email">EMAIL</label> <input type="text" class="form-control" name="email" id="email" value="{{ form.email.value|default_if_none:'' }}"> </div> <div class="mb-3"> <label for="email">DEPARTMENT</label> <input type="text" class="form-control" name="department" id="department" value="{{ form.department.value|default_if_none:'' }}"> </div> <button … -
how can I use `return HttpResponseRedirect(reverse("some-path", args=[slug]))` with user_agent?
I'm looking for a way to use (in the views.py) return HttpResponseRedirect(reverse("some-path", args=[slug])) where I can define to which template a user will be redirected according to the device. The problem is related to the Class-based view with the get and post methods. In my post function I have this unsolved problem in my return statement. I couldn't find an answer anywhere: what's the best approach for this situation? The problem is that redirection uses just url.py and I don't know where and how can I write the if statement about the devices, like in normal view function: if user_agent.is_pc: return render( request, 'dev/registration-success_pc_tablet.html', { 'my_email': my_email }) elif user_agent.is_mobile: return render( request, 'dev/registration-success_mobile.html', { 'my_email': my_email }) elif user_agent.is_tablet: return render( request, 'dev/registration-success_pc_tablet.html', { 'my_email': my_email }) I have set my MIDDLEWARE, INSTALLED_APPS for user_agent. The problem is just with this particular case that I described in my question. -
How delete a model instance and the instance from the OneToOne relation
I have these two models in django rest: class CustomUser(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) class Teacher(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) How can I delete the CustomUser instance related when deleting a Teacher instance? I tried this code but it gives this error "maximum recursion depth exceeded while calling a Python object" @receiver(pre_delete, sender=Teacher) def delete_user(sender, instance, **kwargs): instance.user.delete() -
Django & Form with SelectMultiple: null value in column x of relation y violates not-null constraint
I am facing the following error when trying to save the project after filling the form where i am choosing multiple tags for this project: null value in column "tag_id" of relation "project_tags" violates not-null constraint DETAIL: Failing row contains (10263, 10262, null). --> project_tags(id, project_id, tag_id) The db model is simple: I have projects, and each project has tag(s). All is defined by the following models: class Project(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey(User, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() class Meta: managed = False db_table = 'project' def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class ProjectTag(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=30) class Meta: managed = False db_table = 'project_tag' def __str__(self): return self.name class ProjectTags(models.Model): id = models.AutoField(primary_key=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) tag = models.ManyToManyField(ProjectTag) class Meta: managed = False db_table = 'project_tags' View is following: @login_required def add_project(request): submitted = False if request.method == "POST": form1 = ProjectForm(request.POST) form2 = ProjectTagsForm(request.POST) if form1.is_valid() and form2.is_valid(): form1_part = form1.save(commit=False) form1_part.client = request.user form1_part.save() project_id = Project.objects.get(id=form1_part.id) form2_part = form2.save(commit=False) form2_part.project = project_id form2_part.save() return HttpResponseRedirect('/project/new?submitted=True') else: form1 = ProjectForm form2 = ProjectTagsForm if 'submitted' in request.GET: submitted = True context = {'form1':form1 ,'form2':form2 ,'submitted':submitted } return render(request, … -
django auth with otp and phone number without password
I want user login without password, just by sending an SMS to the user's phone number and entering the code. I used sessions to transfer user inputs and I just don't know if this is correct or if there is a better way for this. Thank you for helping me. This is my code: # models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.core.validators import RegexValidator class MyAccountManager(BaseUserManager): def create_superuser(self,username, email, phone_number,password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True') user = self.create_user(username,email, phone_number, password, **other_fields) user.set_password(password) user.save() return user def create_user(self, username, email, phone_number,password,**other_fields): if not email: raise ValueError('') email = self.normalize_email(email) if password is not None: user = self.model(username=username,email=email, phone_number=phone_number,password=password, **other_fields) user.save() else: user = self.model(username=username,email=email, phone_number=phone_number, password=password,**other_fields) user.set_unusable_password() user.save() return user class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=150,unique=True) phone_number = models.CharField(max_length=17, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['email', 'username'] # views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth import authenticate, login, get_user_model from .forms import … -
Can't handle with Django Model related objects for Analysis-tracking App
I'm trying to make a web app that allows to add patients and add then track their medical analyses. Example Trying to make models for it... Could you advise me: what is the strategy if my next purpose is to make form that allows to fill in all lines from analysis group. Should I move in this way? (So next will be problems with orm queries) I tried to deal with next solution but maybe u will take a professional look at this? Really appreciate patient/models.py: class PatientGender(models.Model): gender = models.CharField(max_length=16) def __str__(self): return f"{self.gender}" # Create your models here. class Patient(models.Model): hist_number = models.IntegerField(unique=True, verbose_name='Номер истории болезни') last_name = models.CharField(max_length=32, verbose_name='Фамилия') first_name = models.CharField(max_length=32, verbose_name='Имя') second_name = models.CharField(max_length=32, verbose_name='Отчество') birth_date = models.DateField(verbose_name='Дата рождения') date_time = models.DateField(auto_now_add=True, verbose_name='Время поступления в ОРиТ') sex = models.ForeignKey(PatientGender, verbose_name='Пол', on_delete=models.CASCADE, default=1) seat = models.PositiveSmallIntegerField(verbose_name='Палата', blank=True, null=True) description = models.TextField(blank=True, verbose_name='Палата') is_Active = models.BooleanField(verbose_name='Находится на лечении', default=True) def __str__(self): return f"{self.hist_number}: {self.last_name} {self.first_name} {self.second_name}" analysis/models.py: class AnalyzesGroup(models.Model): name = models.CharField(max_length=256, verbose_name='Группа исследований') description = models.TextField(blank=True, verbose_name='Примечание') class Meta: verbose_name = 'Группа анализов' verbose_name_plural = 'Группы анализов' def __str__(self): return f"{self.name}" class AnalysisType(models.Model): name = models.CharField(max_length=256, verbose_name='Исследование') measurement = models.CharField(max_length=10, verbose_name='Единицы измерения') ref_min = models.FloatField(verbose_name='Мин. реф. … -
Limit instantiations of class with particular value to one - django
I have two classes in a django app, project and plan The project class has an is_global boolean field, as does the plan class. The plan also has a foreign key to the project class (projects have multiple plans). I am trying to accomplish the following: for both projects and plans, there should only ever be one instance of each where is_global = true. The global plan should belong to the global project. Is it possible to enforce this logic with django models? -
EventConsumer() missing 2 required positional arguments: 'receive' and 'send', while using AsyncWebSocketConsumer
The problem is, that i dont understand why it asks me for 2 positional arguments here, and i didnt see any other problem like this. There were suggestions to update 'channels' library, or to really add that 'send' and 'receive' functions into my Consumers class. But neither of that has any impact on my code. I have tried different variations of routing, setting up asgi, or configuring Docker-compose and nginc.config file. But still nothing helps. The idea is that i just want My WebSocket to be sending me events which are saved to events from POST, or which is about to be saved. Here is my consumers.py: from channels.generic.websocket import AsyncWebsocketConsumer from .models import ( WorkingMode, CarParkItem, Events ) import json class EventConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() await self.channel_layer.group_add("events", self.channel_name) print("Connected to events") async def disconnect(self, close_code): await self.channel_layer.group_discard("events", self.channel_name) print("Disconnected from events") async def receive(self, text_data): text_data_json = json.loads(text_data) cam_id = text_data_json['cam_id'] vehicle_plate = text_data_json['vehicle_plate'] is_recognition = text_data_json['is_recognition'] is_confirmation = text_data_json['is_confirmation'] working_mode = WorkingMode.objects.get(pk=cam_id) event_code = None if working_mode.pass_mode == 'closed': event_code = 1009 else: car_park_item = CarParkItem.objects.filter(vehicle_plate=vehicle_plate).first() if car_park_item: event_code = 1008 else: if is_recognition and is_confirmation: event_code = 1007 elif is_recognition and not is_confirmation: event_code = … -
Django form.is_valid() points
I have submit form with: <textarea name="entry" cols="40" rows="10" placeholder="Entry context..." class="area-fld" maxlength="30" required id="id_entry"> # CSS CSS is a language that can be used to add style to an [HTML](/wiki/HTML) page. </textarea> This code: def new(request): if request.method == "POST": form = NewEntry(request.POST) if form.is_valid(): The form.is_valid() is False! All other fields are OK valued. I found the problem is in the values are in textarea. I need the form validation (required fields) are checked server-side, but above value be approve. What is the points of the form.is_valid()? Which values are not approve? How can handle this problem? I have read this Django documentation -
Problem with getting objects based on ManyToManyField relation
I have Meal model and Ingredient, Meal have ManyToMany relation to Ingredient. I try to get objects that match by Ingredients models.py class Meal(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) recipe = models.TextField() is_published = models.BooleanField(default=False) user = ForeignKey(User, verbose_name='User', on_delete= models.CASCADE) difficulty = ForeignKey('Difficulty', on_delete=models.PROTECT, null=True) ingridients = models.ManyToManyField('Ingridient') ico = models.CharField(max_length=500, blank=True, null=True) class CategoryIngridients(models.Model): name = models.CharField(max_length=100, db_index=True) def __str__(self): return self.name class Ingridient(models.Model): name = models.CharField(max_length=100, db_index=True) category = ForeignKey('CategoryIngridients', on_delete=models.CASCADE, null=True) def __str__(self): return self.name serializers.py class MealSerializer(serializers.ModelSerializer): category = serializers.StringRelatedField() difficulty = serializers.StringRelatedField() #ingridients = serializers.StringRelatedField() user = serializers.StringRelatedField() class Meta: model = Meal fields = "__all__" class IngrigientSerializer(serializers.ModelSerializer): category = serializers.StringRelatedField() class Meta: model = Ingridient fields = "__all__" views.py class TestCraft(APIView): def post(self, request): ingridients_tmp = request.data['ingredients'] ingrid = Ingridient.objects.filter(id__in=ingridients_tmp) print(ingrid) queryset = Meal.objects.filter(ingridients__in=ingrid) print(queryset) serializer = MealSerializer(queryset, many=True) return Response(serializer.data) If I POST json: {"ingredients":[1,2]} This view return, but they are repeating: [ { "id": 1, "difficulty": "Medium", "user": "vleo", "name": "gfgd", "description": "", "recipe": "...", "is_published": true, "ico": "", "ingridients": [ 1, 2, 3, 4, 5, 6 ] }, { "id": 5, "difficulty": "Easy", "user": "vleo", "name": "залупа", "description": "[eqyz", "recipe": "n.,sr", "is_published": false, "ico": "", "ingridients": [ 1, … -
How to convert MediaRecorder stream in Django into wav without disk storage?
I am trying to convert the bytes_data received by the channels receive() method using a WebsocketConsumer. This is the JavaCode: navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => { const mediaRecorder = new MediaRecorder(stream, {mimeType: 'audio/webm' }) console.log(stream) chatSocket.onopen = () => { mediaRecorder.addEventListener("dataavailable", (event) => { if (event.data.size > 0 && chatSocket.readyState == 1) { chatSocket.send(event.data) } }) // chatSocket.onopen close mediaRecorder.start(250) } On the server side I now want to convert the bytes_data into a wav file so that I can send these short audio snippets via speech_recognition to the recognize_google api. I tried to use pydub to convert the bytes_data but so far I had no success. The channels GeneralConsumer(WebsocketConsumer) class now receives the bytes_data and uses this function to convert and send it to google: def transcriber(bytes_data: bytes): r = sr.Recognizer() audio = AudioSegment.from_raw( bytes_data, sample_width=2, frame_rate=16000, channels=1) buffer = io.BytesIO() audio.export(buffer, format="wav") buffer.seek(0) with sr.AudioFile(buffer) as source: audio = sr.AudioData(source.stream.read(), sample_rate=16000, sample_width=2) try: transcription = r.recognize_google(audio, language="en-USA").lower() except sr.UnknownValueError as e: print(e) return transcription But that does not work. I have tried some variations and others I simply don't understand. A comprehensive solution would be appreciated. -
Pycryptodome PBKDF2 same password and salt, different hash
I am using PBKDF2 to hash a key challenge (a uuid is generated on the server, encrypted using the user's public key, then the user decrypts the challenge and sends it to the server for api access). When the uuid is generated it is supposed to be hashed, then stored in the db, then when the user sends the decrypted uuid, the server must hash it to compare with the stored hash. When I tested this, the user sends the correct uuid, and the salt is the same (stored alongside the hash), but the hash is different. What could cause this? See code and sample values below. Hashing function: from Crypto.Hash import SHA512 from Crypto.Protocol.KDF import PBKDF2 from Crypto.Random import get_random_bytes def PBKDF_HASH(salt, plain, length): hashed = PBKDF2(plain, salt, length, count=1000000, hmac_hash_module=SHA512) print('HASHD: ') print(base64.b64encode(hashed)) return base64.b64encode(hashed) #hash is base64 encode for db storage Challenge generator: def challengeGenerator(): uuid = secrets.token_hex(64) print(uuid) salt = get_random_bytes(64) print(salt) hash = PBKDF_HASH(salt, uuid, 128) #uuid is encrypted and hash + salt are stored in db User Authentication Test: print(user_uuid) #decrypted uuid sent in request salt = #salt retrieved from db print(salt) hash = PBKDF_HASH(salt, user_uuid, 128) #hash is compared to the hashed uuid … -
django eventstream - only empty data
I installed and followed the guide from the git, but I hit a wall once I try to execute a send_message() call using the shell. I rewrote the asgi.py: application = ProtocolTypeRouter({ "http": URLRouter([ path("msgs/", AuthMiddlewareStack(URLRouter(django_eventstream.routing.urlpatterns)), { "format-channels": ["test"] }), re_path(r"", get_asgi_application()), ]), }) and I created the entries in urls.py: urlpatterns = [path("msgs/", include(django_eventstream.urls), {'format-channels': ["test"]})] I also added the static ressources to my static directory and I can access them on any page that includes my base.html. But when I open the local msgs channel at 127.0.0.1\msgs\ I only see: When opening a shell in a second terminal and using send_event("test", "message", {"text": "hello"}) I see no indication whatsoever that anything is sent out to the frontend. Also the JS sample code from the repo fetches nothing on the main page when sending out data in a loop with starting django (using the fantastic scheduler huey here): @periodic_task(crontab(minute = "*/1")) def test(): send_event('test', 'message', {'text': 'hello world'}) print("hello world...") I see the output of print() but not the result of send_message() on the frontend. Also, there is no implication that my scheduled or manually run send_message() actions result in anything on the \msgs\ channel - the timing does … -
Why I get this error when I trie to do the migrations on Django 3.2.6?
I was trying to update mi DB using the comand python manage.py makemigrations after of delete all the files of migrations in my Django project, because when I try to do the changes on my db doesnt apply This is my model class ciudades(models.Model): ciudad_nombre = models.CharField(max_length=50) estado = models.CharField(max_length=50) def __str__(self): return self.name class Meta: db_table = 'ciudades' verbose_name ='Ciudad' verbose_name_plural = 'Ciudades' This is the error that I get Traceback (most recent call last): File "/Users/dorianraygoza/Downloads/doha-erp/manage.py", line 22, in <module> main() File "/Users/dorianraygoza/Downloads/doha-erp/manage.py", line 19, in main execute_from_command_line(sys.argv) File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/apps/config.py", line 124, in create mod = import_module(mod_path) ^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/contrib/auth/apps.py", line 8, in <module> from .checks import check_models_permissions, check_user_model File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/contrib/auth/checks.py", line 8, in … -
Negative indexing is not supported in django
I am trying to upload image and show the same in my site but instead i am getting this error my current django-mptt version is 0.5.1 views.py- def home(request): print('here you go ') images=[] images=image_classification.objects.all() url=images[len(images)-1].pic.url return render(request,'home.html',{'print':'everything is ok','image':url}) #handles uploaded images def uploadImage(request): print('image handling ') img= request.FILES['image'] image=image_classification(pic=img) image.save() return HttpResponseRedirect('/') inside models.py from django.db import models class image_classification(models.Model): pic=models.ImageField(upload_to='images') and the error i am facing Traceback (most recent call last): File "C:\Users\prasa\Desktop\Pytorch-Django\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\prasa\Desktop\Pytorch-Django\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\prasa\Desktop\Pytorch-Django\MainApp\ImageClassifier\views.py", line 10, in home url=images[len(images)-1].pic.url File "C:\Users\prasa\Desktop\Pytorch-Django\venv\Lib\site-packages\django\db\models\query.py", line 425, in __getitem__ raise ValueError("Negative indexing is not supported.") Exception Type: ValueError at / Exception Value: Negative indexing is not supported. -
static files are are not working in django
I want to display an image on my site but static file are not being found this is my directory my url: STATIC_URL = 'static/' and my html: {% load static %} -
In Django, I'm having trouble getting the id from HTML; the error is: ( Field "id" expected a number but got )
When the user selects the translator name, I want to access the selected translator in Django by the id and store the information in an appointment table in the database, but there is an error when he tries to mach the id the error is: Field 'id' expected a number but got ''. HtML code: <section style="margin-top: 10%;"> <form method="POST" action="/waite" > {% csrf_token %} <select id="translator" name="translator"> {% for i in pro %} <option value="{{ i.id }}"> {{ i.name }}</option> {% endfor %} </select> <button type="submit">Send request</button> </form> </section> in django view.py: def waitePage(request): if request.method == 'POST': id = request.POST.get("translator") translator = Manager.objects.get(user_id=id) translatorName= translator.name #get the name of the translator translatorID= translator.id #get the id of the translator current_user = request.user #to get the user current_userId = current_user.id #for storing user id customer = Customer.objects.get(id=current_userId) #to get the info of translator customerID=customer.id customerName=customer.name appointment = Appointment.objects.create( customerName=customerName, customerID=customerID, translatorID=translatorID, accepted=False,) appointment.save() return render(request,'waitePage.html') The error comes from: translator = Manager.objects.get(user_id=id) Do you guys have any idea how I can solve it? Do you guys have any idea how I can solve it? -
Slug not recognized
The urls.py file created, containing the app_name = "articles" which is not recognized in the "template_base.html" established as model template. NoReverseMatch at /articles/ Reverse for 'article' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: \ ['articles/(?P\<slug\>\[-a-zA-Z0-9\_\]+)/\\Z'\] The affected line is : \<h2\>\<a href="{% url 'articles:article' slug=article.slug %}"\>{{ article.titre }}\</a\>\ </h2\> 3 times I try to perform the same code as in the lesson but I need your help. urls.py from django.contrib import admin from django.urls import path, include from articles import views app_name = "articles" urlpatterns = [ path('', views.articles_view, name='articles'), path('<slug:slug>/', views.article_view, name='article') ] template_base.html <!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <title>{% block titre %}{% endblock %}</title> </head> <body> <ul style="list-style: none"> <li style="display: inline-block; padding: 10px 20px;"> <a href="{% url 'home' %}">Accueuil</a> </li> <li style="display: inline-block; padding: 10px 20px;"> <a href="{% url 'articles:articles' %}">Articles</a> </li> <li style="display: inline-block; padding: 10px 20px;"> <a href="{% url 'contact' %}">Contact</a> </li> </ul> {% block contenu %} {% endblock %} </body> </html> view.py from django.shortcuts import render from django.http import HttpResponse from articles.models import Article def articles_view(request): articles = Article.objects.all() return render(request, 'articles/list.html', context={'articles': articles}) def article_view(request, slug): return HttpResponse("Page d'article") -
Django filter on list of column values
I'm using Django 3.2 and Postgres 13. I have a simple model: from django.db import models class Member(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE) group = models.ForeignKey("Group", on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint( fields=["user", "group"], name="unique_user_group_tuple" ) ] The important info here is the UniqueConstraint, which also creates a unique index. Let's say I have a list of (user_id, group_id) tuples: member_tuples = [(1, 1), (2, 1), (2, 4)] I would like to retrieve all existing Member objects matching these tuples, while using the index. In PG, I would write: SELECT * from members where (user_id, group_id) in ((1, 1), (2, 1), (2, 4)); My question is: how to get something similar in Django ? Obviously, my main concern is to keep calling the unique_user_group_tuple index, to avoid a sequential scan For now, the best solution I found is to do: filters = Q() for user_id, group_id in member_tuples: filters |= Q(user_id=user_id, group_id=group_id) existing_members = Member.objects.filter(filters) which translates to SELECT * from members WHERE (issue_id = 1 AND group_id = 1) OR (issue_id = 2 AND group_id = 1) OR (issue_id = 2 AND group_id = 4); This also queries the index, but it does not creates the query I expect. … -
CSS Rating Start not checking after click
CSS /* Hide Radio button */ .rate > input{ display: none; } .rate{ display: inline-block; border: 0; } .rate > label{ float: right; } /* Showing the stars */ .rate > label:before{ display: inline-block; font-size: 1.1rem; font-family: FontAwesome; content: "\f005"; margin:0; padding:0.3rem .2rem; cursor: pointer; } /* Half star */ .rate .half:before{ content: "\f089"; position: absolute; padding-right: 0; } /* Click and hover */ input:checked ~ label, label:hover ~ label{ color: #ffb503; } /* Hover highlight */ input:checked + label:hover, input:checked ~ label:hover, input:checked ~ label:hover ~ label, label:hover ~ input:checked ~label{ color: #cc9000; } I try to click on starts and remains saved at least on frontend to see them as checked but after i click one start it don't remain with that color, instead it remains the same as the beginning. How to fix it so after i click to see the input ( to see the stars colored ) -
Django website error 500 when uploading while using AWS
I am running a Django website on an EC2 instance while having my static files on S3 Bucket Storage and every time I try to upload something the post request returns Error Code 500 Internal Server Error. The code works locally with the bucket storage, but it doesn't work with the EC2 instance. -
Django developtment page does not load on Cloud server
i have bought an ionos cloud (linux/ubuntu) server with: 1v Core Cpu and 1gb of RAM When i try to host the developtment server (with manage.py runserver) everythin works fine, but when i then try to connect to that server, there is simply a problem loading the page, as if this page isnt avaible. Note that i didnt install anything else than Django and the requirements for my Project, so no ngix or something. But what i did is i have set up an UFW firewall to block every port except of port 8000 (on which i am running the testserver) If you guys have any ideas or questions pls let me know. PS: its 100% not my Internet connection. PLS and Thank you.:)