Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError at /products/register type object 'address' has no attribute 'USERNAME_FIELD'
Write a code for register function user. here i have auth_user model one-to-one connection with address model. While i am open register.html this error occurs i am refering lots of tutorial & question answer sessions but this is not yet solved. please help to solve it. Error Message AttributeError at /products/register type object 'address' has no attribute 'USERNAME_FIELD' Request Method: GET Request URL: http://127.0.0.1:9000/products/register Django Version: 3.2.9 Exception Type: AttributeError Exception Value: type object 'address' has no attribute 'USERNAME_FIELD' Exception Location: C:\Users\sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\forms.py, line 103, in init Python Executable: C:\Users\sujit\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.0 Python Path: ['C:\Users\sujit\OneDrive\Desktop\project\django', 'C:\Users\sujit\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\sujit\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\sujit\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\sujit\AppData\Local\Programs\Python\Python39', 'C:\Users\sujit\AppData\Roaming\Python\Python39\site-packages', 'C:\Users\sujit\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Wed, 17 Nov 2021 17:13:50 +0000 -
Django and chartjs, Why can't I display same three chart on home page
I want to display a 3 x chart on the home page. The problem is that only one is displayed If I remove first {% block%} from first div, chart will be displayed from the second div. How do I view all three charts? Thanks for every reply. in base.html <div class="card1"> {%block chart1%}{%endblock%} </div> <div class="card2"> {%block chart2%}{%endblock%} </div> <div class="card3"> {%block chart3%}{%endblock%} </div> in index.html {% block chart1 %} <div class="charts"> <canvas id="myChart"></canvas> <script> const ctx = document.getElementById('myChart'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: [ {% for x in data %}'{{ x.name }}',{% endfor %}, {% for y in data %}'{{ y.numbers }}',{% endfor %},], datasets: [{ label: '# of Votes', data: [ {% for x in data %}{{ x.name2 }},{% endfor %}, {% for y in data %}{{ y.name2 }},{% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', ], borderWidth: 5 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </div> {% endblock chart1 %} {% block chart2 %} Here's the code from chart1 {% endblock chart2%} {% block chart3 %} … -
Django inlineformset issue
Helo, i want to ask you, how to add dynamic forms with formsets, i have this code , it works correctly but it dont send data to database, can you tell me how to work with this, what do .empty_form part in this formset enter code here <form id="post_form" method="post" action="{% url 'home' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <a href="javascript:void(0)" id="add_form">Add Form</a> <br><input type="submit" name="submit" value="Submit" /> {{ form_images.management_form }} </form> <script src="{% static 'multiimages/js/main.js' %}"></script> <script> var form_count = {{form_images.total_form_count}}; $('#add_form').click(function() { form_count++; var form = '{{form_images.empty_form.as_p|escapejs}}'.replace(/__prefix__/g, form_count - 1); $('#post_form').prepend(form) $('#id_form-TOTAL_FORMS').val(form_count); }); </script> views class ItemCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): template_name = "multiimages/index.html" success_message = 'Item successfully added!' form_class = ItemForm success_url = "posts" model = Item def get_context_data(self, **kwargs): context = super(ItemCreateView, self).get_context_data(**kwargs) context['form_images'] = ItemImageFormSet() if self.request.POST: context['form_images'] = ItemImageFormSet(self.request.POST, self.request.FILES) else: context['form_images'] = ItemImageFormSet() return context def form_valid(self, form): context = self.get_context_data() form_img = context['form_images'] with transaction.atomic(): form.instance.user = self.request.user self.object = form.save() if form_img.is_valid(): form_img.instance = self.object form_img.save() return super(ItemCreateView, self).form_valid(form) -
Check if email already exist in database
In my django account app I want to check if inputed email exist in database (basic django db.sqlite3). forms.py: from django import forms from django.contrib.auth.models import User class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Hasło', widget=forms.PasswordInput) password2 = forms.CharField(label='Powtórz hasło', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'first_name', 'email') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Hasła nie są identyczne.') return cd['password2'] views.py: def register(request): if request.method == "POST": user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Creating new user object, without saving in database new_user = user_form.save(commit=False) # Setting new password new_user.set_password( user_form.cleaned_data['password']) # Saving user object new_user.save() return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form}) Now when i enter the same email for another user, form creates that user. I think is it possible to make this in that way? 1). make email as variable like password and password2 2). remove email from meta 3). create method clean_email() with checking if email exist in db if not raise error I don't know how to get to emails in db Thanks for all help! -
How can I implement the same widget that Django uses to ManyToMany fields in the admin page?
My models: class Ingredient(models.Model): BASE_UNIT_CHOICES = [("g", "Grams"), ("ml", "Mililiters")] CURRENCY_CHOICES = [("USD", "US Dollars"), ("EUR", "Euro")] ingredient_id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) base_unit = models.CharField(max_length=2, choices=BASE_UNIT_CHOICES) cost_per_base_unit = models.FloatField() currency = models.CharField( max_length=3, choices=CURRENCY_CHOICES, default="EUR") def __str__(self): return self.name class RecipeIngredient(models.Model): quantity = models.FloatField() ingredient_id = models.ForeignKey(Ingredient, on_delete=models.CASCADE) def __str__(self): return f"{self.quantity} / {self.ingredient_id}" class Recipe(models.Model): recipe_id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) ingredients = models.ManyToManyField(RecipeIngredient) date_created = models.DateTimeField('Date Created') def __str__(self): return f"{self.name}, {self.ingredients}" When I use the admin page, it has this + button that allows me to create new ingredient/quantity combinations like this But when I try to use it from a form in my code it looks like this Here is my form code: class AddRecipeForm(forms.ModelForm): class Meta: model = Recipe fields = ['name', 'ingredients', 'date_created'] -
django.contrib.admin.sites.AlreadyRegistered: The model BookInstance is already registered in app 'catalog'
For some reason I can't run my webapp because of this code it is showing this error: django.contrib.admin.sites.AlreadyRegistered: can anyone help me what should I do? class BookInstance(models.Model): """Model representing a specific copy of a book (i.e. that can be borrowed from the library).""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library') book = models.ForeignKey('Book', on_delete=models.RESTRICT, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) status = models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default='m', help_text='Book availability', ) class Meta: ordering = ['due_back'] def __str__(self): """String for representing the Model object.""" return f'{self.id} ({self.book.title})' @property def is_overdue(self): if self.due_back and date.today() > self.due_back: return True return False -
psycopg2-binary installation into a virtual environment fails when trying to compile source code
I am trying to install psycopg2-binary into my Django project. I am using a virtual environment and the command I'm running is pip install psycopg2-binary However, I'm getting a massive error message, the gist of it is this: Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. But, hey, I'm installing exactly 'psycopg2-binary' Why am I getting all this mess? -
How can I display images from my Django DB?
Currently, although it may not be best practice, I have images stored in my django database and want to fetch them to display in a gallery page. However, I cannot get the image to display at all, which I think is because it does not arrive at the correct path. <img src ="{% static 'img/' object.image %}"> This code is to try and arrive at the correct directory for the uploaded image which is \AFA\src\artForAll\static\img Also object.image comes from this model class GalleryPost(models.Model): title = models.CharField(max_length=120) description = models.TextField(blank =True, null=True) artist = models.CharField(max_length=120) featured = models.BooleanField(default= False) image = models.ImageField(null = True, blank = True, upload_to = "static/img/") All of the other fields here work and I can see that the image is being uploaded to the correct place. -
Need Assistance with Raw MySQL Query in Django or Calling a View in Django that Does Not Error from No Primary Key Inclusion
I am working on a project that deals with capacity and resource planning for a small business. I have built an app using a Django that facilitates collection of data for assigned tasks and target goals and then compares that to user entries made against tasks assigned to them. The query for the Finance department should display as two tables on a single page. After researching this topic for some time, I have found two ways that sound best for dealing with the specific SQL queries needed: Use the Raw SQL option for Django to create the lists. Create a View in MySQL and set the model in the model file as a managed=False model. There are several problems impeding progress with this query that seem to stem from the need query sets have in Django to have a primary key value. SQL Queries The following are the two queries as they are executed successfully in the MySQL Workbench: SELECT projects.project_number AS 'project', projects.start_date AS 'start_date', projects.target_date AS 'target_date', SUM(tasks.target_hours) AS 'target_hours', SUM(activities.hours) AS 'billed_hours', (SUM(tasks.target_hours) - SUM(activities.hours)) AS 'remaining_hours' FROM activities INNER JOIN tasks ON activities.task_id = tasks.id INNER JOIN projects ON tasks.project_id = projects.id GROUP BY projects.project_number, tasks.task_number, … -
Django page that uploads csv in memory and sends off json to api
I am attempting to use django to make a site that interacts with an api for the user. The first page of the site needs to be a csv upload, that then parses the data into a json format and sends if off to the api. I've gone through the django tutorial for the polls app, and have a minimal understanding of django. But it is really overwhelming. I was able to get the csv upload from this site working: csv upload But that stores the data to a model. (Which may ultimately be ok.) But I was thinking that I could just upload the csv and convert it straight to a json without storing it? I think I'm just looking for some direction on how to have a simple upload where the upload buttom is just a submit that triggers the csv ingestion, formatting, and api request. The only thing I think I need to store is the response from the request. (It returns an ID that I need in order to retrieve the results through a different API call.) I also notices that the current view only updates the table with new rows. So I was able to … -
Django and Tailwind 'TemplateDoesNotExist' error
I am following this tutoiral: https://www.ordinarycoders.com/blog/article/django-tailwind I have a django project called 'project' with two apps in it 'app' and 'main'. I'm trying to load 'main > template > main > home.html'. but I get this error: Internal Server Error: / Traceback (most recent call last): File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\project\main\views.py", line 5, in homepage return render(request = request, template_name="main/home.html") File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: main/home.html [17/Nov/2021 11:49:03] "GET / HTTP/1.1" 500 80436 Following the tutorial, I have in my 'settings.py': """ Django settings for project project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = … -
AttributeError at /products/register type object 'address' has no attribute 'USERNAME_FIELD'
Write a code for register function user. here i have auth_user model one-to-one connection with address model. i am refering lots of tutorial & question answer sessions but this is not yet solved. please help to solve it. aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaagdddddddddddddfdgnfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdnnnnnnnnnnnnnnnnnnnnn forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from . models import address class RegisterForm(UserCreationForm): first_name = forms.CharField( max_length=100, required = True, help_text='Enter First Name', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), ) last_name = forms.CharField( max_length=100, required = True, help_text='Enter Last Name', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}), ) email = forms.EmailField( max_length=100, required = True, help_text='Enter Email Address', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Email'}), ) house_name = forms.CharField( max_length=200, required = True, help_text='Enter House Name', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'House name'}), ) town = forms.CharField( max_length=200, required = True, help_text='Enter Town', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Town'}), ) post_office = forms.CharField( max_length=200, required = True, help_text='Enter Post Office', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Post Office'}), ) pincode = forms.CharField( max_length=200, required = True, help_text='Enter Pincode', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Pin Code'}), ) district = forms.CharField( max_length=200, required = True, help_text='Enter District', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'District'}), ) land_mark = forms.CharField( max_length=200, required = True, help_text='Enter Landmark', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Landmark'}), ) phone = forms.CharField( max_length=200, required … -
Django model object with foreign key add another model properties
I have two models: class Client(models.Model): name = models.CharField('Name', max_length=250) surname = models.CharField('Surname', max_length=250) phone = models.CharField('Phone', max_length=10) ... def __str__(self): return str(self.surname ) + ' | ' + str(self.name) class Checklist(models.Model): client_name = models.ForeignKey(Client, on_delete=models.CASCADE) point1 = models.BooleanField('point1', default=False) point2 = models.BooleanField('point2', default=False) point3 = models.BooleanField('point3', default=False) ... def __str__(self): return self.client_name The questions are: How can i provide or add all Client properties to Checklist instance? (note: I create Checklist object via forms.py) And when it's done how to get an access to Client properties using Checklist object? When I calling Checklist instance and send it to Telegram app - Telegram gives me an 'Id' instead of client_name...how fix it? Thank you all for any help in advance!! -
Django foreign keys queryset displayed in react-redux
I know that this question was asked a lot of times, but I can't find the answer to my specific problem. I have tried to get to the solution both on the backend (Django) and on the frontend (React.js and Redux) but I can't find it. I'm trying to make a simple dependent dropdown for car brands and car models, but I can only get the full list of models and not only the ones that are related to their brand. I'm new at Django and I don't know if my mistake is that I'm retrieving all data in my serializer or if I'm making the foreign key relationship wrong. If you need any more information or explanation please let me know. Thanks for your help! models.py: class Brand(models.Model): name = models.CharField(max_length=120, unique=True) def __str__(self): return self.name class Model(models.Model): brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, related_name='brand_id') name = models.CharField(max_length=120, unique=True) def __str__(self): return self.name serializers.py: class BrandSerializer(serializers.ModelSerializer): class Meta: model = Brand fields = '__all__' class ModelSerializer(serializers.ModelSerializer): class Meta: model = Model fields = '__all__' views.py: @api_view(['GET']) @permission_classes([AllowAny]) def getBrands(request): brands = Brand.objects.all() serializer = BrandSerializer(brands, many=True) return Response(serializer.data) @api_view(['GET']) @permission_classes([AllowAny]) def getModels(request): #This is wrong, but I don't know how to … -
How can I iterate through each item in a database and display them in divs on my html page with django?
I have some code written to find the first post in the database and output it to my page, but I', not sure how to go about iterating through the database. I've done similar things before but this is my first time using django and bootstrap. My view currently looks like this: def gallery_view (request): obj = GalleryPost.objects.get (id =1) context = { 'object' : obj } return render(request, "gallery.html", context) This works well enough for 1 object but as you can see it takes a set ID of 1, so I need to somehow iterate this to fetch every item from my DB and somehow output them properly. -
pytest-django: Register a database type after creation of test databases
I have a django model field that registers a database type: class FieldMeta(type): def __init__(cls, name, bases, clsdict): super().__init__(name, bases, clsdict) cls.register_type() def register_type(cls): db_type = cls().db_type(connection) cursor = connection.cursor() try: cursor.execute( "CREATE TYPE foo AS (first integer, second integer);" ) _logger.warn("creating type") except ProgrammingError: pass cls.python_type = register_composite( db_type, connection.cursor().cursor, globally=True ).type _logger.warn("registering composite") def adapt_composite(composite): return AsIs(...get sql...) register_adapter(Foo, adapt_composite) class FooField(models.Field, metaclass=FieldMeta): def db_type(self, connection): return "foo" This works fine in these situations: Database already knows about type foo Database does not know about type foo The problem is that pytest-django seems to run these init methods before creating the test database, meaning that the test database does not have the required type. I can fix this on individual tests by calling FooField.register_type() in the setUpClass method of the test, but this is not ideal, since it should always be present. I tried overriding the django_db_setup fixture to look like this: @pytest.fixture(scope="session") def django_db_setup( request, django_test_environment: None, django_db_blocker, django_db_use_migrations: bool, django_db_keepdb: bool, django_db_createdb: bool, django_db_modify_db_settings: None, ) -> None: """Top level fixture to ensure test databases are available""" from django.test.utils import setup_databases, teardown_databases setup_databases_args = {} if django_db_keepdb and not django_db_createdb: setup_databases_args["keepdb"] = True with django_db_blocker.unblock(): db_cfg … -
User() got an unexpected keyword argument 'tutors_data'
How can I solve this error User() got an unexpected keyword argument 'tutors_data' in Django rest-framework and djoser? I found some solutions but couldn't help me models.py # Tutoruser Model class TutorUser(models.Model): tutor_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='tutor_user') full_name = models.CharField(max_length=255, blank=True) slug = models.SlugField(max_length=255) phone_number = models.CharField(max_length=14, blank=True) profile_img = models.ImageField(upload_to='images/tutor/profile-img', blank=True) description = models.TextField(blank=True) serializers.py class TutorUserSerializer(serializers.ModelSerializer): class Meta: model = TutorUser fields = [ 'id', 'full_name', 'phone_number', 'description', 'profile_img', ] class UserCreateSerializer(UserCreateSerializer): tutors_data = TutorUserSerializer() class Meta(UserCreateSerializer.Meta): model = User fields = ['id', 'email', 'is_tutor', 'password', 'tutors_data'] def create(self, validated_data): #create user tutor_user_data = validated_data.pop('tutors_data') user = User.objects.create( email = validated_data['email'], password = validated_data['password'], is_tutor = validated_data['is_tutor'], ) if user.is_tutor: for tutor_data in tutor_user_data: TutorUser.objects.create( tutor_user = user, **tutor_data, ) return user if I change tutors_data = TutorUserSerializer() to tutor_user = TutorUserSerializer() it works but gives me another error Cannot assign "OrderedDict()...: "..." must be a "..." instance.... and is it possible to get only one field on UserCreateSerializer from TutorUserSerializer? Thanks in advance. -
Should I be adding the Django migration files in the .dockerignore /.gitignore file?
This is probably a duplicate of this question. My question is how should I approach this when working in a docker environment so for my project I have a docker-compose.yml and docker-compose-deploy.yml for my production environment and obviously migration files are generated only in the docker images and aren't included in my version control system. How should I approach this? should I stop using Docker as my development environment and go for something like virtual environments or even machines? -
Multiple authors for blogpost
I am a bit stuck on trying to solve this So I have a webapp, and decided to add a blog section using wagtail. This means I have quite a few pages and models already preexisting, that I do not want to touch, as well as some users already. I am aware of the owner field in the base Page class, but can't see a way to extend to into a m2m field. To achieve this, I have created a custom user model at users.User. For blog community purposes, I wanted to add the option of picing an avatar and setting a biography, so I added those two (avatar and bio are newly added fields) class User(AbstractUser): name = models.CharField(_("Name of User as displayed to other users"), blank=True, max_length=255) company = models.ForeignKey(Company, null=True, on_delete=models.CASCADE) job_title = models.CharField(max_length=100) avatar = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+') bio = models.TextField(max_length=300, blank=True) Then I have a classic Blogpost page, with title, body streamfield etc... However, I am trying to replace something where you can add multiple post editors, and each of them has edit rights. So I tried something like this: First an orderable since I need many2many: class PostAuthorsOrderable(Orderable): page = ParentalKey("blog.BlogPost", related_name="post_authors") … -
How do I get local server running - here with language error message?
I have a Django app (with a postgres database) running in a virtual environment. Everything has been working on my localhost until a few days ago when I got an error saying my SSL certificate had expired (localhost:8000). Today, when I tried the python manage.py runserver command I got an error saying psycopg2 was not installed. I know it was because I have been using this app for the last nine months! Anyway, I reinstalled psycopg2 and tried the runserver command again. This time I got the following error message: $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "E:\coding\registrations\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "E:\coding\registrations\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "E:\coding\registrations\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "E:\coding\registrations\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "E:\coding\registrations\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "E:\coding\registrations\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\coding\registrations\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "E:\coding\registrations\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, … -
Problem with invitation to event in my project
i have a following problem... I create "event" in my project but i can not invite friends to this "event". I don't get how to identify the "event" correctly to make a invite request to friend. models.py class Event(models.Model): title = models.CharField(max_length=200, blank=False, null=False) creator = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name='creator') participators = models.ManyToManyField(Profile, blank=True) description = models.TextField(blank=True) start = models.CharField(max_length=5) finish = models.CharField(max_length=5) event_date = models.CharField(max_length=50) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-timestamp', ) def __str__(self): return f"Event: {self.title} by {self.creator}. \ Date: {self.event_date}. From:{self.start} to {self.finish}" def get_sum_participators(self): return self.participators.count() class EventInviteRequest(models.Model): from_event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='from_event', null=True) to_profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='to_profile', null=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"From {self.from_event} to {self.to_profile}" This is a function i'm trying to use, but it sends request to 'event' creator. def from_event_to_user_invite_request(request, id): event = Event.objects.get(id=id) to_profile = Profile.objects.get(id=id) event_invite, created = EventInviteRequest.objects.get_or_create( request, from_event=event, to_profile=to_profile) return redirect('events:event_page', event.id) Could you give me some tips how to fix the problem Thank you -
error when saving multiple (onetoonefield) forms in django views.py. pls, Need correct working view or suggestion
models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) mobileno = models.IntegerField(blank=True, null=True) is_customer = models.BooleanField(default=False) is_vendor = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class VendorDetails(models.Model): vendoruser = models.OneToOneField(CustomUser, on_delete=models.CASCADE) aadhar_number = models.CharField(max_length=200) pan_number = models.CharField(max_length=200) store_name = models.CharField(max_length=200) brand_name = models.CharField(max_length=200) mail_id = models.EmailField(max_length=200) contact_no = models.IntegerField(blank=True, null=True) gst_number = models.CharField(max_length=100) acct_number = models.CharField(max_length=100) ifsc_code = models.CharField(max_length=100) fb_account = models.CharField(max_length=100,blank=True, null=True) insta_account = models.CharField(max_length=100,blank=True, null=True) website = models.CharField(max_length=100,blank=True, null=True) door_no = models.CharField(max_length=100,blank=True, null=True) street_name = models.CharField(max_length=100, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) pincode = models.IntegerField(blank=True, null=True) def __str__(self): return self.mail_id forms.py class UserCreationForm(UserCreationForm): """ A Custom form for creating new users. """ class Meta: model = CustomUser fields = ['email','first_name','last_name','mobileno'] """ For Vendor users forms""" class VendorAdminDetailsForm(forms.ModelForm): class Meta: model = VendorDetails fields = ['aadhar_number', 'pan_number'] class VendorStoreDetailsForm(forms.ModelForm): class Meta: model = VendorDetails fields = ['store_name', 'brand_name', 'mail_id', 'contact_no', 'gst_number'] class VendorBankDetailsForm(forms.ModelForm): class Meta: model = VendorDetails fields = ['acct_number', 'ifsc_code'] class VendorSocialMediaDetailsForm(forms.ModelForm): fb_account = forms.CharField(required=False) insta_account = forms.CharField(required=False) website = forms.CharField(required=False) class Meta: model = VendorDetails fields = ['fb_account', 'insta_account', 'website'] class VendorContactDetailsForm(forms.ModelForm): door_no = forms.CharField(required=False) street_name = forms.CharField(required=False) pincode = forms.IntegerField(required=False) class Meta: model = VendorDetails … -
Can anybody help me to find out why the db values are not showing up in the admin form?
I am a newbie so please help me in resolving this issue. I have a DurationField in my models.py. I have overridden the widget attribute of the field in admin.py. I need duration field as a choice field without changing the DurationField in models.py file. So, I have overridden that field with choice field widget so it displays as dropdown limited to five days. Coming to the issue now. When I click on save in admin the data is saved to the database my widget is not getting updated with the values saved in database. Posting the images and code for reference. Im stuck with this issue for more than 5 days. any help would be appreciated class ManagedAccountAdmin(admin.ModelAdmin): form = ManagedUserAdminForm model = ManagedAccount exclude = ('customer', 'created_by', 'modified_by', 'verification_code') formfield_overrides = { models.DurationField: {"widget": forms.Select(choices=((str(i)+" day",str(i)+" Day") if i==1 else ((str(i)+" days", str(i)+" Days")) for i in range(1,6))) }} def get_form(self, request, obj=None, **kwargs): form = super(ManagedAccountAdmin, self).get_form(request, obj, **kwargs) for field in form.base_fields.keys(): form.base_fields[field].widget.can_change_related = False form.base_fields[field].widget.can_add_related = False return form def save_model(self, request, obj, form, change): obj.program = form.cleaned_data.get('program') obj.managed_by = form.cleaned_data.get('managed_by') obj.created_by = request.user obj.duration_in_days = form.cleaned_data.get('duration_in_days') print("duration in save model",obj.duration_in_days) if change: obj.modified_by = … -
Can't find a guide about how to setup Django+Auth0+Graphene
I've been trying to setup my graphene API with Auth0 but I can't make it work. I found similar questions like this: Auth0 - Django and Graphene but yet unanswered. I'd like to get some guidance about how to setup this 3 things together. Maybe pointing me out with a link? -
Headless Django-Oscar - Correct middleware/session setup
I am a bit confused about the correct setup for a headless middleware/session setup using django-oscar-api. The documentation for the latter is telling me to use oscarapi.middleware.ApiBasketMiddleWare if I want/need to mix "normal" django-oscar and django-oscar-api. The same documentation tells me to use oscarapi.middleware.HeaderSessionMiddleware if django-oscar is being communicated from an "external client using Session-Id headers". In my case I am not using Session-Id headers, but only communicate with oscar via api calls. What would be the correct setup/path for my case? Can I just use the oscarapi.middleware.ApiBasketMiddleWare and just use api calls? How will it handle anonymous baskets and merging of baskets after user login(jwt)?