Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax URL Not Executing The Correct Function in views.py As Defined in urls.py
I am leveraging Ajax for some pie charts but data-ajax-url is not working as intended (or as I thought). Per urls.py, reptibase:item-update should execute the item_update function in my views.py file. item_update never gets executed though and instead the same function associated with the current pages url is executed again. Currently, am getting a parsing error because HTML is coming back instead of json. json is returned from my item_update function though. item.js window.onload = function () { console.log("Child: ", document.getElementById("piee")) var ctx = document.getElementById("piee").getContext('2d'); var rep_name = $("#pie1").attr("data-rep-name") var ajax_url = $("#pie1").attr('data-ajax-url') var _data = [] var _labels = [] // Using the core $.ajax() method $.ajax({ // The URL for the request url: ajax_url, // The data to send (will be converted to a query string) data: { name: rep_name }, // Whether this is a POST or GET request type: "POST", // The type of data we expect back dataType: "json", headers: {'X-CSRFToken': csrftoken}, context: this }) // Code to run if the request succeeds (is done); // The response is passed to the function .done(function (json) { if (json.success == 'success') { var newMale = json.malePerc var newFemale = json.femalePerc console.log(newMale, newFemale) _labels.push("male", "female") _data.push(parseFloat(newMale), parseFloat(newFemale)) … -
how do I save an image in Django using Cropper.js?
I have a little problem again. I have pictures in my database and it must be possible to crop them at will. I'm trying Cropper.js, but I can't save the image afterwards. What am I doing wrong? I am grateful for all ideas! # index.html {% extends 'base.html' %} {% block content %} <section class="py-5 text-center container"> <div class="row py-lg-5"> <div class="col-lg-6 col-md-8 mx-auto"> <!--<h1 class="fw-light">Album example</h1>--> <form class="bg-light p-4 rounded" method="post"> {% csrf_token %} {{ form }} <button class="btn btn-primary my-2" type="submit"> Получить данные </button> </form> </div> </div> </section> {% for apartment in apartments_list %} <div class="album py-5 bg-light"> <div class="container"> <div class="row row-cols-1 row-cols-sm-6 row-cols-md-2 g-3"> {% for img in apartment.images.all %} <div class="col"> <div class="pop card shadow-sm"> <img src="{{ img.img.url }}" width="100%" height="450" alt="" /> </div> <br /> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <a class="pop btn btn-sm btn-outline-secondary" href="{#% url 'apartments:update-image' img.pk %#}"> Редактировать </a> <a type="button" class="btn btn-sm btn-outline-secondary" href="{% url 'apartments:delete-image' img.pk %}"> Удалить </a> </div> </div> <br /> </div> {% endfor %} </div> <h5 class="card-title">{{ apartment.address }}</h5> <h5 class="card-title">{{ apartment.rooms }}</h5> <h5 class="card-title">{{ apartment.floor }}</h5> <h5 class="card-title">{{ apartment.price }}</h5> <p class="card-text">{{ apartment.desc }}</p> <div class="btn-group"> <a type="button" class="btn btn-sm btn-outline-secondary" href="{% url 'apartments:update' … -
The block in my template gets rendered with an incorrect indentation
I have this problem where my block are correctly indented in the template, but when it gets rendered the indentation fails and all the text of my post get out of place. To clarify I'm using django to create a blog. It's just a personal project, I just stated learning like 4 months ago. Actual Blog This is the source code I get: Source Code As you can see all the code should be to the right side of the red line. I don't know what is happening. I have been trying everything for the last 4 hours and nothing. The thing is, this is my firth project so I made a lot of mistakes. When this problem appeared for the first time I didn't pay much attention to it, I thought it was just a html code problem and easy to solve. Now I'm lost. This is a part of the code of my Base template, where the block is: <!-- Main Content--> <div class="container px-4 px-lg-5"> <div class="row gx-4 gx-lg-5 justify-content-center"> <div class="col-md-10 col-lg-8 col-xl-7"> <!-- Post preview--> <div class="post-preview"> {% block content %} {% endblock %} </div> </div> </div> </div> This is the code of my home: … -
How can I add an extra field in the response to understand which item triggered the search result
I have a simple recipe and ingredient models. class Ingredient(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) class Recipe(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) ingredients = models.ManyToManyField(Ingredient, related_name='product_ingredients') I have added a filter for recipe search when I can add ingredient ids as parameter. It returns the recipes which have those ingredients. The filter is as follows, class RecipeFilter(django_filters.FilterSet): ingredient_have = django_filters.CharFilter(method='filter_ingredient_have') def filter_ingredient_have(self, queryset, name, value): if value: ids = value.split(',') return queryset.filter(Q(ingredients__id__in=ids)) return queryset class Meta: model = Recipe fields = [] The url is something like this /recipes/?ingredient_have=id1,id2 The response is something like { "items": [ { "id": "13261f0d-408d-4a51-9cc2-cb69ee72fe24", "name": "Curry", "ingredients": [ { "id": "08089ff8-03fb-4946-be61-659d799ca996", "name": "oil" }, { "id": "dc9cb6f2-1810-48eb-b7a7-52a4bd9fdccb", "name": "water" } ] } ] } I would like to add an extra field (in Ingredient) so that I can understand in the frontend which ingredient has triggered the product to be in the search result such as, { "id": "08089ff8-03fb-4946-be61-659d799ca996", "name": "oil", "highlight": false/true } I hope I made the problem clear. Could you please give me some suggestion/solution? Thanks in advance. -
If the value recieved in a Decimal Form is an empty string how can I convert it to a float number?
On my page I ask for various things to the user in the form as it's a calculator that does various things, now you see, the thing is if the user does not have the value for bf I want to give the option to calculate with different values, that is why I required is False, so first what I want to archive is that if the form is empty I want to be passed as a 0 or False, how can I archive this? I have the following form: class CMForm(forms.Form): age = forms.DecimalField(max_digits=2, decimal_places=0, min_value=15, max_value=80) sex = forms.ChoiceField(choices=sex) pregnant = forms.BooleanField(initial=False, required=False) lactating = forms.BooleanField(initial=False, required=False) weight = forms.DecimalField(max_digits=4, decimal_places=1, max_value=635) height = forms.DecimalField(max_digits=4, decimal_places=1, max_value=272) bf = forms.DecimalField(label='Body Fat(not required)', help_text='%', required=False, decimal_places=1, min_value=1, max_value=80) activeness = forms.ChoiceField(choices=activity_level) units = forms.ChoiceField(choices=units) this view: def cmr(request): a = float(request.GET['age']) bf = float(request.GET.get('bf', 0)) s = str(request.GET['sex']) g = 0 if s == 'female': g = 1 w = float(request.GET['weight']) h = float(request.GET['height']) act = str(request.GET['activeness']) u = str(request.GET['units']) p = str(request.GET.get('pregnant', 0)) lac = str(request.GET.get('lactating', 0)) dci = 0 bmrm = 10*w+6.25*h-5*a+5 bmrf = 10*w+6.25*h-5*a-161 bmi = round(w/(h/100)**2, 1) if bf is False: bf = round(-44.988 + … -
Error when requesting User.history.all ()
I have a model class User (AbstractUser), I would like to keep track of the User history, I have an error while getting User.history.all (), ERROR: table "core_user" is missing from the FROM clause LINE 1: SELECT "core_user". "Id", "core_user". "Password", "core_user" ... SELECT "core_user"."id", "core_user"."password", "core_user"."last_login", ' '"core_user"."is_superuser", "core_user"."username", ' '"core_user"."first_name", "core_user"."last_name", "core_user"."email", ' '"core_user"."is_staff", "core_user"."is_active", "core_user"."date_joined", ' '"core_user"."editor_config", "dib_page_historicaluser"."ip_address", ' '"dib_page_historicaluser"."history_id", ' '"dib_page_historicaluser"."history_date", ' '"dib_page_historicaluser"."history_change_reason", ' '"dib_page_historicaluser"."history_type", ' '"dib_page_historicaluser"."history_user_id" FROM "dib_page_historicaluser" ' 'ORDER BY "dib_page_historicaluser"."history_date" DESC, ' '"dib_page_historicaluser"."history_id" DESC LIMIT 21') core_user table it is my base_model, dib_page_historicaluser table it is history model, whoever knows can tell what the problem is, I'm a beginner -
Tried to create three apps in Django but when try to click on third app it routes to the second app page settings templates DIR allows routing 2 DIRs
in this below code i explained How i rooted the templated but only first two roots are working when click on my third app it automatically rooted to my second app #--assigning apps templates as values-- mail = os.path.join(BASE_DIR,'mail/templates') cloud = os.path.join(BASE_DIR,'cloud_storage/templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', #--rooting the values as dirs -- 'DIRS': [BASE_DIR/'Home/templates',cloud,mail,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
SQL0601N The name of the object to be created is identical to the existing name "DJANGO_MIGRATIONS" of type "TABLE"
I want the django to connect to db2 as another user (a DBADM) instead of db2inst1, the schema is XXX. but after running python manage.py migrate, it failed after creating tables DJANGO_MIGRATIONS and DJANGO_CONTENT_TYPE. They are both empty. The returned error is [IBM][CLI Driver][DB2/AIX64] SQL0601N The name of the object to be created is identical to the existing name "XXX.DJANGO_MIGRATIONS" of type "TABLE". SQLSTATE=42710. I tried to drop tables and run the command again but failed. It seems it cannot find the DJANGO_MIGRATIONS table when trying to insert a new record so it tries to create it again. The command however succeeds when using db2inst1. So I want to know if the issue is caused by insufficient user privileges? What privileges/roles the connection user should have? Are there any restrictions on the connection user? I tried to find document but couldn't find any. Versions: Django 3.2, ibm-db-django 1.5.0.0, ibm-db 3.1.0, DB2 10.5 -
Container command fails when deploying
I'm trying to deploy my Django project using Elastic Beanstalk. It's been fine until it tried to run container commands. Here's my .config file looks like: container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true 02_createsuperuser: # <- The error occurs here command: "echo \"from account.models import Account; Account.objects.create_superuser('Me', 'Me', 'myemail@gmail.com', 'superadmin', 'MyPassword')\" | python3 manage.py shell" And my cfn.init file logs this error: [ERROR] Command 02_createsuperuser (echo "from account.models import Account; Account.objects.create_superuser('Me', 'Me', 'myemail@gmail.com', 'superadmin', 'MyPassword')" | python3 manage.py shell) failed 2021-12-06 03:22:18,662 [ERROR] Error encountered during build of postbuild_0_package404: Command 02_createsuperuser failed Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 573, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 273, in build self._config.commands) File "/usr/lib/python3.7/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 02_createsuperuser failed 2021-12-06 03:22:18,665 [ERROR] -----------------------BUILD FAILED!------------------------ 2021-12-06 03:22:18,665 [ERROR] Unhandled exception during build: Command 02_createsuperuser failed Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 176, in <module> worklog.build(metadata, configSets) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 135, in build Contractor(metadata).build(configSets, self) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 561, in build self.run_config(config, worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 573, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 273, in build self._config.commands) File "/usr/lib/python3.7/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s … -
Insertion with 1 foreign key and 2 pk failed
class TbBoard(models.Model): board_seq = models.BigAutoField(primary_key=True) board_title = models.CharField(max_length=30) board_content = models.CharField(max_length=2000, blank=True, null=True) board_writer = models.CharField(max_length=40) board_password = models.CharField(max_length=200) create_date = models.DateTimeField(default=timezone.now) class Meta: managed = False db_table = 'tb_board' class TbComment(models.Model): board_seq = models.ForeignKey(TbBoard, models.DO_NOTHING, db_column='board_seq') comment_seq = models.IntegerField(primary_key=True) comment_depth = models.IntegerField() comment_content = models.CharField(max_length=2000) comment_writer = models.CharField(max_length=40) comment_password = models.CharField(max_length=200) create_date = models.DateTimeField(default=timezone.now) class Meta: managed = False db_table = 'tb_comment' unique_together = ('board_seq', 'comment_seq', 'comment_depth',) The part to save is as follows. tb_comment = models.TbComment( board_seq = models.TbComment.objects.get(board_seq=board_seq), comment_seq = comment_seq, comment_depth = comment_depth, comment_content = comment_content, comment_writer = comment_writer, comment_password = comment_password, ) board_seq=1, comment_seq=0, comment_depth=0 In the state that is inserted in this db board_seq=2, comment_seq=0, comment_depth=0 I'm trying to insert board_seq=1 -> 2, comment_seq=0, comment_depth=0 will be overwritten by how can i solve it?? force_insert=true? When you try, the already existing key(0, 0) is output like this. -
Django: 'WSGIRequest' object has no attribute error
I've two models in my app: the Dataset model is created when the File model is saved, but I'm having problem linking the file_uploaded field in the dataset to the File model using foreign key. To do so I'm using this: file_uploaded = request.file_uploaded.file, and I'm getting this error: 'WSGIRequest' object has no attribute 'file_uploaded' I'm not getting what I'm doing wrong considering that I can link the user without problems. I had to change a little bit of my code to make it shorter, there may be some inconsistenciesbut, but the original one works (excepts for the error I'm getting). Thank you all for the help MODEL class File(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) filename = models.CharField(max_length=250) file_upload = models.FileField(upload_to=path) upload_date = models.DateField(default=datetime.now) def __str__(self): return self.user.name + 'file' class Dataset(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) file_uploaded = models.OneToOneField(File, on_delete=models.CASCADE) name_user_A = models.CharField(max_length=250) code_user_A = models.PositiveIntegerField(null=True) total_user_A = models.PositiveIntegerField(null=True) sd_user_A = models.PositiveIntegerField(null=True) name_user_B = models.CharField(max_length=250) code_user_B = models.PositiveIntegerField(null=True) total_user_B = models.PositiveIntegerField(null=True) sd_user_B = models.PositiveIntegerField(null=True) With File model it should be uploaded a csv file and then the information in the file should be saved in the Dataset model. After that I'd like to show some chart to my user so I … -
Custom inputs of django-filter in templeta
I want to improve the rendering of the inputs in the template. I have tried adding styles from widgets in the class: class ProductosFilter(django_filters.FilterSet): class Meta: model = Elemento fields = ('estado','tipo','grupo') widgets = { 'grupo':widgets.Select(attrs={ 'class': 'form-control form-select ', }), } but I did not make it. this is my template: <div class="col-md-12" style="text-align: right; padding-top: 50px; padding-right: 50px;" > {{filter.form}} <button type="submit" class="btn btn-primary">Filtrar</button> </div> any contribution is appreciated -
If the value recieved in a Decimal Form is an empty string how can I convert it to a float number?
On my page I ask for various things to the user in the form as it's a calculator that does various things, now you see, the thing is if the user does not have the value for bf I want to give the option to calculate with different values, that is why I required is False, so first what I want to archive is that if the form is empty I want to be passed as a 0 or False, how can I archive this? I have the following form: class CMForm(forms.Form): bf = forms.DecimalField(label='Body Fat(not required)', help_text='%', required=False, decimal_places=1, min_value=1, max_value=80) this view: def cmr(request): a = float(request.GET['age']) bf = float(request.GET.get('bf')) s = str(request.GET['sex']) g = 0 if s == 'female': g = 1 w = float(request.GET['weight']) h = float(request.GET['height']) act = str(request.GET['activeness']) bf = float(request.GET.get('bf')) bmi = round(w/(h/100)**2, 1) if bf is False: bf = round(-44.988 + (0.503 * a) + (10.689 * g) + (3.172 * bmi) - (0.026 * bmi**2) + (0.181 * bmi * g) - (0.02 * bmi * a) - (0.005 * bmi**2 * g) + (0.00021 * bmi**2 * a), 1) tbf = w*(bf/100) ffm = w*(1-(bf/100)) ffmi = ffm/(h/100)**2 nffmi = … -
Cannot unpack non-iterable object Django
So, I'm trying to filter a field's choices by the created_by attribute, which is an User instance gotten from the request when it was created. After doing some research I found some explanations and followed them but I couldn't get the choices to actually appear at the form. Now I'm getting the error that Categoria Object isn't Iterable. The error Django shows me at the browser: Exception Type: TypeError Exception Value: cannot unpack non-iterable Categoria object the Class I used as a model to the Form: class Contato(models.Model): nome = models.CharField(max_length=255) sobrenome = models.CharField(max_length=255, blank=True) telefone = models.CharField(max_length=255) email = models.CharField(max_length=255, blank=True) data_criacao = models.DateTimeField( default=timezone.now) descricao = models.TextField(blank=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) categoria = models.ForeignKey( Categoria, on_delete=models.DO_NOTHING) mostrar = models.BooleanField(default=True) foto = models.ImageField(blank=True, upload_to='fotos/%y/%m/%d') def __str__(self): return self.nome this is the code from the Form I'm trying to modify class ContatoForm(forms.ModelForm): class Meta: model = Contato exclude = ('created_by',) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(ContatoForm, self).__init__(*args, **kwargs) category_choices = list(Categoria.objects.filter( created_by=self.user)) self.fields['categoria'] = forms.ChoiceField(choices=category_choices) And this is the view I'm using this form at @login_required(redirect_field_name='login') def dashboard(request): if request.method != 'POST': form_contato = ContatoForm(user=request.user) form_categoria = CategoriaForm return render(request, 'accounts/dashboard.html', {'form_contato': form_contato, 'form_categoria': form_categoria}) -
Need help in django
I have 4 model classes (Course, Semester, Subject, TuModelQuestions) as you can see below. When I try to render particular question from TuModelQuestions from Partcular Subject From Particular Semester And particuar Course. How do i render it? Please give me some logic and code if you can. (Overall: I want to render that question only for particular subject, course and semester) models.py from django.db import models from django.db.models.base import ModelState # Create your models here. class Course(models.Model): faculty = models.CharField(max_length=100) class Semester(models.Model): sem = models.CharField(max_length=100) faculty = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return F"Semester {self.sem} at Faculty {self.faculty}" class Subject(models.Model): faculty = models.ForeignKey(Course, on_delete=models.CASCADE) sem = models.ForeignKey(Semester, on_delete=models.CASCADE) subject_name = models.CharField(max_length=100) class TuModelQuestions(models.Model): date = models.IntegerField() model_question = models.ImageField(upload_to='imgs/') subject = models.ForeignKey(Subject, on_delete=models.CASCADE) views.py from django.shortcuts import render from django.views import View from django.contrib import messages from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField from django import forms from django.utils.translation import gettext, gettext_lazy as _ from .forms import CustomerRegistrationForm from .models import Course, Semester, Subject, TuModelQuestions # Create your views here. def home(request): return render(request, 'app/home.html') def faculty(request): course = Course.objects.all() return render(request, 'app/faculty.html', {'course':course}) class SemesterView(View): def get(self, request,id): obj = Course.objects.get(id=id) print(obj) semobj = Semester.objects.filter(faculty=obj) print(semobj) subobj = Subject.objects.filter(faculty=obj) print(subobj) return … -
Django - "psycopg2.errors.ForeignKeyViolation: insert or update on table" when running "python manage.py test", but not when running single test
So I made another post regarding this issue and thought I'd break it down even more to see if the good people of StackOverflow can figure out what's going on, because I can't. So I generate all this test data below using setUpTestData and things look good. I put the debugger log below to show that the test database is populated with what is expected. When I get to the test test_correct_num_posts_generated the test itself passes, but I get this weird database error. I put the full error output below. I've gotten this over many tests. I heard it could be related to a Django bug where the test DB doesn't get properly torn down. This is a weird issue, because when I run python manage.py test cheers.test.ExploreTest it passes and python manage.py test cheers.test.ExploreTest.test_correct_num_posts_generated it passes, but when I run python manage.py test I get the error shown below. What is going on? Test.py @classmethod def setUpTestData(cls) -> None: cls.num_posts = 45 cls.health_cate = 'Health' cls.fitness_cate = 'Fitness' cls.relationship_cate = 'Relationship' cls.goal_categories_name_list = [cls.health_cate, cls.fitness_cate, cls.relationship_cate] cls.user = create_test_user_in_DB() cls.access_token = get_test_user_access_token() for name in cls.goal_categories_name_list: goal_category_obj = GoalCategory.objects.create(name=name, emoji='Some URL') goal_obj = Goal.objects.create(creator=cls.user, goal_category=goal_category_obj) if name == cls.relationship_cate: … -
Sending email from DebuggingServer localhost:1025 not working
Im testing sending an email after filling out a form on a website and im using my local host. Upon submitting the form I'm using the django send_mail() method and Im sending the test email to a gmail account and I have the account as a list data type. $ python -m smtpd -n -c DebuggingServer localhost:1025 And I'm getting this depreciated message after I turn on the server and I also have yet to receive an email from my local host C:\Users...\AppData\Local\Programs\Python\Python310\lib\smtpd.py:104: DeprecationWarning: The asyncore module is deprecated. The recommended replacement is asyncio import asyncore C:\Users...\AppData\Local\Programs\Python\Python310\lib\smtpd.py:105: DeprecationWarning: The asynchat module is deprecated. The recommended replacement is asyncio import asynchat Here's whats in my settings.py file: EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False Any ideas why its not sending? -
Django ModuleNotFoundError: No module named "\n 'hello"
I am following Django dj4e course. While going through setup that is linked here https://www.dj4e.com/assn/dj4e_ads1.md?PHPSESSID=991c1f9d88a073cca89c1eeda44f61d2 I got this weird error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/apps/config.py", line 212, in create mod = import_module(mod_path) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import ... bunch of similar bootstrap lines ... ModuleNotFoundError: No module named "\n 'hello" I got this error when I did everything in the tutorial's setup and then copied the settings because they were missing something. I went through all those steps again and this weird error keeps popping up during python3 manage.py check. Here are my settings: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Used for a default title APP_NAME = 'ChucksList' # Add # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! … -
Dockerize Django application with mongoDB
I am working on Django web application which store the data in mongoDB database. When I run the docker using the docker-compose.yml file, it open the login page and gives the CSFR token error. Following are the logs of Django container: pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 61ad29e66ee4fa015775e4b9, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]> [05/Dec/2021 21:13:23] "GET /dashboard/ HTTP/1.1" 500 94504 Content of docker-compose.yml file: version: "3.7" services: mongodb_container: image: mongo:latest volumes: - mongodb_data_container:/data/db ports: - 27017:27017 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - django_data_container:/home/app/webapp ports: - "8000:8000" links: - mongodb_container depends_on: - mongodb_container Can anyone tell me how I can communicate the Django with mongoDB using dockers? -
django Many-To-One relationship model
I want to create models with this specs : A user has ONLY ONE profile to add extra info I want to users to be able to belong to ONLY ONE organization Is it right to write this : Class User(models.Model) name ... class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) address = models.CharField(max_length=100) ... class organization(models.Model): members = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=100) ... or Class User(models.Model) name ... organizatiob = models.ForeignKey(Organization, on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.PROTECT) address = models.CharField(max_length=100) ... class organization(models.Model): name = models.CharField(max_length=100) ... Or I'm completely off the mark? -
How to associate quantity amount in Django's many to many relationship
In Django I have 2 models. One called Box and one called Product. A Box can have many different products and with different quantities of each product. For example box1 can have 1 productA and 2 productB. My box model class Box(models.Model): boxName = models.CharField(max_length=255, blank = False) product = models.ManyToManyField(Product) def __str__(self): return self.boxName My product model class Product(models.Model): productName = models.CharField(max_length=200) productDescription = models.TextField(blank=True) productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0) class Meta: db_table = 'products' ordering = ['-productName'] def __str__(self): return self.productName How do I set up this model allowing me to select quantity of a products when creating the box object? -
Can't login after overriding default user model in Django
I have customized default Django model and now after creating a new superuser I can't login. It says that login or password is invalid. models.py: class UserProfileManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError("Email is required") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, password = password ) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name,password=None): user = self.create_user( email = self.normalize_email(email), password = password, first_name = first_name, last_name = last_name ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser): GENDERS = ( ("Male", "Male"), ("Female", "Female"), ("Other", "Other") ) email = models.EmailField(max_length=150, unique=True) first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) birth_date = models.DateField(blank=True, null=True) gender = models.CharField(choices=GENDERS, max_length=50, blank=True, null=True) location = models.CharField(max_length=150, blank=True, null=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserProfileManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True settings.py: AUTH_USER_MODEL = "UserProfile.UserProfile" AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) So when I create a new superuser and try to login in admin panel I … -
DRF API design: the best way to create views for logged-in user
I'm working on a DRF + React app that allows users to label medical data. Need your opinion on my API design There are 3 models here: User, Annotation and IC (independent component). Each User can make only one Annotation for each IC. Currently, I made a separate view with implicit user substitution. GET gives me existing annotation for a user or empty JSON if not exists. POST allows me to create/update annotation for a user. URL has the form of /api/user-annotation-by-ic/1 class UserAnnotationByIcView(APIView): permission_classes = [IsAuthenticated] serializer_class = UserAnnotationSerializer def get(self, request, ic_id): try: obj = Annotation.objects.get(ic=ic_id, user=request.user) serializer = self.serializer_class(obj) return Response(serializer.data) except ObjectDoesNotExist: return Response({}) def post(self, request, ic_id): create = False data = request.data data['ic'] = ic_id context = { 'request': self.request, } try: obj = Annotation.objects.get(ic=ic_id, user=request.user) serializer = self.serializer_class(obj, data=data, context=context) except ObjectDoesNotExist: serializer = self.serializer_class(data=data, context=context) create = True serializer.is_valid(raise_exception=True) serializer.save() if create: return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.data) In all tutorials on DRF I see ViewSet CRUD views with filtering feature. Following this approach, I could use URLs like /api/annotations?user=1&ic=1. For security reasons, I would have to check that provided user matches to the logged-in user. So which approach is better? What … -
How to give css style in Django filter
Friends, is there any other way to change the style of Django filter fields except Bootstrap? can we style it ourselves with css -
How to build a E-commerce website using django
Hello guys.... Any one can suggest me, a video tutorial and wab-site tutorial of build a E-commerce project using django,html ,css, and any database but dont't useing javascript because i don't JS. And what is functionality went to add on my project.... I think you guys help me.. Thanks....