Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deploy a Django+React App to Herocu?
I've tried many tutorials but I failed to deploy my application specially with handling the static files, can you recommend me a good working tutorial. Thanks alot. -
Unique together causes IntegrityError
Django==4.1 I have stipulated a unique together constraint. Then I try to check whether it really works. But I have an IntegrityError. I hoped that a unique together constraint will raise ValidationError. But it didn't happen. Could you help me understand whether I'm wrong with my supposition about ValidationError in this case. And how to cope with this problem (which method to redefine and how)? Model class Task(PriorityMixin, CommentMixin, ): # n-fipi cypher = models.CharField( max_length=255, null=False, default="", ) fipi_section = models.ForeignKey("fipi_site_sections.FipiSection", on_delete=models.CASCADE, null=False, blank=False) page = models.PositiveIntegerField(null=False, blank=False, default=0) task_description = models.ForeignKey("fipi_task_descriptions.TaskDescription", on_delete=models.CASCADE, null=False, blank=False) def __str__(self): return self.cypher class Meta: ordering = ['fipi_section', 'page', 'priority', ] constraints = [ models.UniqueConstraint(fields=['fipi_section', 'page', 'priority', ], name='fipi_section-page-priority') ] Traceback Environment: Request Method: POST Request URL: https://aux.academic.gift/whibrsp1tapre4rl/fipi_tasks/task/add/ Django Version: 4.1 Python Version: 3.10.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'isbn_field', 'general', 'fipi_exam_parts', 'fipi_exam_sections', 'fipi_site_sections', 'fipi_task_descriptions', 'fipi_tasks', 'fipi_options', 'vocabulary_sources', 'vocabulary_units', 'vocabulary_exercises', 'vocabulary_phrases', 'vocabulary_videos', 'vocabulary_options'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/g/grablmz2/aux.academic.gift/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/g/grablmz2/aux.academic.gift/venv/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) File "/home/g/grablmz2/aux.academic.gift/venv/lib/python3.10/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/home/g/grablmz2/aux.academic.gift/venv/lib/python3.10/site-packages/MySQLdb/cursors.py", line 319, in _query … -
django: How add to database by loop corectly?
I am trying to save in the database all fights for a given group (everyone with everyone) at the same time from the form taking the number of rounds for each of the fights, so far the function does not add anything to the database. I am not sure if it can be added in a loop like this following the list of pairs: [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4 ), (2, 5), (3, 4), (3, 5), (4, 5)] and refer to the indexes of list items when creating combat objects to save def add_fights(request, group_id): group = Group.objects.get(pk=group_id) tournament = group.tournament participants = group.participants.all() participants_ids = participants.values('id') only_ids_ls = [i.get('id', 0) for i in participants_ids] participants_pairs = list(itertools.combinations(only_ids_ls, 2)) group.fighters_one = [p[0] for p in participants_pairs] group.fighters_two = [p[1] for p in participants_pairs] print(participants_pairs) if request.user.is_authenticated: form = AddGroupForm(request.POST) if request.method == "POST" and form.is_valid(): rounds = form.cleaned_data['rounds'] obj = form.save(commit=False) if obj: for p in participants_pairs: obj.group = group obj.rounds = rounds obj.tournament = tournament obj.fighter_one = group.participants.get(id=p[0]) obj.fighter_two =group.participants.get(id=p[1]) obj.save() print("obj") print(obj) group.fights.create(group=group, rounds=rounds, tournament=tournament, fighter_one=obj.fighter_one, fighter_two=obj.fighter_two) return HttpResponseRedirect(reverse("tournaments:tournament_details", args=[group_id])) else: form = AddFightsForm return ( render(request, "add_fights.html", context={ 'form': form, … -
Bringing Select-Option values to Select-Option
I made a drop-down field that I created with select-option, after saving the data I selected here, when I enter the update form, I want the data selected in the save form to be selected again, can you help with this? insert.html <select name="healmedy_car_info" id="healmedy_car_info" class="form-select" aria-label="Default select example"> <option value="selectcar">Lütfen Araç Seçiniz</option> <option value="34SAS20">34 SAS 20</option> <option value="34SAS30">34 SAS 30</option> <option value="34BF2904">34 BF 2904</option> <option value="34TP0633">34 TP 0633</option> <option value="34BF9529">34 BF 9529</option> </select> update.html <select name="healmedy_car_info" id="healmedy_car_info" class="form-select" aria-label="Default select example"> <option value="selectcar">Lütfen Araç Seçiniz</option> <option value="34SAS20">34 SAS 20</option> <option value="34SAS30">34 SAS 30</option> <option value="34BF2904">34 BF 2904</option> <option value="34TP0633">34 TP 0633</option> <option value="34BF9529">34 BF 9529</option> </select> I pull the data with django and save it to the database, I just want the data I pulled here to be selected in update.html. -
Is it possible to use aggregate on a queryset annotation?
I am using annotate on a django queryset: class MyModel(models.Model): my_m2m = models.ManytoManyField() my_qs = MyModel.objects.all().annotate(total_m2m=Count('my_m2m')) This yields the desired result. E.g: >>> my_qs[0].total_m2m >>> 3 How do I use aggregate to count the total number of my_m2m in the queryset? E.g. >>> my_qs.aggregate_m2m >>> 9 -
Django DETAIL: Failing row contains (11, SG 553, BATTLE-SCARRED, CLASSIFIED, NORMAL, RIFLE, null, 6235.05)
task to create Weapon objects: def populate_weapon_objects(amount: int = 1) -> None: for _ in range(amount): weapon = Weapon.objects.create( name=_get_random_name(), exterior=_get_random_exterior(), quality=_get_random_quality(), category=_get_random_category(), price=_get_random_price(), ) Weapon model: class Weapon(models.Model): ... name = models.CharField(max_length=64, choices=WEAPONS, db_index=True) exterior = models.CharField(max_length=64, choices=EXTERIOR, default=EXTERIOR_FACTORY_NEW, db_index=True) quality = models.CharField(max_length=64, choices=QUALITY, default=QUALITY_CONSUMER_GRADE, db_index=True) category = models.CharField(max_length=64, choices=CATEGORY, default=CATEGORY_NORMAL, db_index=True) type = models.CharField(max_length=64, editable=False, db_index=True) slug = models.SlugField(max_length=64, editable=False, unique=True, db_index=True) price = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(10**4)], db_index=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if not self.type: self.type = self._get_type_by_name() if not self.slug: self.slug = self._get_slug() return super().save(*args, **kwargs) def _get_type_by_name(self) -> str: return next(k for k, v in self.NAME_TO_TYPE_DICT.items() if self.name in v) def _get_slug(self) -> None: self.slug = generate_slug(self) generate_slug function: def generate_slug(weapon) -> str: name = weapon.name exterior = weapon.exterior quality = weapon.quality category = weapon.category sequence = [name, exterior, quality, category] slug = slugify(' '.join(sequence)) return slug This leads to: django.db.utils.IntegrityError: null value in column "slug" of relation "weapons_weapon" violates not-null constraint celery-worker | DETAIL: Failing row contains (14, PP-BIZON, MINIMAL WEAR, RESTRICTED, NORMAL, SMG, null, 7354.3, 2022-09-15 13:15:43.75499+00, 2022-09-15 13:15:43.754978+00). Why this happens? Why the type field is being filled when creating an Weapon objects and slug field keeps crashing … -
Yandex webvisor error peticiones cada 2 segundos
No se por que me aparecen unas peticiones a mi sitio que dicen Yandex webvisor, no he añadido nada que tenga que ver con Yandex, Yandex error peticiones Estas son las peticiones que se repiten cada 2 segundos: peticion yandex 2 peticion yandex 1 Me gustaria desactivarlas pero no encuentro nada de información en internet -
Filter records by lookup in the same table
Suppose we have a table: +--------------- ... | id | old_id | +--------------- ... | ... How do I select all values by some custom criteria except where id is found in column old_id? I've tried: records = MyRecords.objects\ .filter(<my custom criteria>)\ .exclude(id__in=models.OuterRef('old_id'))\ .order_by('-modified_at') and other variations, but to no avail. Basically, I am trying to achieve this behavior: select * from mytable where <custom criteria> and not id in (select old_id from mytable where 1) -
Which database would be best for simple e-commerce site?
I am newbie for designing and programming. I'm working personal project to make e-commerce site in django. Will MySql or Postgresql be better suit for a e-commerce website? As far I know reading data mysql is fast if there is read from database more. What would be best suit for e-commerce site? -
Django app gets stuck after sometime that the server is running
i am facing an issue with my Django application. After i build the container and i have my Django app working fine after some time in use, it just gets stuck. For example i try to log in and it is just loading infinitely and i have to restart the container in order to have the application up running again. Is this issue happening for any specific reason, and can someone help me so i avoid restarting the container anytime this happens? I have also tried changing the templates configuration in the settings.py file from: DIR:[] to 'DIRS': [os.path.join(BASE_DIR, 'templates')] but it still happens. -
Django app - Browse a dictionary with sub arrays
I would like to browse and display this dictionary which contains other sub-tables inside Here I would like to display the purchases of "fafa" only Views.py def app(request): dict= { "toto": "tata", "messages": [ { "mont": "ton", "fafa": "fki" } ], "commandes": [ { "numero": "h221g", "date": "14-07-22", "reference": "ref1", "name": "fafa", "purchases": [ { "article": "articlename", "designation": "laptop", "quantity": 2, "price": 133 }, { "article":"article2", "designation":"Dell" "quantity":3, "price":144 }, ... ] }, .... ] } mes_ventes=dict['commandes'] purchases=dict['commandes'][0]['purchases'] context={'commandes':mes_ventes,'lignes':mes_lignes} return render(request,'test/test.html',context) test.html {% for commande in commandes %} {% if commande.name == "fafa" %} {% for ligne in lignes %} <p>{{ligne.article}}<br>{{ligne.designation}}<br> {{ligne.quantity}}<br> {{ligne.price}}</p> {% endfor %} {% endif %} {% endfor %} It shows me purchases but that of "fafa" -
Handle Django Rest Framework permission when creating related objects
The has_object_permission method of a Permission on DRF obviously does not get executed on Create, since the object does not exist yet. However, there are use cases where the permission depends on a related object. For example: class Daddy(models.Model): name = models.CharField(max_length=20) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Kiddy: title = models.CharField(max_length=12) daddy = models.ForeignKey(Daddy, on_delete=models.CASCADE) If we only want to allow the owner of Daddy to create Kiddy of that Daddy, we would have to validate that somewhere. I know this a really common discussion, also mentioned on this question and in many many more. It is also discussed on DRF GitHub itself where a docs update is done for that purpose, and referring to DRF docs it solves the problem here with the following sentence: ... In order to restrict object creation you need to implement the permission check either in your Serializer class or override the perform_create() method of your ViewSet class. So, referring to DRF docs, we could do one of the following solutions: class KiddySerializer(viewsets.ModelViewSet): validate_daddy(self, daddy): if not daddy.owner == self.context['request'].user: raise ValidationError("You cannot create Kiddies of that Daddy") return daddy or class KiddyViewSet(ModelViewSet): def perform_create(self, serializer): if (self.request.user != serializer.validated_data['daddy'].owner) raise ValidationError("You cannot create … -
How to get a value from the result of queryset and assign it
How to get a value from the result of queryset and assign it I've got a result of queryset <QueryDict: {'payment_id': ['KIAhwplaq0qgx8'], 'pay_order_id': ['order_KIAhsgbBDXth83'], 'result': ['5e5ab4f08a09915aa4791d25315b565beb62efe52fae71de877e2818d266f538']}> I want those values to be assigned like this payment_id = 'KIAhwplaq0qgx8' pay_order_id = 'order_KIAhsgbBDXth83' result = '5e5ab4f08a09915aa4791d25315b565beb62efe52fae71de877e2818d266f538' Even the queryset code to get a value AND ASSIGNING IT IS FINE BUT i Don't KNOW How. If anyone knows. Please share it. It would be Helpful -
django annotate one model queryset with another model's queryset method
I am not sure if what I want to do can be done. I want to filter or exclude elements from one QuerySet object, using the annotated values of the QuerySet of another model, related to the first via FK. models Below an overview of the models I'm talking about: the two models sit in my main.models.py a Member class and its Manager from django.db import models from django.contrib.auth.models import UserManager class MemberManager(UserManager): def get_queryset(self): return MemberQuerySet(self.model, using=self._db) def annotate_something(self): return self.get_queryset().annotate_something_important() class Member(User): objects = MemberManager() field_1 = models.BooleanField(default = False) field_2 = models.CharField(max_length = 1, blank = True, null = True) ... an Experience class and its Manager class ExperienceManager(models.Manager): def get_queryset(self): return ExperienceQuerySet(self.model, using=self._db) def annotate_duracion(self): return self.get_queryset().annotate_duracion() class Experience(models.Model): objects = ExperienceManager() member = models.ForeignKey(Member, related_name='experiences', on_delete = models.CASCADE) start_date = models.DateField(blank = True, null = True) end_date = models.DateField(blank = True, null = True) note the FK in Experience to Member both MemberQuerySet and ExperienceQuerySet classes are defined in a separate main.queryset.py file class MemberQuerySet(models.QuerySet): def annotate_something_important(self): return self.something_important ... class ExperienceQuerySet(models.QuerySet): def annotate_duration(self): current_date = datetime.now().date() return self.annotate( end_date_obj = Case( When(end_date = None, then = Value(current_date)), default = F('end_date'), output_field = DateField(), ) … -
DRF multiple qyeryset serializer
need some help with serializers. I am a beginner in DRF. I query for objects and serialize each with their own model serializer then manually write down all serializer data in the response in json format. I am sure there is a better way to do this that could also be more efficient. Currently my code looks like this: class GetData(APIView): permission_classes = [IsAuthenticated] def get(self, request): user = request.user subjects = Subject.objects.all() serializersubject = SubjectSerializer(subjects, many=True) subject_skill_levels = SubjectSkillLevel.objects.filter(user=user) serializer2 = SubjectSkillLevelSerializer(subject_skill_levels, many=True) topic_skill_levels = TopicSkillLevel.objects.filter(user=user) serializer3 = TopicSkillLevelSerializer(topic_skill_levels, many=True) progress = Progress.objects.filter(user=request.user).order_by("-date") todays = progress[:1][0] last_5_days = progress.exclude(id=todays.id)[:5] todays_serializer = ProgressSerializer(todays) last_5_days_serializer = ProgressSerializer(last_5_days, many=True) history = ExerciseToken.objects.filter(user=request.user, completed=True).order_by("-id") history_serializer = HistorySerializer(history, many=True) notes = Note.objects.filter(user=request.user) notes_serializer = NotesSerializer(notes, many=True) data = { "username": user.username, "subjects": serializersubject.data, "skill_level": { "subjects" : serializer2.data, "topics" : serializer3.data }, "progress": { "todays": todays_serializer.data, "last_5_days": last_5_days_serializer.data }, "history": history_serializer.data, "notes": notes_serializer.data } return Response(data) -
Running Django Project in PyCharm: ModuleNotFoundError: No module named 'sql_server' - windows10
I was given a zipped django project from others, and after unzipped it, I directly openned it with pyCharm. The directory is as follows, Project logs App Project templates venv db.sqlite3 manage.py It was my very first time using Django, sqlite and Pycharm. It seems like PyCharm could directly connect to the db.sqlite3 database, therefore I did so. And when I ran python manage.py runserver, everything seemingly worked just fine - PS C:\Users\dell\Project> python manage.py runserver engine: Engine(mssql+pyodbc://LAPTOP-RITC6JLO/nlp_db?driver=ODBC+Driver+17+for+SQL+Server&trusted_connection=yes) create engine: mssql+pyodbc://LAPTOP-RITC6JLO/nlp_db?driver=ODBC+Driver+17+for+SQL+Server&trusted_connection=yes engine: Engine(mssql+pyodbc://LAPTOP-RITC6JLO/nlp_db?driver=ODBC+Driver+17+for+SQL+Server&trusted_connection=yes) create engine: mssql+pyodbc://LAPTOP-RITC6JLO/nlp_db?driver=ODBC+Driver+17+for+SQL+Server&trusted_connection=yes Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 15, 2022 - 20:13:53 Django version 4.0.7, using settings 'Project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. But when I openned http://127.0.0.1:8000/, the page shown A server error occurred. Please contact the administrator. with web console giving Failed to load resource: the server responded with a status of 500 (Internal Server Error) 127.0.0.1/:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) Then the project terminal gave Traceback (most recent call last): File "C:\Users\dell\anaconda3\lib\site-packages\django\db\utils.py", line 113, in load_backend return import_module("%s.base" % backend_name) File "C:\Users\dell\anaconda3\lib\importlib\__init__.py", line 127, in import_module … -
use the next of the url in the custom login view
I have this customized views login the problem is that when I have a view with the decorators login the url with next does not work but it redirects me to the page I marked in my customized views class Login(auth_views.LoginView): def get_success_url(self): if self.request.user.is_superuser: return reverse('dashboard') else: return reverse('homepage') -
How to choose default choice field from a list
In a django model I need to set a default for a choice field but I don't get how to do the syntax part This is the list CHAT_STYLES = [ ("orange", "orange"), ("purple", "purple"), ("aquamarine", "aquamarine"), ("aqua", "aqua"), ("beige", "beige"), ("yellow", "yellow"), ("green", "green"), ("blue", "blue") ] I tried to do like this chat_styles = models.CharField(max_length=2, choices=CHAT_STYLES, default=CHAT_STYLES."purple") or chat_styles = models.CharField(max_length=2, choices=CHAT_STYLES, default=CHAT_STYLES["purple"]) but it didn't work -
problemas ao criar uma querySet ao fazer uma consulta em loop
Bom dia, tenho esse codigo abaixo que faz uma consulta para buscar ids cadastrados e apos isso, eu percoro essa lista e pego o ID dessa queryset, gero outra consulta com este ID... o meu problema e que essa variavel loadcartrep dentro do loop retorna uma lista [valor1, valor2] e não uma queryset<[valor1:'1', valor2:'2']> e assim não consigo acessar os registros no html para exibir. alguem consegue me ajudar a como eu faço para que essa agregação na variavel loadcarrep+= crie uma lista queryset ou alguma forma de como acessar ou fazer essa consulta com loop funcional? loadcartrep = [] loadcart = carrinho.objects.filter(id_empresa_id=empresa, status__range=[0, 1]) for l in loadcart: log = PecasReposicao.objects.filter(codigoSap=int(l.codigoSap)) if log: loadcartrep = log -
Django hidden field value is not in POST data
I need to send form data via POST request to save a new model instance to DB. I have a hidden field name="owner" in html wich has a value of authorized user id. I can see this value in HTML code, but not in POST request. This gives me Chrome Devtools: <input type="hidden" id="owner" name="owner" value="3"> And this gives me a pyCharm's debugger: cleaned_data = {'latitude': 55.2288, 'longitude': 24.3686, 'comment': '', 'category': <Category: Host>} What is the problem? I have this code in Django views.py: if request.method == "POST": form = AddMarkerForm(request.POST) if form.is_valid(): form.save() messages.success( request, _("Marker added successfully!"), extra_tags="success" ) return redirect(to="home") else: messages.error(request, _("Error. Check coordinates."), extra_tags="danger") else: form = AddMarkerForm() And html: <form class="row g-3" method="post" enctype="multipart/form-data" id="addMarkerForm" name="addMarkerForm"> {% csrf_token %} {% for field in form.visible_fields|slice:":2" %} <div class="col-md-6"> {{ field }} </div> {% endfor %} {% for field in form.visible_fields|slice:"2:" %} <div class="col-12"> {{ field }} </div> {% endfor %} <input type="hidden" id="owner" name="owner" value="{% if request.user %}{{ request.user.id }}{% endif %}"> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% translate "Close" %}</button> <button type="submit" name="submit" class="btn btn-primary">{% translate "Add" %}</button> </div> </form> A form code in forms.py: class AddMarkerForm(forms.ModelForm): """Form for adding a new … -
Django formset not saving with particular code
I have a helper function to save a formset for the model Fields. This function does not save any records, unless I remove a specific piece of code. code that does not save: @transaction.atomic def update_fields_and_fields_group(formset, fg_id, fg_name, ordered_ids): fg = FieldsGroup.objects.get(pk=fg_id) fg.name = fg_name fg.save() # store fields as dictionary fields_list = Fields.objects.filter(fields_group__pk=fg_id) fields_dict = {} for f in fields_list: fields_dict[f.id] = f num_fields = len(fields_dict) # save values instances = formset.save(commit=False) print(instances) for fields in instances: # populate order for new fields with order at the end if not fields.id: fields.order = num_fields + 1 # populate FK fields.fields_group_id = fg_id print(fields.id) fields.save() # save order current_order = 1 for id in ordered_ids: # id is none for new rows if id == 'None': continue fields = fields_dict[int(id)] fields.order = current_order current_order += 1 fields.save() code that does save: @transaction.atomic def update_fields_and_fields_group(formset, fg_id, fg_name, ordered_ids): fg = FieldsGroup.objects.get(pk=fg_id) fg.name = fg_name fg.save() # store fields as dictionary # fields_list = Fields.objects.filter(fields_group__pk=fg_id) # fields_dict = {} # for f in fields_list: # fields_dict[f.id] = f # num_fields = len(fields_dict) # save values instances = formset.save(commit=False) print(instances) for fields in instances: # populate order for new fields with order at … -
Image from an ImageField ModelForm not uploading into the server
Hi so I am new to Django and one of the things I'm trying to do is make a simple gallery application. Somehow I can't add images through the server via the forms if I use a Model Form although I can do it using a plain form. I've tried a lot of the stuff in here and also tried some Youtube stuff but it didn't still work. Here is my models.py from django.db import models from django.urls import reverse from django.core.validators import validate_image_file_extension from django.core.files.storage import FileSystemStorage fs = FileSystemStorage(location='/media') class FavoriteImages(models.Manager): def get_queryset(self): return super().get_queryset().filter(favorite=True) # Create your models here. class Photo(models.Model): name = models.CharField(max_length=120, null=True) photo = models.ImageField(storage=fs, upload_to='media/', validators=[validate_image_file_extension]) date_uploaded = models.DateTimeField(auto_now=True) favorite = models.BooleanField(default=False, blank=False) slug = models.SlugField(null=True, blank=True) gallery = models.Manager() gallery_favorites = FavoriteImages() class Meta: ordering = ['-date_uploaded'] My Views.py from PIL import Image def image_new(request, *args, **kwargs): Image.init() form = PhotoForm(data=request.POST, files=request.FILES) if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): form.save() redirect('../all') context = { 'form': form } return render(request, "form.html", context) My forms.py class PhotoForm(forms.ModelForm): name = forms.CharField(label='',widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Title'})) photo = forms.ImageField(widget=forms.FileInput(attrs={'class':'form-control'})) favorite = forms.BooleanField(label='Mark as Favorite',widget=forms.CheckboxInput(attrs={'class':'form-check-input'})) class Meta: model = Photo fields = ['name', 'photo', 'favorite'] my .html … -
AWS Beanstalk django and reactjs app 504 error when registering?
I am trying to get a django REST framework api with reactjs as frontend to work on Beantstalk. The pages are now showing, however when I try to register I get a 504 error. Looking at the logs: First error: /var/log/nginx/error.log 2022/09/14 15:39:29 [error] 4456#4456: *1127 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.32.240, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "django-env1.eba--.us-west-2.elasticbeanstalk.com" /var/log/web.stdout.log Sep 15 10:51:30 ip-172-31-29-189 web: Traceback (most recent call last): Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection Sep 15 10:51:30 ip-172-31-29-189 web: self.connect() Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner Sep 15 10:51:30 ip-172-31-29-189 web: return func(*args, **kwargs) Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/base/base.py", line 225, in connect Sep 15 10:51:30 ip-172-31-29-189 web: self.connection = self.get_new_connection(conn_params) Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner Sep 15 10:51:30 ip-172-31-29-189 web: return func(*args, **kwargs) Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 244, in get_new_connection Sep 15 10:51:30 ip-172-31-29-189 web: connection = Database.connect(**conn_params) Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/MySQLdb/init.py", line 123, in Connect Sep 15 10:51:30 ip-172-31-29-189 web: return Connection(*args, **kwargs) Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/MySQLdb/connections.py", line 185, in … -
Dockerizing Django. How to reload each time I make changes to my code [duplicate]
I am dockerizing my Django app and I have the following docker-compose.yml file: version: '3' services: # other services as db etc. web: container_name: web build: context: . dockerfile: Dockerfile.web restart: 'always' env_file: - csgo.env ports: - '8000:8000' volumes: - web:/code depends_on: - db volumes: web: I want my container (or the app, idk) to reload whenever I let's say make changes to my models or functions etc. For now, I add some functionality to my app, edit some html views, but no changes appears and the app logs doesn't say that it's reloading. I have to rebuild and up my compose again to see my changes. How to do live-reload composing up? How to send changes to docker? Should I do something with wsgi or gunicorn? I need broad explanation please! Thanks! -
Django 'QuerySet' object has no attribute
With this model: class Batch(models.Model): product = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) stock = models.IntegerField() expiration = models.DateField() This view: @api_view(['GET']) def getByProduct(request, product_name, format=None): try: batches = Batch.objects.filter(product=product_name) except Batch.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = BatchSerializer(batches) return Response(serializer.data, status=status.HTTP_200_OK) And this URL: path('get_by_product/<str:product_name>/', views.getByProduct), I get the following error when running this: http://127.0.0.1:8000/get_by_product/Potatoes/ Got AttributeError when attempting to get a value for field `product` on serializer `BatchSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'product'. However if I force a different error I get this: Cannot resolve keyword 'many' into field. Choices are: created, expiration, history, id, product, stock I cannot .get() as that query expects many batches with the same property "product".