Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django runserver issues - ImportError: DLL load failed while importing _sqlite3: The specified module could not be found
I had a perfectly working Django test server in venv, I made no changes after getting the server to run now I get this error the next day: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Anaconda3\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Anaconda3\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\User1\Desktop\PROGRAMMING\Django\jose_portilla\django_lectures\My_Django_Stuff\myDjangoEnv2\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User1\Desktop\PROGRAMMING\Django\jose_portilla\django_lectures\My_Django_Stuff\myDjangoEnv2\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\User1\Desktop\PROGRAMMING\Django\jose_portilla\django_lectures\My_Django_Stuff\myDjangoEnv2\lib\site-packages\django\db\backends\sqlite3\base.py", line 15, in <module> from sqlite3 import dbapi2 as Database File "C:\Anaconda3\lib\sqlite3\__init__.py", line 57, in <module> from sqlite3.dbapi2 import * File "C:\Anaconda3\lib\sqlite3\dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: DLL load failed while importing _sqlite3: The specified module could not be found. -
Integrating Wagtail Into Django
I have confirmed that my django project works perfectly. However, I am interested in integrating wagtail CMS to the project. I am following Wagtail documentation, for a proper guidance. However, on clicking python manage.py runserver. I get the error shown below. Wagtail Integration Error I have removed all my created apps from INSTALLED_APP, I have also removed them from the available URLs. Unfortunately, non of the above method fixed the problem for me. Your guide on how to fix this type of error will be appreciated. -
Problem with sending email in django using SMTP with new google rules
I am using smtp to send emails in django app but for some reasons it stops working and i found this on the google page. I do not want to use SendGrid or others.because in my app i send more than 1000000 emails per semester and it was working well before this new condition. How can i solve this problem ? Thanks. -
Connecting an internet-facing Django web app (served with Gunicorn) with a non-internet-facing local application to be used by the Django web app
Use case of the internal app: take in a list of words (200-300 words), perform some analysis on them and return large tuples of data, anywhere from 5-10 tuples per word. The Django application will block waiting for the results of the internal app to serve the webpages that needs the word analyses. The reason I want to separate them is because the internal app uses a lot of memory, and integrating the word-analysis (i.e. the task of the internal app) into the Django app will cause high memory usage because of gunicorn forking multiple workers. The internal app uses about 1GB of memory once loaded, but is not compute-intense. Now, assuming I want to host the Django web app and the internal app on the same server, what comes to my mind is to use a flask application for the internal app, and put it behind gunicorn. So two questions: Is there a better way to accomplish this? Is using gunicorn the right way to go for the internal app? -
Django project on AWS EC2, what should put in ALLOWED_HOSTS?
Problem I deployed my project on AWS EC2 with docker. When ALLOWED_HOSTS is set as '*', the web site works fine, it looks just what it should be. After switched ALLOWED_HOSTS from '*' to AWS EC2 Public IPv4 DNS, the website response with Bad request 400. It is weird. Why it happened? Or should I put another value instead of Public IPv4 DNS ? Here are my project config nginx.conf user root; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$host $remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' '$request_time'; access_log /var/log/nginx/access.log main; access_log /dev/stdout; error_log /var/log/nginx/error.log; error_log /dev/stdout info; sendfile on; #tcp_nopush on; keepalive_timeout 65; # Gzip Compression gzip on; # gzip_min_length 1000; gzip_types text/plain application/xml; gzip_proxied expired no-cache no-store private auth; gzip_vary on; include /etc/nginx/conf.d/*.conf; } custom_nginx.conf # the upstream component nginx needs to connect to upstream uwsgi { server unix:/code/demo.sock; } # configuration of the server server { # the port your site will be served on listen 80; listen [::]:80; client_max_body_size 75M; # adjust to taste # Django media location /media/ { alias /code/media/; # your Django project's media files … -
CSS in sub static folder not working properly in Django
I know it's a simple problem but I want to know what I missed. I'm sure the solution is simple. Here is the problem: settings.py: STATIC_URL = 'static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') The tree with the problem: ├── manage.py ├── static │ ├── css │ │ ├── bootstrap.min.css │ │ └── style.css │ └── js └── templates ├── hi.html .html file: {% load static %} <!DOCTYPE html> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> and the boom does not work but some codes work and some do not. I'm not quite sure what's going on there. when there is no subfolder: ├── manage.py ├── static │ ├── bootstrap.min.css │ └── style.css └── templates ├── hi.html and when I use it this way it works fine! {% load static %} <link rel="stylesheet" href="{% static 'bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'cstyle.css' %}"> Am I really missing something? I'm not sure, I haven't opened a project from scratch with django for a long time. Thanks in advance. -
Django Redirects + FeinCMS - URL variable
I am using an older server with Python 2.7 and Django 1.11.7 with FeinCMS as the CMS. If I wanted to redirect any incoming URL from a request that had mixed casing to the proper URL in all lowercase letters, how would I go about doing that? Is there a way to edit the incoming request and, if the page is matched but it's detected not to be a match to the lowercase URL, it will do a redirect to the page? I have the original function below and one that I edited and made enough progress to get the proper page to show up, but the URL in the address bar still has the mixed casing. Any help would be greatly appreciated. Original Function: def dispatch(self, request, *args, **kwargs): try: return super(Handler, self).dispatch(request, *args, **kwargs) except Http404 as e: if settings.FEINCMS_CMS_404_PAGE is not None: logger.info( "Http404 raised for '%s', attempting redirect to" " FEINCMS_CMS_404_PAGE", args[0]) try: # Fudge environment so that we end up resolving the right # page. # Note: request.path is used by the page redirect processor # to determine if the redirect can be taken, must be == to # page url. # Also clear out … -
django avatar upload default value
I got a profile page where I can upload an avatar pic, but when there is no avatar there is this weblink "False" How can I change it to "No Image" string and to remove the weblink tag as well? Is it intended to work as a weblink to the default image? This template uses {{ form.as_p }} to output a page. -
How to give arguments to Class in python
I am trying to create a Django app. I want create function to pass some initial text to text area. I tried following : Here is required part of views.py : from django import forms class createform(forms.Form): def __init__(self, title, value): self.newtitle = forms.CharField(max_length=30, label='Enter Title:', widget=forms.TextInput(attrs={'value': title})) self.content = forms.CharField(widget=forms.Textarea(attrs={'value': value}), label='Enter the description:') def create(request): return render(request, "encyclopedia/create.html", { "form": createform('this title','this content') }) But when I try to run this I get following error: -
django multi select field saves only one value
I have a form that you can select a province and its' cities. This is the model that my form is using in my app: class ScientificSchedule(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) province = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=2048, blank=True) #other fields and the form: class ScientificScheduleForm(forms.ModelForm): class Meta: model = ScientificSchedule fields = '__all__' also these are my views and HTML code: class ScientificScheduleView(FormView): model = ScientificSchedule template_name = 'reg/scientific-schedule.html' form_class = ScientificScheduleForm success_url = '/scientific/schedule' def post(self, request): form = ScientificScheduleForm(request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(ScientificScheduleView, self).form_valid(form) and this is part of the form which is for city and province fields: <form id="manager-users" method="POST" autocomplete="off" class="ant-form ant-form-horizontal"> {% csrf_token %} <div class="ant-row-flex ant-row-flex-space-between" style="margin-left: -10px; margin-right: -10px;"> <div class="ant-col ant-col-xs-24 ant-col-md-12" style="padding-left: 10px; padding-right: 10px;"> <div class="ant-row ant-form-item formItemRow"> <div class="ant-col ant-form-item-label"><label for="province" class="ant-form-item-required" title="province">province</label></div> <div class="ant-col ant-form-item-control-wrapper"> <div class="ant-form-item-control has-success"> <span class="ant-form-item-children"> <div id="province" class="ant-select ant-select-selection ant-select-selection--single" style="width: 100%;"> <select name="province" class="ant-col ant-select-selection ant-select-selection--single" role="combobox" aria-autocomplete="list" aria-haspopup="true" tabindex="-1"> <option value="" class=""> - </option> </select> </div> </span> </div> </div> </div> </div> <div class="ant-col ant-col-xs-24 ant-col-md-12" style="padding-left: 10px; padding-right: 10px;"> <div class="ant-row ant-form-item formItemRow"> <div class="ant-col ant-form-item-label"><label for="city" class="ant-form-item-required" title="city">city</label></div> <div class="ant-col … -
Is there any way to add address autocomplete to django forms?
I am trying to use address autocomplete api and I want to use django forms to save address on database. forms: class AdressInputForm(forms.ModelForm): class Meta: model = AdressInput fields = '__all__' views: def new(request): if request.method == 'POST': form = AdressInputForm(request.POST) form.save() else: form = AdressInputForm() return render(request, 'example_app/index.html', {'form': form}) html: <div class="autocomplete-container" id="autocomplete-container"></div> css: body { font: 16px; background: #f3f5f6; } .autocomplete-container { margin-bottom: 20px; margin-right: 50%; } .input-container { display: flex; position: relative; } .input-container input { flex: 1; outline: none; border: 1px solid rgba(0, 0, 0, 0.2); padding: 10px; padding-right: 31px; font-size: 16px; } .autocomplete-items { position: absolute; border: 1px solid rgba(0, 0, 0, 0.1); box-shadow: 0px 2px 10px 2px rgba(0, 0, 0, 0.1); border-top: none; background-color: #fff; z-index: 99; top: calc(100% + 2px); left: 0; right: 0; } .autocomplete-items div { padding: 10px; cursor: pointer; } .autocomplete-items div:hover { /*when hovering an item:*/ background-color: rgba(0, 0, 0, 0.1); } .autocomplete-items .autocomplete-active { /*when navigating through the items using the arrow keys:*/ background-color: rgba(0, 0, 0, 0.1); } .clear-button { color: rgba(0, 0, 0, 0.4); cursor: pointer; position: absolute; right: 5px; top: 0; height: 100%; display: none; align-items: center; } .clear-button.visible { display: flex; } .clear-button:hover … -
How to check if user has passed the form?
I have a Person class in models.py, a class has a code field (charfield). A user should enter code on the page with the form where he will enter the code user will be allowed to enter the site. It is similar to registration but without actually registration. So, how do i check if he is entered a code? Is there anything similar to "is_authorized" function, but NOT for User model? I tried to add more fields to the User model and authorize on these fields but faced with a lot of problems there is an easier solution? -
Can I move django app simply to the apps folder?
I have django project. and it has apps folder which contains 6-7 apps. I created an app by running manage.py startapp myapp. And it located BASEDIR. Is correct simply move myapp to apps folder. Thanks. -
Django admin add record using signal
I dont have problem with saving the record when the user login, the problem here is for example the user login June 19, 2022 8am and accidentally logout, and if that user login again I dont want the data insert again, I just want that 1 record insert per day, even the user login multiple times class UserLogs(models.Model): user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) time_in = models.DateTimeField(null=True, blank=True) time_out = models.DateTimeField(null=True, blank=True) @receiver(user_logged_in) def post_login(sender, request, user, **kwargs): print(user) insert = UserLogs( fullname = user, time_in = datetime.now() ) print(insert.id) if insert.id.exists(): insert.save() else: print('dont save!') -
Bad Gateway python-telegram-bot with webhook and Nginx
I'm trying to set up a webhook with python-telegram-bot and Nginx. I am faced with a problem, my bot doesn't get messages from telegram. I also tried to make GET/POST queries from the postman and I always get a "502 Bad Gateway" error. I also launched the netstat to monitor port 5000 where my telegram bot connects but it is always empty. It seems like webhook doesn't launch at all. My Nginx default.conf file looks like the following: upstream django { server gunicorn:8000; } server { listen 80; server_name example.com www.example.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; ssl on; server_name example.com www.example.com; ssl_certificate fullchain.pem; ssl_certificate_key privkey.pem; access_log /var/log/nginx/nginx.vhost.access.log; error_log /var/log/nginx/nginx.vhost.error.log; location /TELEGRAM_TOKEN { proxy_pass http://0.0.0.0:5000/TELEGRAM_TOKEN/; } location /static/ { alias /static/; } location / { proxy_pass http://example.com:8000; } } And my telegram client code: updater = Updater(api_token) updater.dispatcher.add_handler(CommandHandler('start', start)) updater.dispatcher.add_handler(CallbackQueryHandler(button)) updater.dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, custom_command)) jq = updater.job_queue job_minute = jq.run_repeating(callback_minute, interval=5) #updater.start_polling() updater.start_webhook(listen="0.0.0.0", port=5000, url_path=api_token, webhook_url=f'https://example.com/{api_token}') updater.idle() I also have Django options for the Nginx server but I've never seen any tutorial or documentation on how to tune the webhook with Django and it can be the reason for my problems. Have anyone any idea about solving … -
Django admin users timein and timeout of the user
Hi I am new in Django framework, I just want to know if is it possible to capture the timein and timeout of the user, I have this model that if the employee1 login on django-admin it will add automatic record and if the user click logout it will update the time-out. What I want is for every time the employee login in django admin it will add record and it will update the record once the employee logout, just like daily attendance record on company. class UserLogs(models.Model): user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) time_in = models.DateTimeField(default=now) time_out = models.DateTimeField(null=True, blank=True) -
How to give specific users specific persmissions to view and edit Specific Areas in Django admin
I'm making a django website whose admin page looks like this I want users(The content writer) to access only the Main Area(Events, Formats, Organisers) and not the whole thing. I haven't made any such user as Content Writer as of now. What are the permissions that should be given to that user. Should I make Groups for users(since there are basically 3 types of users as of now, i.e., Admin(Full Access), Content Writer(Limited Access), Basic Users(No access)) or should I just add one/two more variable(s) in my custom user model so that that user can access only the main area of the admin site. After Giving these permissions can I extract the main area on a new html page and style it accordingly as:- Events, Formats, Organisers, in Navbar and the details of these page presented somewhat beautifully models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager # Custom User Manager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name=None, **extra_fields): if (not email): raise ValueError("Email Must Be Provided") if (not password): raise ValueError("Password is not Provided") user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_active', … -
Django - POST/GET for HyperlinkedIdentityField
I've tried following several guides https://stackabuse.com/creating-a-rest-api-with-django-rest-framework/ https://www.django-rest-framework.org/tutorial/2-requests-and-responses/ Both were not suited because my code uses a HyperlinkedIdentityField How may I go and add a POST/GET request to it? views.py class SpecialityView(APIView): def get(self, request, id=None): if id: item = Speciality.objects.get(id=id) serializer_class = SpecialitySerializer(item) return Response({"status": "success", "data": serializer_class.data}, status=status.HTTP_200_OK) items = Speciality.objects.all() serializer_class = SpecialitySerializer(items, many=True) return Response({"status": "success", "data": serializer_class.data}, status=status.HTTP_200_OK) def post(self, request): serializer_class = SpecialitySerializer(data=request.data) if serializer_class.is_valid(): serializer_class.save() return Response({"status": "success", "data": serializer_class.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer_class.errors}, status=status.HTTP_400_BAD_REQUEST) class WorkerView(APIView): def get(self, request, id=None): if id: item = Worker.objects.get(id=id) serializer_class = WorkerSerializer(item) return Response({"status": "success", "data": serializer_class.data}, status=status.HTTP_200_OK) items = Worker.objects.all() serializer_class = WorkerSerializer(items, many=True) return Response({"status": "success", "data": serializer_class.data}, status=status.HTTP_200_OK) def post(self, request): serializer_class = WorkerSerializer(data=request.data) if serializer_class.is_valid(): serializer_class.save() return Response({"status": "success", "data": serializer_class.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer_class.errors}, status=status.HTTP_400_BAD_REQUEST) serializers.py class SpecialitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Speciality fields = ['id', 'url', 'name'] class WorkerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Worker fields = ['id', 'url', 'name', 'last_name', 'hire_date', 'email', 'phone_number', 'job', 'speciality', 'salary', 'commission_pct', 'manager_id', 'department_id'] Error page : AssertionError at /speciality/ `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. -
Is it possible to restore data from docker postgres volume backup
Primarely wanted to migrate postgress volume to another host, following this instruction https://docs.docker.com/storage/volumes/ on macos made a backup of volume using docker run --rm --volumes-from a1df4bee1dc1 -v $(pwd):/backup debian:jessie tar cvf /backup/backup_db_floo.tar /var/lib/postgresql/data And after deleting and recreating new container/volume and restoring via docker run --rm --volumes-from docker-db-1 -v $(pwd):/backup debian:jessie bash -c "cd /var/lib/postgresql/data && tar xvf /backup/backup_db_floo.tar --strip 1" no my data is there. Now realise that it was bad idea and i have to use pg_dumpall - but is it possible to recover somehow database from that postgres volume backup? -
CREATE MANY TO MANY FIELD DATA IN SERIALIZER
I am trying to send a post request to create an object - course, but every time I get an error, how can I write a serializer for a class - course. What do I need to do so that it creates an object and at the same time displays a list of contacts instead of a list of keys MODELS: class Category(models.Model): title = models.CharField(max_length=30) imgpath = models.CharField(max_length=100) def __str__(self): return self.title class Branch(models.Model): latitude = models.CharField(max_length=250) longitude = models.CharField(max_length=250) address = models.CharField(max_length=250) def __str__(self): return self.address class Contact(models.Model): class Type(models.IntegerChoices): PHONE = 1, FACEBOOK = 2, EMAIL = 3 type = models.IntegerField(choices=Type.choices) value = models.CharField(max_length=250) def __str__(self): return self.value class Course(models.Model): name = models.CharField(max_length=30) description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') logo = models.CharField(max_length=20, blank=True) contacts = models.ManyToManyField(Contact) branches = models.ManyToManyField(Branch, blank=True) def __str__(self): return self.name SERIALIZER: from rest_framework import serializers from application.category.models import Category, Branch, Contact, Course class CategorySerializers(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class BranchSerializer(serializers.ModelSerializer): class Meta: model = Branch fields = '__all__' class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = '__all__' class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = '__all__' def create(self, validate_data): contacts_data = validate_data.pop('contacts') branchs_data = validate_data.pop('branches') … -
Django page reloading too long
I have some issues with the reloading time in some page in django, it takes too long. I use debug_toolbar and shows me Browser timing request: 4 (+113577) models.py class Subsidiary(models.Model): name = models.CharField(unique=True, max_length=100, blank=False) def __str__(self): return self.name class Department(models.Model): name = models.CharField(unique=True, max_length=200, blank=False,) def __str__(self): return self.name class SubBudget(models.Model): name = models.CharField(max_length=100, unique=True, blank=False) def __str__(self): return self.name class SubBudgetOwner(models.Model): budget_owner = models.ForeignKey(Person, models.PROTECT, related_name="budgets_owned") sub_budget_owner = models.ForeignKey(Person, models.PROTECT, related_name="sub_budgets_owned") class Meta: ordering = ["id"] unique_together = (("budget_owner", "sub_budget_owner"),) verbose_name = "Budget Owner" # Title on the maint page for this table verbose_name_plural = "Budget Owners" # Title for the navbar navigation def __str__(self): return str(self.budget_owner) + " - " + str(self.sub_budget_owner) class Combination(models.Model): id = models.AutoField(primary_key=True) subsidiary = models.ForeignKey(Subsidiary, verbose_name="Subsidiary", null=True, blank=True, on_delete=models.CASCADE,) department = models.ForeignKey(Department, verbose_name="Department", on_delete=models.CASCADE,) sub_budget = models.ForeignKey(SubBudget, verbose_name="Sub Budget", on_delete=models.CASCADE,) budget_owner = models.ForeignKey(SubBudgetOwner, verbose_name="Budget Owner & Sub Budget Owner", null=True, blank=True, on_delete=models.CASCADE,) def __str__(self): return (f"{self.subsidiary} {self.department} {self.sub_budget} {self.budget_owner}") class Meta: ordering = ["id"] My views.py class CombinationListView(LoginRequiredMixin, ListView): model = Combination template_name = "budget/combination_list.html" What can I do to improve it? TNX guy -
Django ORM , Query optimization
I am building e-commerce website with Django and wanted to optimize my database , but stuck with the following problem: I have Order model which has property attributes, like : overallamount and overallprice .So they make many similar queries to the database , is there any way to optimize it . models.py class Product(models.Model): name = models.CharField(max_length=15) price = models.IntegerField() digital = models.BooleanField(default=False) image = models.ImageField(upload_to='store/', null=True, blank=True) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, default=None, null=True, on_delete=models.SET_NULL) completed = models.BooleanField(default=False) date_ordered = models.DateField(auto_now=True) @property def overallprice(self): return sum([item.totalprice for item in self.orderitem_set.all()]) @property def overallamount(self): return sum([item.quantity for item in self.orderitem_set.all()]) def __str__(self): return str(self.customer) class OrderItem(models.Model): order = models.ForeignKey(Order, null=True, on_delete=models.SET_NULL) date_ordered = models.DateField(auto_now=True) product = models.ForeignKey(Product, default=None, null=True, on_delete=models.SET_NULL) quantity = models.IntegerField(default=0) views.py @login_required(login_url='login') def cart(request): order, created = Order.objects.get_or_create(customer=request.user.id) orderitem = OrderItem.objects.filter(order=order).select_related('product') return render(request, 'cart.html', {'orderitem': orderitem, 'order': order}) and the template/cart.html {%extends 'layout.html'%} {% load static %} {%block content%} <div class="box-element"> <a class="btn btn-outline-dark" href="{% url 'menu' %}">&#x2190; Continue Shopping</a> <br> <br> <table class="table"> <tr> <th><h5>Items:<strong>{{order.overallamount}}</strong></h5></th> <th><h5>Total:<strong>${{order.overallprice}}</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="{% url 'checkout' %}">Checkout</a> </th> </tr> </table> </div> <div class="box-element"> <div class="cart-row"> <div style="flex:2"></div> <div style="flex:2"><strong>Item</strong></div> <div style="flex:1"><strong>Price</strong></div> <div style="flex:1"><strong>Quantity</strong></div> … -
Not able to migrate for my custom user model
Hey guys I am having this problem with my django migrations when I am trying to create a custom user model for my website So what is happening is when I run migrations it throws an error on me saying:- ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'user.newuser', but app 'user' doesn't provide model 'newuser'. The field user.UserInfo.user was declared with a lazy reference to 'user.newuser', but app 'user' doesn't provide model 'newuser'. I tried my best to try and debug it but it nothing is working i also did follow a answer on stack overflow but that also did not work I have implemented everything that is needed so yea the rest is the rest, and here is my code along with the migrations file models:- class CustomAccountManager(BaseUserManager): def create_user(self, first_name, last_name, phone_number, email, password, **other_fields): if not email: raise ValueError(_('You must provie an email address')) if not first_name: raise ValueError(_('You must provide a first name')) if not last_name: raise ValueError(_('You must provide a last name')) email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, phone_number=phone_number, **other_fields) user.set_password(password) return user def create_superuser(self, email, first_name, last_name, phone_number, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') … -
How to manage devices on docker-compose automatically?
Here is the docker-compose.yml to map local USB cameras to container on a django web application. In this case, it works if 10 cameras are connected to the local PC, but cause errors if I take out any of them because the container can not map some of the cameras listed up. So for now, I need to comment out them depending on the number of cameras connected to the local. Is there any solutions for this case so that I do not have to comment out like I mentioned above? version: '3' web: build: . devices: # Here is the problem!!! - '/dev/video0:/dev/video0:mwr' - '/dev/video1:/dev/video1:mwr' - '/dev/video2:/dev/video2:mwr' - '/dev/video3:/dev/video3:mwr' - '/dev/video4:/dev/video4:mwr' - '/dev/video5:/dev/video5:mwr' - '/dev/video6:/dev/video6:mwr' - '/dev/video7:/dev/video7:mwr' - '/dev/video8:/dev/video8:mwr' - '/dev/video9:/dev/video9:mwr' ports: - '8000:8000' volumes: - '.:/code' tty: true stdin_open: true command: > bash -c 'python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000' Thank you in advance for my very first question in stack overflow! -
Why doesn’t Heroku add or remove database tables after initial launch for django app
So I punched my Django app on heroku and every thing has been going fine for about 3 weeks now. Now I want to update my models and add more fields but when I do so, it doesn’t seem to update the database. I run the following: heroku run python manage.pu makemigrations and the same for migrate. Every run through fine but the migrations doesn’t really go through although it says the fields have been altered. Anyone know how to update models for django app on heroku after initial launch?