Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error connecting dockerized Django with MySQL on Mac OS
I am using Dockerized Djano to connect with MySql but getting the following error: File "/usr/local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 17, in <module> raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Have tried every single possible solution on stackoverflow and google, but nothing seems to work. I suspect the MySQL driver within the docker container needs to be updated/configured correctly. Does anyone have any suggestions on what are the exact steps to undertake to fix it? THANKS! ENVIRONMENT MacOS 10.15.7. requirements.txt: Django==3.1.3 djangorestframework==3.12.2 mysqlclient==2.0.1 django-mysql==3.9 django-cors-headers==3.5.0 pika==1.1.0 Dockerfile: FROM python:3.9 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python manage.py runserver 0.0.0.0:8000 docker-compose.yml: version: '3.8' services: backend: build: context: . dockerfile: Dockerfile ports: - 8000:8000 volumes: - .:/app depends_on: - db db: image: mysql:5.7.22 restart: always environment: MYSQL_DATABASE: !@#$% MYSQL_USER: root MYSQL_PASSWORD: ****** MYSQL_ROOT_PASSWORD: ****** volumes: - .dbdata:/var/lib/mysql ports: - 33066:3306 -
My Django update form is not saving and it is also not showing the instance as a patient from the details the patient uses when they sign up
My django project does not recognize the instance of the patient details when I go to that page and it is also not saving the new patient details that I enter, instead I'm brought back to the same page with the new details I have entered. When I press the submit button again the same thing happens (same page with the new details) Models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.utils import timezone class User(AbstractUser): is_patient = models.BooleanField(default=False) is_doctor = models.BooleanField(default=False) class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) insurance = models.CharField(max_length=200) insuranceID = models.CharField(max_length=200) address = models.CharField(max_length=200) date_of_birth = models.DateField(default=timezone.now) gender = models.CharField(max_length=200) phone = models.CharField(max_length=200) current_medication = models.TextField(null=True, blank=True) preexisting_medication = models.TextField(null=True, blank=True) next_of_kin = models.TextField(null=True, blank=True) def __str__(self): return self.user.username class Doctor(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) name = models.CharField(max_length=200) date_of_birth = models.DateField(default=timezone.now) gender = models.CharField(max_length=200) phone = models.CharField(max_length=200) address = models.CharField(max_length=200) speciality = models.CharField(max_length=200) npi= models.CharField(max_length=200) education = models.TextField() qualifications = models.TextField() places_worked = models.TextField() consultation_fee = models.CharField(max_length=200) venue_of_operation = models.CharField(max_length=200) def __str__(self): return self.user.username FORMS.PY from django import forms from django.contrib.auth.forms import UserCreationForm from django.db import transaction from .models import Patient,Doctor, User GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), … -
Back button still works after logout in Safari with Django website
I am building a website with Django that handles sensitive data. My website has a logout button that logs the user out and redirects the browser to the login page. When using Safari version 14.1.1, I am able to click the back button in the browser after being logged out and I am returned to the previous page which contains private data. From my understanding, this doesn't seem to be a Django issue, rather Safari is storing content so it does not have to make another request to the server. I have tried a couple of methods to stop caching including: @cache_control(no_cache=True, must_revalidate=True, no_store=True) def some_method(request): #do some stuff and: @never_cache def some_method(request): #do some stuff and finally I tried manually changing the request headers with: response["Cache-Control"] = "no-cache, no-store, must-revalidate" response["Pragma"] = "no-cache" response["Expires"] = "0" Also, my views are annotated with @login_required(redirect_field_name="/somelink"). Some of my research suggested that this may not be a cache issue but rather a browser history issue but I'm not sure. It is also worth nothing that Chrome has given me no issues and when I click back button after logout it does not show what the previous user was viewing. Any ideas how … -
elided_page_range paginator not functioning as expected
I implemented a paginator based on this blog post with a goal of having a paginator that looks something like this so I don't have a ton of pages being display view def home(request): page = request.GET.get('page', 1) paginator = Paginator(Post.objects.all(), 1) page_obj = paginator.get_page(page) page_range = paginator.get_elided_page_range(number=page) context = {'page_range': page_range, 'page': page, 'paginator': paginator, 'page_obj': page_obj} return render(request, 'blog/home.html', context) template <main role="main" class="container"> <div class="row"> {% for post in page_obj %} <a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.year }}</a> <a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a> {% endfor %} </div> <ul class="pagination justify-content-center flex-wrap mt-2 mb-4"> {% if page_obj.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled page-item"><span class="page-link">&laquo;</span></li> {% endif %} {% for i in page_range|default_if_none:page_obj.paginator.get_elided_page_range %} {% if page_obj.number == i %} <li class="active page-item"><span class="page-link">{{ i }} <span class="sr-only">(current)</span></span> </li> {% else %} {% if i == page_obj.paginator.ELLIPSIS %} <li class="page-item"><span class="page-link">{{ i }}</span></li> {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled page-item"><span class="page-link">&raquo;</span></li> {% endif %} </ul> </main> The … -
502 Error Docker container running in the background
I have a container running Django app with PyTorch model(s) The issue is when starting the app/container it takes time to load and download the models Running the container in the background results in a 502 error, how can I avoid this should I make a function waiting for the models to be ready first just like the one I have that waits for the DB to be ready ? how can I check the readiness of the models? -
is there a way to get the import directly by typing name of module of python in vscode
lets say i have Django in a virtual environment and activated it and now i want to use the built-in user model "User", so every time i have to look for, then type: from django.contrib.auth.models import User the same thing for every import needed is there a way to quick-fix that , instead of looking for where this module or this other or ... comes from in the docs every time, is there a way that it suggests or gives the import path?? -
what is the difference between this two django imports
I am new to django and I am a little bit confused what is the difference between: from django.views.generic.detail import DetailView and from django.views.generic import DetailView I've tried to read up on it in the documentation but I wasn't able to find the answer. -
django - view that creates or updates a model but requires a submit
I have class based modelview where I want the model/instance to be created or updated. If updating, I want the fields to show their current values. I have this working except that the instance is being created just by loading the view/template. As soon as the page loads, the object is saved. I think it's very important that the save is not done until the submit button is clicked. I also want to override the model's save() method because I need to check what field is being updated and update a different model/object. Model class GradeBookSetup(DirtyFieldsMixin, models.Model): user = models.OneToOneField(CustomUser, on_delete=CASCADE) level1 = models.IntegerField(default=55) scale_mode = models.CharField(max_length=7, blank=True, default="VSB") teacher_show_sec_percent = models.BooleanField(default=True) def save(self, *args, **kwargs): super(GradeBookSetup, self).save(*args, **kwargs) if 'scale_mode' in dirty_fields: objs = Grade.objects.filter(user=self.user) n = 0 for grade in objs: objs[n].score = "BEG" View @method_decorator([login_required], name='dispatch') class GradeBookSetupCreateView(UpdateView): form_class = GradeBookSetupForm model = GradeBookSetup success_url = "/gradebook/" def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def get_object(self, queryset=None): obj, created = GradeBookSetup.objects.get_or_create( user=self.request.user) return obj Form class GradeBookSetupForm(forms.ModelForm): class Meta: model = GradeBookSetup fields = ['level1', 'scale_mode', 'teacher_show_sec_percent'] labels = { "level1": "What percent?", "scale_mode": "Choose your proficiency scale.", 'teacher_show_sec_percent': "Teacher view (10-12), show percent", } -
data related to primary key is not displayed
I have a model that contains some judgments along with their title. Now i want to display the judgement when the related title is clicked. i have written the following code: models.py class Laws(models.Model): date= models.DateField(default=timezone.now) title= models.CharField(max_length=225, help_text="judgement title") judgements= RichTextField(blank=True, null= True) law_type= models.CharField(max_length=40, choices= type_of_law) law_category= models.CharField(max_length=60, choices= category) views.py class DocView(ListView): model= Laws template_name = 'doc.html' class Doc1DetailView(DetailView): model= Laws template_name = 'doc1.html' urls.py urlpatterns=[ path('doc', DocView.as_view(), name='doc' ), path('doc1/<int:pk>', Doc1DetailView.as_view(), name='doc1' ), ] and the html files are doc.html {% for data in object_list %} <div class="tab"> <a href="{% url 'doc1' data.pk %}">{{data.title}}</a><br/> </div> {% endfor %} doc1.html <p style="color: black;">{{data.title}}</p> I refered to a video in youtube and wrote this code his was working and mine not. i have chamged nothing from that code still the data doesn't show up in doc1.html. please rectify my code and tell me what i am doing wrong here. -
how can i want change config server with putty for django project?
I want change config server with putty for Django project I want change this configs: firewall Nginx Supervisord database Psql and ... -
How to check if a range from Min to Max overlaps with the list of existing ranges in python
Suppose I have a list of ranges E.G ==Min== ==Max== 10 100 101 200 201 500 rules = [(10,100),(101,200),(201,500)] I want to check if the new range is overlapping with the existing ranges. Example if I add any of the below entries all of them showed be invalid because the new entries are overlapping with the existing lists: 50 800 Invalid 50 80 Invalid 150 199 Invalid 200 300 Invalid and the below entries should be valid: 501 550 Valid 0 9 Valid -
How to get contact details to be filled on that page after deploying django webiste to heroku?
I have deployed one of my Django website to Heroku. But now I do not understand that I have been given a contact form on that website, so how will I get that data? I am getting all that data on my local server but I have no idea about online can anyone help me with this? -
Show more data button in a list of posts django
I'm practicing with Django making a web with data about LoL with the Riot API. There is a page where you can see the game history of a searched player. I'm trying to create a button that shows the in-depth data of a game on the same page without reloading because if I try to load the data for each game at first, it takes a long time to load the page. I haven't done much about the front-end yet, so it currently looks this: And the relevant part of the views.py looks like this: def user_info(request, server, summoner_name, template='riot/user-profile.html'): account_id = user_account_info['accountId'] games_list = api_interaction.get_past_games(server, account_id) champ_json = services.load_champ_json_session(request) game_summary_list = services.get_game_summary_list(games_list, champ_json) context = { 'game_summary_list': game_summary_list, 'user_account_info': user_account_info, 'summoner_stats': summoner_stats } if ('load') in request.POST: gameId = (request.POST['load']) game_data = api_interaction.game_summary(server, gameId, champ_json) context['game_data'] = game_data return render(request, template, context) else: return render(request, template, context) Basically what I have right now is that the button submits a form and in views.py, if a form is submitted, it will process some data and return an extra python dictionary. Then in my template I have a div that looks like this: <div id="load_more"> {% if game_data.success %} {% if … -
How to debug this stracktrace in django?
I have a form inside a modal, when I click save I get the following error. The issue is that I dont know where to find it because it's not showing that the error is in my code. Environment: Request Method: POST Request URL: http://localhost:8000/user/add/ Django Version: 3.1.3 Python Version: 3.9.0 Installed Applications: ['app.apps.AppConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar'] 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', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback (most recent call last): File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /user/add/ Exception Value: __init__() takes 1 positional argument but 2 were given -
how to render key value pairs of this dictionary in template
views.py from django.shortcuts import render, redirect import wikipedia from wikipedia.exceptions import DisambiguationError, PageError def index(request): context = {} if request.GET.get('search'): search_value = wikipedia.search(request.GET.get('search'), results=3) print(search_value) keys = search_value values = [] for s in search_value: print(s) try: if wikipedia.summary(s): values.append(wikipedia.summary(s)) except DisambiguationError as error: print('errorrrrrr \n', error) values.append("Disambiguation error") except PageError as error: print('erorrrrrrr \n', error) values.append("Page error") for i in range(len(keys)): context[keys[i]] = values[i] context = dict(zip(keys, values)) res = not bool(context) print(res) for key, value in context.items(): print('key', key) print('value', value) return render(request, 'webapp/index.html', context) How to render these key value pairs in the template, is it related to this https://code.djangoproject.com/ticket/16335 if so can someone suggest a solution index.html <div class="results"> {% for key, value in context.items %} <h3>something</h3> {{key}} {{value}} {% endfor %} </div> the above for loop doesn't put anything in the template -
Django / DRF - Get field of a related model
everyone. What I want is get field of a related model by serializer. I have 2 models: class Question(models.Model): question_text = models.CharField(max_length=200) def __str__(self): return self.question_text class Test(models.Model): test_name = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') question = models.ManyToManyField(Question, related_name='tests') def __str__(self): return self.test_name Why I've used ManyToManyField? Because I've followed here: https://medium.com/django-rest/lets-build-a-basic-product-review-backend-with-drf-part-1-652dd9b95485 Now I can do smth like: But I want get question_text in response. What I tried: class TestSerializer(serializers.HyperlinkedModelSerializer): question_text = serializers.CharField(read_only=True, source="question.question_text") class Meta: model = Test fields = ['pk', 'test_name', 'pub_date', 'question_text'] expandable_fields = { 'question': (QuestionSerializer, {'many': True}) } But it returned: I understand, that problem might be in DB relations, but I can't get it. Thanks in advance! -
Cannot assign "'4'": "Element.value_code" must be a "Value" instance
I'm trying to save element.value_code, but this error occurs. If I get the value_code on the getlist, my mission will be over. How should I correct this error? I'd really appreciate it if you could let me know. Error: Cannot assign "'4'": "Element.value_code" must be a "Value" instance. models.py There were only models related to Value and Element, but we added all models to help you understand why option_code and designated_code exist. class Option(models.Model): option_code = models.AutoField(primary_key=True) name = models.CharField(max_length=32) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') def __str__(self): return self.name class Meta: ordering = ['option_code'] class Value(models.Model): value_code = models.AutoField(primary_key=True) option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') name = models.CharField(max_length=32) extra_cost = models.IntegerField() def __str__(self): return self.name class Meta: ordering = ['value_code'] class Designated(models.Model): designated_code = models.AutoField(primary_key=True) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') price = models.IntegerField() rep_price = models.BooleanField(default=True) class Meta: ordering = ['designated_code'] def __str__(self): return str(self.designated_code) class Element(models.Model): element_code = models.AutoField(primary_key=True) designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, db_column='designated_code') value_code = models.ForeignKey(Value, on_delete=models.CASCADE, db_column='value_code', null=True, blank=True) class Meta: ordering = ['element_code'] def __str__(self): return str(self.element_code) views.py if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): for value_code2 in request.POST.getlist('value_code2'): element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = value_code2 element.save() else: … -
Update django database automatically with schedule
I am working on a Django project to track my daily tasks. I hope my database can automatically create a new record as "unfinished" at midnight each day. How can I implement this feature in Django + React? -
How to render template without extending?
I want to make a template in which i don't want base.html content but when i don't extend base.html template my code doesn't work. So is there any way by which i can make a template without extending base.html file ? -
Count consecutive days of user visit
I am building a BlogApp and I am trying to count user's visited days. Like stackoverflow does. User have visited two consecutive days. When user login in last 24 hours in a day then count that days, AND if user missed a day then days will add from starting. I also tried by adding a decorator :- def W_update_user_login(func): @wraps(func) def wrapper(*args, **kwargs): request = args[0] if request.user.is_authenticated: user=User.objects.get(username=request.user) user.last_login=timezone.now() user.save() return wrapper BUT it shows The view app.views.home didn't return an HttpResponse object. It returned None instead. Then i thought about make a IntegerField in Profile which will count last login which has happened in last 24 hours BUT then i figured that it will count in every time user log in. @receiver(user_logged_in) def sig_user_logged_in(sender,user,request,**kwargs): user.profile.last_login = datetime.now() user.profile.save() I have no idea how can i do it. Any help would be much Appreciated. Thank You in Advance. -
How to change values of select box by another value?
I have three models. class Country(models.Model): title = models.CharField(max_length = 100, null = True) def __str__(self): return self.title class Province(models.Model): title = models.CharField(max_length = 100,null = True) country= models.ForeignKey(Country ,on_delete=models.SET_NULL, null = True,blank=True) def __str__(self): return self.title class Flower(models.Model): name = models.CharField(max_length = 200) country = models.ManyToManyField(Country, null = True,blank=True) provinces = models.ManyToManyField(Province, null = True,blank=True) I have the below admin when i add Flower: I want to show provinces/states of Germany in Provinces when Germany is selected in the Country field. How can i do it? -
django one to many polymorphic (comment model)
how to create a comment model that can be used on two models at once. in this case I want to create a post and video model but only with one comment model. -
how can I filter that elements?
I am a beginner at Django. How can I filter that element in Django? Here is my views.py for teacherhome & commentpost enter image description here enter image description here Here is my models.py for UserComment enter image description here -
django.db.utils.OperationalError: (1292, "Truncated incorrect INTEGER value: 'incompleted'") django
i tried to change a field type from CharField to BooleanField , change this completed = _('completed ') incompleted = _('incompleted ') payment_status = ( (completed,completed), (incompleted,incompleted), ) payment_status = models.CharField(max_length=25,choices=payment_status,default=incompleted) to payment_status = models.BooleanField(default=False) python manage.py makemigrations created the changed in migrations folders but when i tried to migrate it raises this error: django.db.utils.OperationalError: (1292, "Truncated incorrect INTEGER value: 'incompleted'") django django version : 3.2 , db : mysql i also tried remove that field but still raise the same error? i dont want to lose my data into my databse -
Deleted all my migrations including __init.py__
I am a beginner using Django. I have recently been working on a website that has a few different pages. I reference a couple of views from other apps in urls.py. One app I used to take inputs and make some calculations, so it had some forms defined. It was all working fine and I was able to import the views fine, but I changed one of my form field names. This caused some problems because I was storing these values in a database. That made sense to me because I had already saved some data with the previous naming convention and now I had changed it. So, I figured that deleting my database and migrations would allow me to start over and start a new database with my updated fields. I messed up though because I read that I should not have deleted my init.py file in my migrations folder. I have tried re-doing my migrations with makemigrations and migrate but I keep getting an error saying that no changes are made and no new migrations show up in my folder. Also, now when I look in my urls.py file, the imported views and apps are showing up with …