Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.ProgrammingError: (1146, "Table 'ITnews$default.auth_user' doesn't exist")
when I do: python manage.py migrate I get: django.db.utils.ProgrammingError: (1146, "Table 'ITnews$default.auth_user' doesn't exist") I trying to deploy my website in pythonanywhere. And I cannot to connect site and mysql. Database settings in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ITnews$default', 'USER': 'ITnews', 'PASSWORD': 'mypass', 'HOST': 'ITnews.mysql.pythonanywhere-services.com', } } :) -
Group By with Django's queryset
I have a model in Django and this is how it looks like with fewer fields - I want to group the rows w.r.t buy_price_per_unit and at the same time I also want to know the total units on sale for that buy_price_per_unit. So in our case only two distinct buy_price_per_unit are available (9, 10). Hence the query would return only two rows like this - The one last condition which I have to meet is the query result should be in descending order of buy_price_per_unit. This is what I have tried so far - orders = Orders.objects.values('id', 'buy_price_per_unit')\ .annotate(units=Sum("units"))\ .order_by("-buy_price_per_unit")\ The response for the query above was - [ { "id": 13, "buy_price_per_unit": 10, "units": 1 }, { "id": 12, "buy_price_per_unit": 9, "units": 10 }, { "id": 14, "buy_price_per_unit": 9, "units": 2 }, { "id": 15, "buy_price_per_unit": 9, "units": 1 } ] The problem with this response is that even for the same price multiple records are being returned. -
Django RestFramework Nested List view
I want to nest only the ListView of my objects like this: { "Organisations": [{ "OrganisationName": "Organisation1", "OrganisationID": "ABC12345" }, { "OrganisationName": "Organisation2", "OrganisationID": "XYZ12345" } ]} However I can only get results like this: [ { "OrganisationID": "Organisation1", "OrganisationName": "ABC12345" }, { "OrganisationID": "Organisation2", "OrganisationName": "XYZ12345" } ] models.py: from django.db import models class Organisation(models.Model): """Model class for the Atomo Organisations""" OrganisationName = models.CharField(max_length=60, blank=True, null=True, default="") OrganisationID = models.CharField(max_length=60, unique=True, blank=True, null=True, default="") class Meta: ordering = ['OrganisationName'] def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return self.OrganisationName serializers.py: from rest_framework import serializers from ndx_org.models import Organisation class OrgSerializer(serializers.ModelSerializer): class Meta: model = Organisation fields = ["OrganisationID", "OrganisationName"] views.py: from ndx_org.models import Organisation from ndx_org.api.serializers import OrgSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class OrgList(APIView): def get(self, request, format=None): orgs = Organisation.objects.all() serializer = OrgSerializer(orgs, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = OrgSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have tried to nest the serializer but I nests every object. What I need is a nested result of the object lists. How can I do it? Thanks for … -
Updating multiple checkboxes forms with Django
in my django website I'm trying to building a page in which there are multiple forms (In particular 3: the first is simply a checkbox, as the second one. The third one requires the entering of two text fields). I've already managed the presence of multiple forms and I've no problem when the user performs the first assignment. The problem is instead during the updating of the answers that the user gave the first time: there are no problems when adding new instances of the text fields of the third form, while instead if I've selected one checkbox of the first two forms and I want to change them unchecking them it seems like django doesn't save the new values. Any idea of why it's happening? Here's the view associated: def new_4e2(request, pk, var=None): if Specifiche.objects.filter(ID_rich = pk).exists(): specs = Specifiche.objects.filter(ID_rich = pk) choicesp =[] lista =[] for spec in specs: choicesp+=[(spec.id, str(spec.rif))] lista+=[spec.id] att = MAIN.objects.get(id=pk) unform = FormUn(instance=att) data = {'ID_rich': pk} form = UnicitaForm(initial=data) form.fields['rifext'].choices = choicesp if Unicita.objects.filter(rifext__in = lista).exists(): uns=Unicita.objects.filter(rifext__in = lista) context={ 'att': att, 'uns': uns, 'var':var, 'specs': specs } else: context = { 'att': att, 'var':var, 'specs': specs, } form = UnicitaForm(initial = … -
how to completely hide a particular form field for users in django
I want to completely hide the fields in the form, now only the field is hidden, but the name of the field remains. I don't want the name or anything to show about the field. take a look at my code. class RechargeDataForm (forms.ModelForm): def __init__(self, *args, **kwargs): from django.forms.widgets import HiddenInput hide_condition = kwargs.pop('hide_condition',None) super(RechargeDataForm, self).__init__(*args, **kwargs) if hide_condition: self.fields['idnetwork'].widget = HiddenInput() self.fields['idplan'].widget = HiddenInput() # or alternately: del self.fields['fieldname'] to remove it from the form altogether. class Meta: model = RechargeData fields = '__all__' exclude = ('user', 'user', 'type', ) this code below brought the same outcome too- the field disappears why field name remains #widgets = { # 'idplan': forms.TextInput(attrs={'type': 'hidden'}), #} models.py file. class RechargeData(models.Model, Main): networks = models.ForeignKey(Networks, default=1,on_delete=models.CASCADE, verbose_name="networks") circle = ChainedForeignKey( "Circle", chained_field="networks", chained_model_field="networks", show_all=False, auto_choose=True, sort=True ) plans = ChainedForeignKey( "Plans", chained_field="circle", chained_model_field="circle", show_all=False, auto_choose=True, ) user = models.ForeignKey(User, default=1,on_delete=models.CASCADE) mobile_number = models.CharField( max_length=11, blank=True, null=False) # validators should be a list timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) idnetwork = ChainedForeignKey( "IdNetwork", chained_field="networks", chained_model_field="networks", show_all=False, auto_choose=True, sort=True ) idplan = ChainedForeignKey( "IdPlan", chained_field="circle", chained_model_field="circle", show_all=False, auto_choose=True, sort=True ) I want the field remove permanetly without affecting my form validation. something like this refused to … -
Formset saved duplicate entries
My system allows user to add questions to form when clicking on Add More button. I am using formset to create and add new question. I am trying to save the formset to database however, when saving to database i noticed that there are duplicated entries. How to prevent duplicate entries/ save only the new entries from the formsets. add_quiz_questions.html {% load crispy_forms_tags %} <div class="container-fluid p-5"> <!-- Main Content Here --> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ questionformset.management_form }} <div id="question-form-list"> {% for question in questionformset %} <script type="text/javascript" src="/static/selectable/js/jquery.dj.selectable.js"></script> <div class="card shadow mb-4"> <div class="question-form"> <div class="card-body"> {{ question|crispy }} </div> </div> </div> {% endfor %} </div> <div id="empty-form" style="display: none;"> <div class="card shadow mb-4"> <div class="card-body"> {{ questionformset.empty_form|crispy }} </div> </div> </div> <button type="button" class="btn btn-info" id="add-more"> Add Question</button> <button type="submit" class="btn btn-primary">Save</button> </form> </div> <!-- /.container-fluid --> </div> <script> $('#add-more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#question-form-list').append($('#empty-form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> views.py def createQuizQuestion(request,pk): user_id = Users.objects.get(user=request.user) quizzes = Quiz.objects.get(id=pk) for row in QuizQuestion.objects.filter(quiz=quizzes).reverse(): if QuizQuestion.objects.filter(quiz_id=row.quiz_id, question=row.question).count()>1: print(row) question = QuizQuestion.objects.filter(quiz=quizzes) QuestionFormSet = modelformset_factory(QuizQuestion, form=QuizQuestionForm, extra=0) questionformset = QuestionFormSet(request.POST or None, queryset=question) if request.method == "POST": questionformset = QuestionFormSet(request.POST or None, queryset=question) if questionformset.is_valid(): … -
Color table cells for reservation system Django
I am trying to develop a reservation system based on a Django project. My final goal is to have something like that: Until now, what I was able to achieve is to have the table with the times of the day and the column (which are aicrafts). My final goal is to have my reservations displayed as "legs", meaning that, for example a reservation from 09:00 until 11:00 is displayed in the aircraft cells between 09:00 up to 11:00. In fact, what I'd need to achieve is to have each single table cell or group of cells colored to advise that the airplane is booked for that period of time. So far my code is something like that: models.py class AirportTime(models.Model): aerodrome = models.ForeignKey(Aerodrome, on_delete=models.CASCADE, blank=True, null=True) opening_time = models.TimeField() closing_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.opening_time) + ' ' + str(self.closing_time) class Booking(models.Model): aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) student = models.ForeignKey( Student, on_delete=models.CASCADE, blank=True, null=True) instructor = models.ForeignKey( Instructor, on_delete=models.CASCADE, blank=True, null=True) date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.aircraft.registration + ' ' + str(self.date) + ' ' + str(self.start_time) + ' ' … -
How to filter by year, month, or day in django graphene query
I am building a django graphql api with graphene for photography events. Each event has a location, photographer and event date. I want to be able to filter all events by year, month or day, e.g. return all events happening in April 2022 or all events that happen on Thursdays. I would also like to filter for future events only. The model: # models.py class Event(models.Model): STATUS = ( ("Scheduled", "Scheduled"), ("Cancelled", "Cancelled"), ("Available", "Available"), ("Complete", "Complete"), ) location = models.ForeignKey( Location, on_delete=models.SET_NULL, null=True, related_name="location_events" ) photographer = models.ForeignKey( Photographer, on_delete=models.SET_NULL, null=True, related_name="photographer_events", ) event_date = models.DateField() status = models.CharField(max_length=50, choices=STATUS, default="Scheduled") created = models.DateTimeField(auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint( name="location_event", fields=("location", "event_date") ) ] def __str__(self): return f"Event {self.location}, {self.event_date}, {self.status}" # schema.py from graphene_django import DjangoObjectType from graphene import relay, ObjectType from graphene_django.filter import DjangoFilterConnectionField from events.models import Event class EventNode(DjangoObjectType): class Meta: model = Event filter_fields = { "event_date": ["exact", "year", "month", "day"], "status": ["exact"], } interfaces = (relay.Node,) class EventsQuery(ObjectType): event = relay.Node.Field(EventNode) all_events = DjangoFilterConnectionField(EventNode) Using this set up, when I try to run this query on graphiql browser interface: query filterEvents{ allEvents(eventDate:"2022-02-14"){ edges{ node{ id eventDate photographer{ firstName lastName } location{ id name … -
Not able to get all the columns while using group by in Pandas df
controller.py def consolidated_universities_data_by_country(countries,universities): cursor = connection.cursor() query = None if countries == str(1): query = f""" @sql_query@ """ result_data=cursor.execute(query) result=dict_fetchall_rows(result_data) consolidated_df_USA=pd.DataFrame(result).fillna('NULL').replace( {True : 1, False : 0}).groupby('CourseId')['ApplicationDeadline'].apply(', '.join).reset_index() return consolidated_df_USA With the mentioned code i am able to get desired output i.e., i wanted to merge n rows deadline in one row for given courseid, but i am not able to get rest of the columns. consolidated_df_USA=pd.DataFrame(result).fillna('NULL').replace( {True : 1, False : 0}).groupby('CourseId')['ApplicationDeadline','CourseName'].agg(', '.join).reset_index() return consolidated_df_USA With this i am able to get some columns but some of the columns are getting depricated. Also getting below warning. FutureWarning: Dropping invalid columns in SeriesGroupBy.agg is deprecated. In a future version, a TypeError will be raised. Before calling .agg, select only columns which should be valid for the aggregating function. How to get all the columns which is given by sql query? -
Is it possible to get the name of IntegerChoices
I have IntegerChoices like this class Action(models.IntegerChoices): SYSTEM_START = 1 SYSTEM_STOP = 2 and model has this as the member class ActionLog(BaseModel): log_action = m.PositiveSmallIntegerField( choices=Action.choices,null=False) def action_name(self): // can I get the name such as SYSTEM_START here? then I want to return the readable name in action_name function of model. Is it possible?? or I should not use models.IntegerChoices? If so what should be used in this case? -
how to update record and same record create in other table in django form
i have 2 model one is Tempdriver and other one is Hiring, i am register new customer in Tempdriver table, i need when i edit tempdriver record and status is (accept) and when i save this record then need to same record create on hiring table with matching column with status=(Applied on app) rest column should be null in hiring table models.py class Tempdriver(BaseModel): name = models.CharField(max_length=255) mobile = models.CharField(max_length=20,unique=True,null=True, blank=True) alternate_number = models.CharField(max_length=20, null=True, blank=True) date = models.DateField(null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) status = EnumField(choices=['Accept','Reject','Hold'], null=True) class Hiring(BaseModel): STATUS_CHOICES = (('', 'Type...'), ('HR Interview Pass', 'HR Interview Pass'), ('HR Interview Fail', 'HR Interview Fail'), ('Allocation Completed', 'Allocation Completed'), ('Applied on app','Applied on app') ) name = models.CharField(max_length=254, null=True, blank=True) mobile = models.CharField(max_length=20,unique=True,null=True, blank=True) city = models.ForeignKey(City, models.CASCADE, verbose_name='City', null=True, blank=True) age = models.PositiveIntegerField(null=True, blank=True) status = models.CharField(max_length = 255,choices=STATUS_CHOICES, null=True, blank=True) forms.py class TempDriverForm(forms.ModelForm): class Meta: model= Tempdriver fields='__all__' views.py def edit_temp_driver(request,id=0): tempdr=Tempdriver.objects.get(pk=id) form= TempDriverForm(request.POST or None, request.FILES or None, instance=tempdr) if form.is_valid(): edit = form.save(commit=False) edit.save() messages.success(request,'Driver data updated successfully!') return redirect('/fleet/tempdr') return render(request, 'hiringprocess/edit_tempdriver.html', {'form':form}) -
Django FormWizard done function saves each step (form) as a separate instance in DB
I've searched all over for a solution to this but just can't figure it out. I feel the solution is quite simple but... I have a formwizard - class FormWizardView(SessionWizardView): template_name = "requests/data_change_requests.html" form_list = [dc_step1, dc_step2] def done(self, form_list,**kwargs): for form in form_list: form.save() return HttpResponseRedirect ('success.html') when the Done function is run, each step in the form is saved as a separate instance in the DB. how can I tie both form instances together and then save that so it is all in the instance? Thanks -
Django templates Could not parse the remainder
I have this template, I am looping through all choices in a question, and I want to default check the question user previously selected. selected_choice variable is coming from my view and I got have it ok in my template. {% extends 'base.html' %} {% block content %} <div id="detail" class=""> <form hx-post="{% url 'main:vote' question.id %}" hx-trigger="submit" hx-target="#detail" hx-swap="outerHTML"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %}<p> <strong>{{ error_message }}</strong> </p> {% endif %} {% for choice in question.choices.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" {% if selected_choice and choice.id==selected_choice %}checked{% endif %}> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} </fieldset> <button type="submit">Submit</button> </form> </div> {% endblock content %} I get this error Could not parse the remainder: '==selected_choice' from 'choice.id==selected_choice' -
Django ReactJS web app Icons and Images Inside Public Folder Not Showing
I'm trying to deploy a small Django/ReactJS web app to heroku. I'm having an issue with the static images used as background and icons (the images folder is inside the public folder). The images do not show. However, when I deploy only the frontend part as a static app, the images show correctly. All the Django/ReactJS project I've been able to access so far have images imported inside App.js, it's not what I want to do. I want to use the urls to the images as for example: background: "url(/images/somemage.png)" Website without backend: https://base-apparel-coming-soon-react.herokuapp.com/ Website with backend: https://base-apparel-coming-soon-dr.herokuapp.com/ Git repository: https://github.com/.../base-apparel-coming-soon-DRF.../ -
Reservation system Djangop [closed]
I am trying to develop a reservation system based on a Django project. My final goal is to have something like that: Until now, what I was able to achieve is to have the table with the times of the day and the column (which are aicrafts). My final goal is to have my reservations displayed as "legs", meaning that for example a reservation from 09:00 until 11:00 is displayed in the aircraft cells between 09:00 up to 11:00. So far my code is something like that: models.py class AirportTime(models.Model): aerodrome = models.ForeignKey(Aerodrome, on_delete=models.CASCADE, blank=True, null=True) opening_time = models.TimeField() closing_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.opening_time) + ' ' + str(self.closing_time) class Booking(models.Model): aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) student = models.ForeignKey( Student, on_delete=models.CASCADE, blank=True, null=True) instructor = models.ForeignKey( Instructor, on_delete=models.CASCADE, blank=True, null=True) date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.aircraft.registration + ' ' + str(self.date) + ' ' + str(self.start_time) + ' ' + str(self.end_time) views.py def index(request, date): if date is None: date_obj = datetime.now().date() else: date_obj = datetime.strptime(date, '%Y-%m-%d') next_day_obj = date_obj + timedelta(days=1) next_day_link = next_day_obj.strftime('%Y-%m-%d') prev_day_obj = date_obj - timedelta(days=1) … -
Passing secret variables Django to Javascript [closed]
Is there some way to not show variables in Django Template Ninja, or hidden them in Javascript for not show in Source Code? <div id="scriptBlock" style="display:none;"> <input type="hidden" id="username_api" value="{{ username }}"> <input type="hidden" id="password_api" value="{{DATA_API.password }}"> <input type="hidden" id="grant_type" value="{{DATA_API.grant_type }}"> <input type="hidden" id="scope" value="{{ DATA_API.scope }}"> <input type="hidden" id="client_id" value="{{ DATA_API.client_id }}"> <input type="hidden" id="client_secret" value="{{ DATA_API.client_secret }}"> <script> var username = document.getElementById('username_api').value.replace(/&quot;/g,"\"") var password = document.getElementById('password_api').value.replace(/&quot;/g,"\"") var grant_type = document.getElementById('grant_type').value.replace(/&quot;/g,"\"") var scope = document.getElementById('scope').value.replace(/&quot;/g,"\"") var client_id = document.getElementById('client_id').value.replace(/&quot;/g,"\"") var client_secret = document.getElementById('client_secret').value.replace(/&quot;/g,"\"") I tried to remove input hidden after get the variable, but they are showed in source code anyway. let scriptBlock = document.getElementById('scriptBlock') scriptBlock.parentElement.removeChild(document.getElementById('geonames_api')); scriptBlock.parentElement.removeChild(document.getElementById('google_maps')); scriptBlock.parentElement.removeChild(document.getElementById('username_api')); -
why does python3.6 container uses the /usr/lib of python 3.9
I start a docker contain with FROM python:3.6 It installs both python 3.6 and 3.9 as I noticed: All pips I installed are in 3.6 including mysqlclient But when it tries to import _mysql, it checks the /usr/lib of python3.9 which gives an error because it in 3.6 not 3.9. File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module ImportError: cannot import name '_mysql' from partially initialized module 'MySQLdb' (most likely due to a circular import) (/usr/local/lib/python3.6/site-packages/MySQLdb/__init__.py) Why doe this issue happen and how to prevent it? Here are the logs for the django application, I get the error: [Thu Mar 10 11:19:44.400586 2022] [wsgi:error] [pid 12660:tid 139881606039296] [client 172.23.0.1:43972] mod_wsgi (pid=12660): Exception occurred processing WSGI script '/var/www/html/project/project/wsgi.py'., referer: http://localhost:8005/request/outgoing/ [Thu Mar 10 11:19:44.423410 2022] [wsgi:error] [pid 12660:tid 139881606039296] [client 172.23.0.1:43972] Traceback (most recent call last):, referer: http://localhost:8005/request/outgoing/ [Thu Mar 10 11:19:44.423482 2022] [wsgi:error] [pid 12660:tid 139881606039296] [client 172.23.0.1:43972] File "/usr/local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 18, in <module>, referer: http://localhost:8005/request/outgoing/ [Thu Mar 10 11:19:44.423498 2022] [wsgi:error] [pid 12660:tid 139881606039296] [client 172.23.0.1:43972] from . import _mysql, referer: http://localhost:8005/request/outgoing/ [Thu Mar 10 11:19:44.423533 2022] [wsgi:error] [pid 12660:tid 139881606039296] [client 172.23.0.1:43972] ImportError: cannot import name '_mysql' from partially initialized module 'MySQLdb' (most likely due to a circular import) (/usr/local/lib/python3.6/site-packages/MySQLdb/__init__.py), … -
after upgrade python version 3.9 my virtualenv Import "django_filters.rest_framework" could not be resolved
After upgrading python version 3.8 to 3.9, I have an issue in my virtual environment Import "django_filters.rest_framework" could not be resolved. enter code here from django_filters.rest_framework import DjangoFilterBackend class Reviewlist(generics.ListAPIView): serializer_class = ReviewSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['review_user__username', 'active'] def get_queryset(self): pk = self.kwargs['pk'] return Review.objects.filter(watchlist=pk) -
Building a django app in Travis CI not successful
I am trying to integrate Travis CI with Django application. But I am getting the following error Successfully built 9b60427cea1c Successfully tagged 3_recipe_app_app:latest WARNING: Image for service app was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`. Creating 3_recipe_app_app_run ... System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK ./app/settings.py:23:80: E501 line too long (81 > 79 characters) ./app/settings.py:89:80: E501 line too long (91 > 79 characters) ./app/settings.py:92:80: E501 line too long (81 > 79 characters) ./app/settings.py:95:80: E501 line too long (82 > 79 characters) ./app/settings.py:98:80: E501 line too long (83 > 79 characters) ERROR: 1 The command "docker-compose run app sh -c "python manage.py test && flake8"" exited with 1. Done. Your build exited with 1. .travis.yml language: python python: - "3.6" services: - docker before_script: pip install docker-compose script: - docker-compose run app sh -c "python manage.py test && flake8" .flake8 [flake8] exclude = migrations __pycache__, manage.py, settings.py Dockerfile FROM python:3.7-alpine LABEL maintainer="hans" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user USER user docker-compose.yml version: "3" … -
Difference between import appname.models and from appname.models.ModelName in Djano
As a programming style, I find it more useful to write the following: import appname.models obj = appname.models.ModelName.objects.filter(status=1) However, I find lot of code written where only the ModelName is imported: from appname.models import ModelName obj = ModelName.objects.filter(status=1) However, I often come across the scenario, where the change in the ModelName result in the application breaking and we need to make changes everywhere. Also, from a readability perspective, the second approach, I find it very difficult know, where was the model defined(which app). I have been insisting my team to go with the first approach. Wanted to hear your thoughts which is the best approach from the following perspective: Readability Scalability Performance I really appreciate all your thoughts here. -
Django Rest Framework prefetching data
I would like to minimize number of queries to get data. I have 3 models: class SubCategory(models.Model): game = models.ForeignKey(Game, verbose_name=_("Gra"), on_delete=models.CASCADE) name = models.CharField(verbose_name=_("Nazwa"), max_length=40) ... class GameTask(CloneModel): game = models.ForeignKey(Game, verbose_name='Gra', related_name='tasks', on_delete=models.CASCADE) name = models.CharField(verbose_name='Nazwa', max_length=200) subcategory = models.ForeignKey(SubCategory, verbose_name=_("Podkategoria"), on_delete=models.SET_NULL, blank=True, null=True) class TaskLevel(CloneModel): name = models.CharField(max_length=50) master_task = models.ForeignKey(GameTask, related_name='sub_levels', on_delete=models.CASCADE) My subcategory view looks like: class SubCategoryList(ListAPIView, PermissionMixin): permission_classes = (permissions.IsAuthenticated,) serializer_class = SubCategorySerializer def get_queryset(self): return SubCategory.objects.filter(game=self.get_game()).order_by("slug") and my SubCategorySerializer: class SubCategorySerializer(serializers.ModelSerializer): developments = SubCategoryDevelopmentSerializer(many=True, read_only=True) in_progress = serializers.SerializerMethodField() class Meta: model = SubCategory fields = ("id", "name", "slug", "description", "image", "developments", "in_progress") def get_in_progress(self, obj: SubCategory): user = self.context["request"].user subcategory_tasks = obj.gametask_set.all() // rest of the logic All I want to achieve is to return only tasks, which are related to TaskLevel model as master_task. I was trying using subcategory_tasks = obj.gametask_set.all().prefetch_related("sub_levels") but the amount of queries was the same. Could somebody give my any hint how to solve this? -
Django How to know if an object exist and has a value that is equal to an object of same model
Here in my code, I have a models that collects data of users for a particular foreignkey object. Now I want it in a way that if an ip_address has visited a particular DetailPage, I create an instance. But now, if an IP address has already visited this particular detail page, I don't want it to create an instance anymore, instead it should update the instance. But now this is where the problem lies; if an IP address has visited a particular IP address (my first DetailPage) and now tries to visit my second DetailPage object, it does not create an instance because the IP address already exists. I want it to create an instance because the logistic foreignkey is a different foreignkey (my Second Detail Page) and not the first because this IP address was in the first. Here's my code below: models.py class UserVisitOfLogisticDetailPage(models.Model): logistic = models.ForeignKey(Logistic, null=True, on_delete=models.SET_NULL) user_ip_address = models.CharField(max_length=255, null=True, blank=True) user_latitude = models.CharField(max_length=255, null=True, blank=True) user_longitude = models.CharField(max_length=255, null=True, blank=True) user_city_location = models.CharField(max_length=255, null=True, blank=True) user_country_location = models.CharField(max_length=255, null=True, blank=True) user_device_type = models.CharField(max_length=255, null=True, blank=True) user_browser_type = models.CharField(max_length=255, null=True, blank=True) user_browser_version = models.CharField(max_length=255, null=True, blank=True) user_os_type = models.CharField(max_length=255, null=True, blank=True) user_os_version = models.CharField(max_length=255, null=True, … -
How can i display data from my REST API in a React JS Schedule
Everyone, On the coloured cells are data comming from my static JSON file and i want to change it, to data comming from a REST API, how can i do? So! I want to know how can I fetch data from my REST API to my schedule. I want to take the name and the date. The date will automatically be allocated to the correspondent schedule date and be displayed. Help please! -
Django Validate URLs in a List
I have an emtpy list called 'to_be_directed' that I save in direct.py file. I store all the previous links that user visited in that list up to 10 times. I save that list to redirect the user. However some links might be dead. Therefore, I like to check the links in the list with an order and redirect the user from latest proper link. However I see that requests library doing it multiple times. Although there are 1 link in the list, I see that it's going up to 10 times. How can I manage to redirect the users from latest active link in the list ? views.py from . import direct # here I save the visited links in to_be_directed list previous = self.request.META.get('HTTP_REFERER') direct.to_be_directed.insert(0, previous) if len(direct.to_be_directed) >= 10: direct.to_be_directed.pop() # here I check the links if they are dead; import requests for i in direct.to_be_directed: print('***************** i printed: ', i) try: print('************** status: ', requests.get(i).status_code) except: print('************ ERR') direct.py to_be_directed = [] outcome of prints [10/Mar/2022 14:29:55] "GET /actions/acbadem-admin-15f0ed1d/ HTTP/1.1" 200 68324 ************** status: 200 ***************** i printed: None ************ ERR ***************** i printed: None ************ ERR ***************** i printed: None ************ ERR ***************** i printed: None … -
Django-App s3 bucket not working properly
So I'm currently deploying my website on heroku and I want to serve the static and media files from AWS S3, and at this point the files are being served from aws but the styling is not being applied. This are my settings: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl' : 'max-age=86400'} AWS_DEFAULT_ACL = 'public-read' AWS_S3_REGION_NAME = 'eu-west-3' # AWS_S3_SIGNATURE_VERSION = 's3v4's3 AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' DEFAULT_FILE_STORAGE = "joaoLina.storages.MediaStorage" MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/media/' I have the right permissions on my bucket and as you can se the files are being served from aws: So if someone knows what I'm missing I would be glad to know.