Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Losing data when overriding post method in UpdateView
I wanted to use the same UpdateView with two different templates for 2 separate tasks: Update couple of CharFields Delete instances of related model I pass it different templates in urls.py and override post method like this: def post(self, request, *args, **kwargs): self.object = self.get_object() uploads = Upload.objects.filter(press=self.object) marked_uploads = request.POST.getlist('marked_upload', None) if marked_uploads is not None: for upload_id in marked_uploads: upload = uploads.get(id=upload_id) upload.file.delete(save=True) upload.delete() return super(PressUpdateView, self).post(request, *args, **kwargs) The problem is this: because i don't render CharFields in second template every time i call POST function from my second template, the values in them get erased. How do i correctly override post method so it doesn't happen. PS I know i can simply add <div style="display:none;">{{ form.as_p }}</div> to the form in my second template, but i want to know how to do it in post. -
My live Django website works fine, but my local repo is broken
DM Why does my working website not work from local clone? 0 Daniel Mark · Lecture 56 · 7 minutes ago Hi there, So I have my website running and am generally happy with it. I want to do some updates (add commenting to my blog app and also fix the link from main page to blog). However the website pulled from git does not work locally (error messages at bottom of message). I have had this problem since deleting some image files from the local media (these were my dummy images "uploaded" via the admin page) I have checked using git push from the website and git pull locally (and even with a fresh git clone locally to another folder). The live website on the server is running the latest code (I restarted nginx and gunicorn and even the whole server using sudo reboot). I tried python manage.py flush to blitz the local database, but I cannot recreate one locally. I created a new directory on my local machine and did a git clone, made a virtual env and did a pip install of my requirements. So my question is why is this happening? I don't want to start … -
Is there anyway to upload multiple image in my blog?
''' views.py ''' I can upload single image in my db. I want to upload multiple image. Is their anyway to solve the problem.helphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelp class IndexView(View): def get(self, request, *args, **kwargs): slide = Slider.objects.all() blogslide = BlogSlider.objects.all() post_form = PostForm() paginator = Paginator(blogslide, 3) page = request.GET.get('page') blogslide = paginator.get_page(page) return render(request, 'index.html', {'slide': slide, 'blogslide': blogslide, 'post_form': post_form}) def post(self, *args, **kwargs): post_form = PostForm(self.request.POST, self.request.FILES or None) if post_form.is_valid(): title = post_form.cleaned_data['title'] sub_title = post_form.cleaned_data['sub_title'] description = post_form.cleaned_data['description'] image = post_form.cleaned_data['image'] p = BlogSlider( description = description, image = image, title = title, sub_title = sub_title, user = self.request.user, ) p.save() #return JsonResponse({'newcomic': model_to_dict(p)}, status=200) return redirect('/') ''' forms.py This is my form help help help help help help help help helphelp ''' class PostForm(ModelForm): image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = BlogSlider fields = ('title', 'sub_title', 'description',) ''' models.py this is model.helphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelp ''' class BlogSlider(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField() title = models.CharField(max_length = 100) sub_title = models.CharField(max_length = 20) description = models.TextField(null=True, blank=True) slug = models.SlugField(null=True, blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.sub_title) super(BlogSlider, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('blog-details', kwargs={ 'slug':self.slug }) class Meta: ordering = ['-id'] -
Design Patterns for Integrating External Data with Django's Database-Backed Models
I'm building a Django web application that maintains both relational data in a MySQL database as well as loosely coupled (by reference ID) full-text data in ElasticSearch (for optimized search). When a new object is created, I leverage Django signals + Celery tasks to asynchronously index the full-text data into Elasticsearch via elasticsearch-py, which works nicely. I had originally started with more tightly-coupled approaches (haystack and django-elasticsearch-py), but I quickly realized that I lost flexibility and decided to de-couple a bit. Well, now I've come full circle as I begin to develop my views/templates (where I largely leverage Model Querysets and the like) and I'm faced with decisions on how to best "fold-in" my loosely-coupled external data. For example, if my homepage by default displays a list of the 50 most recent objects, but then a user conducts a full-text search, how do I best replace the objects (via Ajax) on the page with the ES search result while also linking corresponding database data? And then revert to the Model Queryset data when a filter is pressed and the search is cleared? In other words, what are best practice implementations and design patterns for integrating external data with Django ORM/database-backed … -
Django should I use select_for_update in my view?
Imagine these two cases: First case A website where users can rent cars with each other, so the view that handle the reservation should be something like this: def reservations(request, id): deal = Deal.objects.filter(id=id, available=True) # if not exist return error ... if request.method == 'POST': form = ReservationDealForm(request.POST) if form.is_valid(): reservation = ReservationDeal() with transaction.atomic(): reservation.check_in = form.cleaned_data['check_in'] reservation.check_out = form.cleaned_data['check_out'] # ... reservation.deal = deal[0] reservation.save() deal.update(available=False) # We make the deal not available return redirect('index') Second case An e-commerce website with the view that handle the add to cart feature should be something like this: def add_to_cart(request, id): # ... quantity_request = form.cleaned_data.get('quantity') item = Item.objects.filter(id=id) with transaction.atomic(): # decrease the stock item.stock -= F('stock') - quantity_request item.save() # create an order item for the user or if # he has an order item we update only the quantity order_item = OrderItem.objects.create(user=request.user, item=item, quantity=quantity_request) # ... My questions are: For the first case, what happens if two people in the website click "reserve car" simultaneously for an available car ? It could happen that both requests are valid ? the transaction.atomic guarantee that this cannot happen or should I use select_for_update ? For the second case same … -
Having trouble extending UserDetailSerialzer in django-rest-auth
The project I am currently working on requires allowing the user to update their user info along with their user profile info. I followed the instructions on the django-rest-auth faq page for how to extend the UserDetailSerializer to allow this https://django-rest-auth.readthedocs.io/en/latest/faq.html but when I test the update methods locally I get the following error: (0.005) QUERY = 'SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > %s AND "django_session"."session_key" = %s)' - PARAMS = (datetime.datetime(2020, 5, 8, 1, 44, 9, 588358), '2f8sxtig4ajxjvylyl4naa6bv6ibjk49'); args=(datetime.datetime(2020, 5, 8, 1, 44, 9, 588358), '2f8sxtig4ajxjvylyl4naa6bv6ibjk49') (0.003) QUERY = 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = %s' - PARAMS = (1,); args=(1,) Bad Request: /rest-auth/user/ "PUT /rest-auth/user/ HTTP/1.1" 400 73 My code for the serializer is: from rest_framework.validators import UniqueValidator from django.contrib.auth.models import User class UserSerializer(UserDetailsSerializer): dob = serializers.CharField(source="profile.dob") bio = serializers.CharField(source="profile.bio") profile_link = serializers.URLField(source="profile.profile_link") class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('dob', 'bio', 'profile_link') def update(self, instance, validated_data): profile_data = validated_data.pop('profile', {}) dob = profile_data.get("profile.dob") bio = profile_data.get("profile.bio") profile_link = profile_data.get("profile.profile_link") instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.profile if profile_data and dob: profile.dob = dob profile.save() if profile_data and … -
Django Pagination - how to reduce number of displayed links?
How to display this << 1 2 3 4... 11 12 >> instead of this << 1 2 3 4 5 6 7 8 9 10 11 12>> in my site on Django using pagination ? Thank you in advance !!! My html code: <div class="row"> <div class="col-md-12"> {% if jokes.has_other_pages %} <ul class="pagination"> {% if jokes.has_previous %} <li class="page-item"> <a href="?page={{jokes.previous_page_number}}" class="page-link">&laquo;</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">&laquo;</a> </li> {% endif %} {% for i in jokes.paginator.page_range %} {% if jokes.number == i %} <li class="page-item active"> <a class="page-link">{{i}}</a> </li> {% else %} <li class="page-item"> <a href="?page={{i}}" class="page-link">{{i}}</a> </li> {% endif %} {% endfor %} {% if jokes.has_next %} <li class="page-item"> <a href="?page={{jokes.next_page_number}}" class="page-link">&raquo;</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">&raquo;</a> </li> {% endif %} </ul> {% endif %} </div> </div> -
Django default entries on model creation
I'm sure this has been asked before, but I cannot find the answer. In django, if I have this model from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) How would one populate this model with a default Person entry when the first migrating the field? I'm not talking about default values for the fields, but for default entries in the database. thanks -
Insert String Into Django URL in JQuery Load
I'm new to JQuery, Django and web development in general. I'm trying to figure out how to insert a string into the URL in the JQuery load function based on HTML data, but I'm getting reverse URL errors. I have view that returns a rendered HTML table from a file given a search query: urls.py urlpatterns = [ ... path('database/<search>', views.db_search, name='db_search'), ... ] views.py def db_search(request, search): return render(request, 'app/Content/database.htm', {'context': context}) This works fine when I hard-code the search string in JQuery as: $(".filterBtn").click(function(){ $("#mainpanel").load("{% url 'db_search' 'str_param' %}"); }); The problem is that there are multiple filter buttons which are dynamically generated by Django based on the state of the database. I don't want to hard-code the search parameters (nor should I). What I want to do is something like: $(".filterBtn").click(function(){ $("#mainpanel").load("{% url 'db_search' this.innerText %}"); }); but Django throws reverse URL errors because "this.innerText" isn't defined. Reverse for 'db_search' with arguments '('',)' not found. 1 pattern(s) tried: ['database/(?P[^/]+)$'] Am I missing something? It seems like this should be pretty straightforward. -
Value error when trying to migrate models in Django
I am trying to run migrations on my models but keep running into a ValueError. Here is my models.py: class Vehicles(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) make = models.CharField(max_length=128) model = models.CharField(max_length=128) cover_image = models.ImageField(default='vehicle_cover_pics/default.jpg', upload_to='vehicle_cover_pics') class Meta: verbose_name = 'Vehicles' verbose_name_plural = 'Vehicles' def __str__(self): return f"{self.user.username}'s {self.model}" def get_image_filename(instance, filename): id = instance.vehicle.id return f"vehicle_pics/{id}.jpg" class VehicleImages(models.Model): vehicle = models.OneToOneField(Vehicles, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_image_filename, default=None) class Meta: verbose_name = 'Vehicle Images' verbose_name_plural = 'Vehicle Images' def __str__(self): return f"{self.vehicle.user.username}'s {self.vehicle.model} Image" And when I try to migrate the models i get the following error: C:\Users\T Smith\Documents\Python\garage>python manage.py migrate Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, home, sessions Running migrations: Applying accounts.0021_auto_20200508_1328... OK Applying home.0002_auto_20200507_1905...Traceback (most recent call last): File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 1768, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'None' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\core\management\base.py", line 369, … -
How to extract folder from .gitignore?
Folks, I've deleted my own django project by accident and then cloned it from Github. But the problem is that before pushing I've added my virtual environment folder to .gitignore and now can't extract/use/activate it. What can I do sometimes ? -
Uncaught SyntaxError: Unexpected token '<' VUEJS-DJANGO
I am trying to up on an application, it is made with Django using Vue.js like templates. I have the Vue app in a folder inside to Django Project, the name is Frontend. I link the static files to dist/static inside to Frontend Vue app. In localhost it working correctly, with this configuration in settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/dist/static/') ] MEDIA_ROOT = os.path.join(BASE_DIR,'MEDIA') MEDIA_URL = '/media/' TEMPLATES = [ ... 'DIRS': [os.path.join(BASE_DIR, 'frontend/dist')], ... ] But my server forces me to use this configuration, and nothing work. STATIC_URL = '/' STATIC_ROOT= '/home/usuario_cpanel/python/miapp/public/' When I tip my domain in Browser, it response a white page with this errors in console: Uncaught SyntaxError: Unexpected token '<' ---- vendor.109784b9586c18ebcb5e.js:1 Uncaught SyntaxError: Unexpected token '<'----- app.69d321f0d34cdfbb9e42.js:1 My urls.py urlpatterns = [...] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += [ url(r'^.*$', include(('articles.urls', 'articles'), namespace='articles')), ] And my config/index.js build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, useEslint: false, productionGzip: false, productionGzipExtensions: ['js', 'css'], bundleAnalyzerReport: process.env.npm_config_report }, I am not sure if this configuration is correct, but I tested some posibilities, and nothing work. -
Django integration with Charts.js, I'm unable to find the syntax for passing the data to the template
I'm trying to integrate charts.js charts with django. So far im able to display the pie chart. But the problem im facing is in the bar chart or charts such as where i have not just x and y but x, y1, y2, y3 etc. I'm unable to find the syntax for passing the data to the template Here's my Model class due(models.Model): months= models.CharField(max_length=30) paid = models.PositiveIntegerField() unpaid = models.PositiveIntegerField() def __str__(self): return "{}-{}".format(self.months, self.paid,self.unpaid) Here's my View def graph2(request): labels = [] data = [] queryset = due.objects.order_by('-paid')[:10] for Due in queryset: labels.append(Due.name) data.append(Due.paid,Due.unpaid) return render(request, 'account/graph1.html', { 'labels': labels, 'data': data, }) And this is where i want to access the data from my view, how do i replace the both data fields with my paid and unpaid fields from views. I know the data: {{ data|safe }} this is the syntax but it gets only one column. How do i get y1, y2, y3 etc. <script> new Chart(document.getElementById("bar-chart-grouped"), { type: 'bar', data: { labels: ["1900", "1950", "1999", "2050"], datasets: [ { label: "Africa", backgroundColor: "#3e95cd", data: [133,221,783,2478] }, { label: "Europe", backgroundColor: "#8e5ea2", data: [408,547,675,734] } ] }, options: { title: { display: true, text: 'Population … -
Why does the for loop behave like this?
When I run the program, the for loop does not delete all the list items, but only certain ones. Why? Here is the code: def res(array): for i in range(len(array)): print(array[i]) del array[i] print(array) arr = [10, 5, 40, 30, 20, 50] res(arr) -
didn't return an HttpResponse
Good morning, when I try to send the form, I get the error, and when I send it, it generates that my view does not return any httpresponse object. this is the view class ProductView(View): template_name = 'products/product.html' model = Product form_class = ProductForm def get_queryset(self): return self.model.objects.filter(state=True) def get_context_data(self, **kwargs): context = {} context['product'] = self.get_queryset() context['list_product'] = self.form_class return context def get(self, request, *args, **kwargs): return render(request, self.template_name, self.get_context_data()) def post(self, request, *args, **kwargs): list_product = self.form_class(request.POST) if list_product.is_valid(): list_product.save() return redirect('products:product') and this is the form class ProductForm(forms.ModelForm): name_product = forms.CharField( max_length=25, widget=forms.TextInput( attrs={ 'class': 'form-control', 'id': 'name_product', } ) ) def clean_name_product(self): name_product = self.cleaned_data.get('name_product') if Product.objects.filter(name_product=name_product).exists(): raise forms.ValidationError('El nombre del producto ya existe') return name_product class Meta: model = Product fields = ( 'name_product', 'description', 'price', 'category', 'state', 'image' ) labels = { 'name_product': 'Nombre del Producto', 'description': 'Descripcion', 'price': 'Precio', 'category': 'Categoria', 'state': 'Estado', 'image': 'Imagen del Producto', } widgets = { 'name_product': forms.TextInput( attrs={ 'class': 'form-control', 'id': 'name_product', } ), 'description': forms.TextInput( attrs={ 'class': 'form-control', 'id': 'description', } ), 'price': forms.NumberInput( attrs={ 'class': 'form-control', 'id': 'price', } ), 'category': forms.SelectMultiple( attrs={ 'class': 'custom-select', 'id': 'category', } ), 'state': forms.CheckboxInput(), } when I give … -
How to manage version controlled Django migrations as a team?
We're a small team of developers working on a version-controlled Django 3 project. We are worried about utilizing migrations and the possibility of overwriting one another's migration files. Options we've considered: Using the --name / -n option of makemigrations to have a naming convention, but that seems cumbersome Django documentation mentions tools for version control, but I don't see much on the specifics on it. How do other teams handle this? -
Can not get images to be displayed in Django template
The title is pretty much self explanatory. I did put some images in the static/rakunai folder and added the dirs etc, the whole shebang. I still can't get to display it. I am using docker. Python 3.8 was used and the newest django version was used. The settings.py: ``` """ Django settings for rakunai project. Generated by 'django-admin startproject' using Django 2.2.12. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/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__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'rakunai.urls' STYLESHEETS='/stylesheets/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], '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', ], }, }, ] WSGI_APPLICATION = 'rakunai.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', … -
What is a "state operation" and "database operation" in SeparateDatabaseAndState?
This is an extension to this question: Move models between Django (1.8) apps with required ForeignKey references The Nostalg.io's answer worked perfectly. But I still can't get what is a "state operation" and "database operation" and what actually is going on when using SeparateDatabaseAndState. -
OSError: [WinError 123] La syntaxe du nom de fichier, de répertoire ou de volume est incorrecte: '<frozen importlib._bootstrap>'
I have an error but did know why and how to resolve I start a new projects and use code of my previous project for authentification I install all dependencies Problem come form 2 dependencies crispy_forms and boostrap4 I already use in the same way As you can see in the settings.py below, crispy_forms and boostrap4 are declared in apps My virtual env is active and I have install all dependencies in this environnement If I deactivate the 'crispy_forms' and 'bootstrap4' in INSTALLED_APP, my home page can be display but error raised if I try to display the login page (error: 'crispy_forms_tags' is not a registered tag library) settings.py """ Django settings for mereva project. Generated by 'django-admin startproject' using Django 3.0.6. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/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__))) # 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! SECRET_KEY = 'rc_oh(6&d$)jin3txiiiqvuw2+-mla*f^em9!=yzlgx_o^mph9' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # … -
Speed up Django Migrations on Large Database
I have a MySQL DB with multiple tables that each have almost 2M records. When I run a migration that updates those tables, it's very slow. I tried beefing up the server to 64 CPU and 240GB RAM (probably really unnecessary) but it's still taking too long. Is there any way to speed up the migrations? -
create a table in django and save model to it
I am stuck on this stage where I need to save my model to a particular table. I have installed postgres and now I want to firstly create 2 tables A and B and append instance of model 'modelA' to table 'A' and of 'modelB' to B. I cannot find much on this on googling and stackoverflow in a clear form. -
Django always trying to connect to Mysql using root user
I created a Dockerfile to build a docker image for a django Project : FROM python:3.6 RUN apt-get update \ && apt-get install -y --no-install-recommends \ postgresql-client \ && rm -rf /var/lib/apt/lists/* WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY shop /usr/src/app RUN python manage.py migrate EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] And in my settings.py i have this : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'USER ': 'admin', 'HOST': 'mydatabase.eu-west-3.rds.amazonaws.com', 'PASSWORD': 'adminadmin', 'PORT': '3306', } } Now when building the image i'm having this error : ** django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'172.31.7.119' (using password: YES)") ** What don't understand is why the error talking about a user "root" while in my settings.py it's clearly set to "admin" ? -
AttributeError: module 'django.db.models' has no attribute 'RegexField'. python (django)
I want add RegexField but i have this error. why? found it on Google but there is nothing on regexfield this is error mob = models.RegexField(regex=r'^+?1?\d{9,15}$') AttributeError: module 'django.db.models' has no attribute 'RegexField' models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from django import forms class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) mob = models.RegexField(regex=r'^\+?1?\d{9,15}$') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() -
Duplicate elements (products) is creating in Swiper function of js in django template
I am trying to show some products Django template. I have tried Swiper js class to show those products in a div. There are two buttons "prev" and "next" used to scroll horizontally in those products. In my Product model, there is one product i have inserted from admin and going to see how its shown in the Swiper div. But its showing duplicates of that one element whenever i am trying to click "prev" or "next" or grabbing by "Cursor" I got idea from this link. Picture in which my product is shown in the Swiper div: HTML CODE in Django template: <!-- products --> <div class="container my-4 bg-white border border-light-dark flex"> <div class="lunchbox"> <!-- slider main container --> <div id="swiper1" class="swiper-container"> <!-- additional required wrapper --> <div class="swiper-wrapper"> <!-- slides --> {% for product in products %} <div class="swiper-slide"> <div class="product"> <img class="photograph" src="/media/product_images/{{product.product_code}}.jpg" alt=""> <h2 class="product__name">{{product.name}}</h2> <p class="product__description"><span class="font-weight-normal">৳</span>{{product.product_price}}</p> </div> </div> {% endfor %} </div> <!-- pagination --> <div class="swiper-pagination"></div> </div> <!-- navigation buttons --> <div id="js-prev1" class="swiper-button-prev btn-edit" style="top:35%;"></div> <div id="js-next1" class="swiper-button-next btn-edit" style="top:35%;"></div> </div> </div> JavaScript CODE: (function() { 'use strict'; const mySwiper = new Swiper ('#swiper1', { loop: true, slidesPerView: 'auto', centeredSlides: true, a11y: … -
Django unit tests are returning a strange format where strings are being returned in the format [33 chars] of [num chars]
I am currently building a django-rest-framework API and the unit tests seem to be mostly working but there seems to be a problem with how strings are being handled. So for example I have a test for updating users and it is failing with AssertionError: {'pk': 3, 'username': 'new_user', 'email': [33 chars]: ''} != {'username': 'new_user', 'email': 'new_user[20 chars]': 3} I haven't run into this before and I'm not sure why it is behaving like this. My test settings are: if 'test' in sys.argv in sys.argv: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'HOST': '', 'PORT': '', 'USER': '', 'PASSWORD': '', } } Any ideas on why this is happening?