Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I group products based on their age in django?
I have a django ecommerce site where I have products for 3 age groups. i.e. Child, Adult, Senior. The issue is one product can be on more than one age group. How can I arrange that with the product model? I tried using booleans and use select option but when I change pages it gives "keywords must be strings" error because of the filter. Here is my code: Templates <li class="age"><Form action="{% url 'get_products' %}" method="get"> <select style="text-transform: uppercase;" name="age_group" onchange="submit()"> <option value="" selected disabled>Gifts by Age</option> <option value="infant">Infant</option> <option value="toddler">Toddler</option> <option value="child">Child</option> <option value="teen">Teenager</option> <option value="adult">Adult</option> </select> </Form></li> Views def get_products(request): # getting the age group you passed via form age_group = request.GET.get("age_group") products = Product.objects.filter(**{age_group: True}) paginator = Paginator(products, 1) page_number = request.GET.get('page') products = paginator.get_page(page_number) context = {'products': products } return render(request, "age.html", context) -
Django admin conditional inline
I have a question model which can have different types like SINGLE_ANSWER, MULTIPLE_ANSWER , CODE , ... MODELS.PY : class Question(BaseModel): class QuestionType(models.IntegerChoices): SINGLE_ANSWER = 1 MULTIPLE_ANSWER = 2 ESSAY = 3 CODE = 4 VIDEO = 5 UPLOAD = 6 class DifficultyLevel(models.IntegerChoices): EASY = 1 MEDIUM = 2 HARD = 3 question_text = models.TextField() type = models.IntegerField(choices=QuestionType.choices) level = models.IntegerField(default=1, choices=DifficultyLevel.choices) def get_absolute_url(self): self.get_type_display() def __str__(self): return truncatewords(self.question_text, 7) ADMIN : @admin.register(Question) class QuestionAdmin(admin.ModelAdmin): inlines = [ OptionInline, CodeInline, TestCaseInline, ] By this code all inlines(OptionInline,CodeInline,TestCaseInline) will be shown in admin page like the picture bellow: question admin panel pic but i want the inlines appear whenever the user choose the type, for example the OptionInline shows when user choose multiple_answer or CodeInline shows when user choose CODE from type dropdownlist what i did for this purpose is overriding the get_inlines method ADMIN : def get_inlines(self, request, obj: Question): if obj: if obj.type in [Question.QuestionType.SINGLE_ANSWER, Question.QuestionType.MULTIPLE_ANSWER]: return [OptionInline] elif obj.type == Question.QuestionType.CODE: return [CodeInline, TestCaseInline] else: return [] else: return [] but i have a problem when i want to change the type after saving the question this error appears : (Hidden field INITIAL_FORMS) This field is required. ManagementForm … -
How can I make a Django application connect to a minio server when both are behind an nginx proxy and inside individual docker containers?
Goal Access minio server via subdomain from Django server in docker environment (both minio server and Django server are behind nginx proxy) Expected result: Django can access minio server using the subdomain specified in nginx. Problem Django service can't connect properly. Docker logs: api | Traceback (most recent call last): api | File "manage.py", line 22, in <module> api | main() api | File "manage.py", line 18, in main api | execute_from_command_line(sys.argv) api | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line api | utility.execute() api | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 386, in execute api | settings.INSTALLED_APPS api | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ api | self._setup(name) api | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup api | self._wrapped = Settings(settings_module) api | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ api | mod = importlib.import_module(self.SETTINGS_MODULE) api | File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module api | return _bootstrap._gcd_import(name[level:], package, level) api | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import api | File "<frozen importlib._bootstrap>", line 991, in _find_and_load api | File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked api | File "<frozen importlib._bootstrap>", line 671, in _load_unlocked api | File "<frozen importlib._bootstrap_external>", line 843, in exec_module api | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed api … -
Django cannot find path although it is not hardcoded
The background of this problem is that I am deploying a Django project on production server. Upon testing on production server I get the below error from my asgi.log 2022-07-24 07:03:12,962 ERROR Internal Server Error: /paymentWebhook Traceback (most recent call last): File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/asgiref/sync.py", line 482, in thread_handler raise exc_info[1] File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/asgiref/sync.py", line 444, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/lib/python3.10/asyncio/tasks.py", line 408, in wait_for return await fut File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/asgiref/current_thread_executor.py", line 22, in run result = self.fn(*self.args, **self.kwargs) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/asgiref/sync.py", line 486, in thread_handler return func(*args, **kwargs) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/django/views/decorators/http.py", line 40, in inner return func(request, *args, **kwargs) File "/home/jianwu/DimsumBox_website/dimsumbox/./customer/views.py", line 124, in payment_webhook paymentHandle = handlePostPayment(request = request) File "/home/jianwu/DimsumBox_website/dimsumbox/./customer/views.py", line 165, in handlePostPayment pdfReceipt = webshopUtils.generateReceipt(session_id = customer.session_id) File "/home/jianwu/DimsumBox_website/dimsumbox/./dimsumbox/Modules/webshopUtils.py", line 484, in generateReceipt return pdf.pdf.output() File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 2929, in output self.close() File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 672, in close self._enddoc() # close document File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 3672, in _enddoc self._putresources() # trace_size is performed inside File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 3565, in _putresources self._putfonts() File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 3205, in … -
How to deploy django project on aws ec2 using bitbucket ci/cd?
I am looking for any documents or step by step tutorial on how to deploy Django project on AWS ec2 using bitbucket ci/cd?. I have gone through many docs but unable to get the proper workflow on deploying the project. I'm learning ci/cd pipelines. Thanks!! -
Django: unable to loaddata, UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
I'm new to Django, I'm encounter an error during loaddata. I had completely dump my data in seed_data.json, but when I attempt to loaddata, it came out UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte At first I dump my data into python manage.py dumpdata > seed_data.json Then I removed db.sqlite3 rm db.sqlite3 Make migrations python manage.py migrate Now I loaddata seed_data.json, it came out error python manage.py loaddata seed_data.json error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Seed_data.json [{"model": "auth.permission", "pk": 1, "fields": {"name": "Can add log entry", "content_type": 1, "codename": "add_logentry"}}, {"model": "auth.permission", "pk": 2, "fields": {"name": "Can change log entry", "content_type": 1, "codename": "change_logentry"}}, {"model": "auth.permission", "pk": 3, "fields": {"name": "Can delete log entry", "content_type": 1, "codename": "delete_logentry"}}, {"model": "auth.permission", "pk": 4, "fields": {"name": "Can view log entry", "content_type": 1, "codename": "view_logentry"}}, {"model": "auth.permission", "pk": 5, "fields": {"name": "Can add permission", "content_type": 2, "codename": "add_permission"}}, {"model": "auth.permission", "pk": 6, "fields": {"name": "Can change permission", "content_type": 2, "codename": "change_permission"}}, {"model": "auth.permission", "pk": 7, "fields": {"name": "Can delete permission", "content_type": 2, "codename": "delete_permission"}}, {"model": "auth.permission", "pk": 8, "fields": {"name": "Can view permission", "content_type": 2, "codename": "view_permission"}}, {"model": "auth.permission", … -
How do I add Page in this my code? django
I want to add paging function in my code. This socre_by function line up by score. But A lot of Movie and TV line up. I want to page Movie and TV. How can I add paging functionality while preserving the functionality of this code? def Score_by(request): query_min = 0 query_max = 10 if request.GET.get('min') and request.GET.get('max'): query_min = request.GET.get('min') query_max = request.GET.get('max') movies = Movie.objects.order_by('-stars') movie_list= [] Ranking = 1 if movies.exists(): for obj in movies: if (float(query_min) <= float(obj.average_stars())) and (float(query_max) >= float(obj.average_stars())): data = requests.get(f"https://api.themoviedb.org/3/movie/{obj.id}?api_key={TMDB_API_KEY}&language=en-US") data_movie = data.json() data_movie['score'] = obj.average_stars() data_movie['Ranking'] = Ranking movie_list.append(data_movie) Ranking += 1 # print(movie_list) tv = TV.objects.order_by('-stars') tv_list = [] Ranking = 1 if tv.exists(): for obj in tv: if (float(query_min) <= float(obj.average_stars())) and (float(query_max) >= float(obj.average_stars())): data = requests.get(f"https://api.themoviedb.org/3/tv/{obj.id}?api_key={TMDB_API_KEY}&language=en-US") data_tv = data.json() data_tv['score'] = obj.stars data_movie['Ranking'] = Ranking tv_list.append(data_tv) Ranking += 1 context = { 'movie':movie_list, 'tv' :tv_list } return render(request, 'Movie/score_by.html', context) -
Why my custom script processing data just fine on local development Django server but not on Digital Ocean App?
Does anyone know why when I upload a CSV file locally to the Django development server, my code does work as plan as in processing the CSV file and adding data to the database correctly, but when I try the same thing with the production server on Digital Ocean using App service - the CSV file just uploaded without having getting processed? I notice this because no new product is being added when uploading the CSV file to the production server on Digital Ocean. By the way, the local development server is also using S3 storage - so the same file got uploaded to Amazon S3 all the same - but the code processes the file in the development server but not on the production server - the development server is on my laptop. The production server is on Digital Ocean's App. I did something like this in the code: from django.core.files.storage import default_storage def upload_csvs(request): current_page_bread_crumb_title = 'upload csv' form = CsvsModelForm(request.POST or None, request.FILES or None) random_category = None if form.is_valid(): form.save() # reset form after save form = CsvsModelForm() # Only getting csv file that isn't activated or being used already. get_csv_data = Csvs.objects.filter(activated=False).order_by('-id').first() with default_storage.open(get_csv_data.file_name.name, mode='r') … -
How to query a dropdown in a Django ModelForm field based on current logged in user
I have a django model form were a user can submit their budget information. One of the fields in the form is a Category which is a foreign key from a Category Model. Unfortunately all users can see each other category's. How can I query the Category Field in the model form to only show logged in user. This is my Model.py from django.contrib.auth.models import User class Category(models.Model): user = models.ForeignKey(User,on_delete=models.SET_NULL,null=True,blank =True) TYPE = ( ('Income', 'Income'), ('Expense', 'Expense'),) category_feild = models.CharField(max_length = 100,unique = True) income_or_expense = models.CharField(default =" ",max_length=200, choices=TYPE) def __str__(self): return self.category_feild class Budget(models.Model): category = models.ForeignKey(Category,on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=False) budget_amt = models.FloatField(default= 0) comments = models.CharField(max_length = 140,default="") def __str__(self): return self.category.category_feild +' - ' + str(self.date.strftime('%b %Y')) This is my forms.py class budget_form(ModelForm): class Meta: model = Budget fields = ['category','date','budget_amt','comments' ] widgets = { 'category' : forms.Select(attrs={'class':'form-control'}), 'date' : forms.DateInput(attrs={'class':'form-control'}), 'budget_amt' : forms.NumberInput(attrs={'class':'form-control'}), 'comments' : forms.TextInput(attrs={'class':'form-control'}), } This is the view.py where I have attempted a query to filter for category of logged in users. def add_budget(request): b_form = budget_form if request.method == 'POST' and "budgetForminfo" in request.POST: budget_form.fields["category"].queryset= Category.objects.filter(user=request.user) b_form = budget_form(request.POST or None) if b_form.is_valid(): b_form.save() b_form = budget_form() return redirect('add_budget') … -
Connect Django to SQL database in Google Cloud's Compute Engine
My Django app has been working successfully using Google's App Engine standard environment. However I need to use Compute Engine for more power. I am testing a single VM instance running the app, however it has issues connecting to the POSTGRES database. The compute engine service account has all the same permissions as the app engine service account. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': '/cloudsql/myproject:us-central1:mypostgresname', 'NAME': 'mydatabasename', 'USER': 'myusername', 'PASSWORD': 'mypassword', } } -
How to replace empty values from api query to a number
I have a piece of code that pulls api data from an external website. The issue I am having is that during the pull it also saves the data to the database if it does not exist. Well some of the values from the json data I pull are empty and the database is expecting an integer when saving. How do I convert he json data empty strings to default 0? The Error ValueError at / Field 'he_displaced_threshold_ft' expected a number but got ''. services.py def get_runways(): params = { "apiToken": "SECRET", } api_base = "https://airportdb.io/api/v1/airport/KMIA" api_result = requests.get(api_base, params) api_response = api_result.json() for runway in api_response["runways"]: runway_data, created = Runway.objects.update_or_create( airport_ident=Airport.objects.get(ident=runway["airport_ident"]), length_ft=runway["length_ft"], width_ft=runway["width_ft"], surface=runway["surface"], lighted=runway["lighted"], closed=runway["closed"], le_ident=runway["le_ident"], le_latitude_deg=runway["le_latitude_deg"], le_longitude_deg=runway["le_longitude_deg"], le_elevation_ft=runway["le_elevation_ft"], le_heading_degT=runway["le_heading_degT"], le_displaced_threshold_ft=runway["le_displaced_threshold_ft"], he_ident=runway["he_ident"], he_latitude_deg=runway["he_latitude_deg"], he_longitude_deg=runway["he_longitude_deg"], he_elevation_ft=runway["he_elevation_ft"], he_heading_degT=runway["he_heading_degT"], he_displaced_threshold_ft=runway["he_displaced_threshold_ft"], ) runway_data.save() return runway models.py class Runway(models.Model): airport_ident = models.ForeignKey(Airport, on_delete=models.CASCADE) length_ft = models.IntegerField(default=None, blank=True, null=True) width_ft = models.IntegerField(default=None, blank=True, null=True) surface = models.CharField(max_length=50, blank=True, null=True) lighted = models.IntegerField(default=None, blank=True, null=True) closed = models.PositiveBigIntegerField(default=None, blank=True, null=True) le_ident = models.CharField(max_length=5, blank=True, null=True) le_latitude_deg = models.FloatField(default=None, blank=True, null=True) le_longitude_deg = models.FloatField(default=None, blank=True, null=True) le_elevation_ft = models.IntegerField(default=None, blank=True, null=True) le_heading_degT = models.FloatField(default=None, blank=True, null=True) le_displaced_threshold_ft = models.IntegerField(blank=True, null=True) he_ident = models.CharField(max_length=5, blank=True, null=True) he_latitude_deg … -
Get data belongs to a field of model in select_related to a list and create a dataframe
I'm trying to query two related tables and create a pandas dataframe then use it for rule mining. The dataframe should look like this, order products ---------------- 1 ['product1', 'product2'] 2 ['product1', 'product3', 'product10'] ... My models, class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ManyToManyField(Product, through='OrderedProduct', related_name='orders') class OrderedProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) quantity = models.IntegerField(default=1) class Product(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) I've done the dataframe creating part as follows in views, and it works but needs preprocessing to get end result and feels it's inefficient for a larger dataset. orders = OrderedProduct.objects.all().values('order__id', 'product__name') df = pd.DataFrame.from_records(orders) df = df.groupby(['order__id'])['product__name'].apply(list).to_list() So, my question is 'Is there a more direct and efficient approach to do this?'. Any advice is highly appreciated. -
How to get data of last 6 months by using date field - django
I have a model as below, class Visits(models.Model): visit_date = models.DateField(blank=False, null=False) fees = models.DecimalField(null=False, blank=False, max_digits=10, decimal_places=2) I want to get data for last six months (including current month) total fees month wise Example: { July : 750, June : 800, May : 500, April : 200, March: 450, Febraury: 310 } How to get done this by having date field.? -
Python, JSignature, and ReportLab
I'm looking to write a signature to PDF. I'm using JSignature and Reportlab. My code works successfully for writing the data to a file and the database. I just cannot figure out how to write the signature to the canvas. Has anyone passed the signature into the canvas successfully? Thank you in advance. Here's a look at my code: pdf.py import io from django.core.files.base import ContentFile from reportlab.lib.units import inch from reportlab.pdfgen import canvas from reportlab.lib.utils import ImageReader def create_pdf(parent): # create a file-like buffer to receive PDF data buffer = io.BytesIO() # create the pdf object, using the buffer as its "file" p = canvas.Canvas(buffer) # create text textobject = p.beginText() # start text at top left of page textobject.setTextOrigin(inch, 11*inch) # set font and size textobject.setFont("Helvetica-Bold", 18) textobject.textLine("My Document") textobject.textLine("") # write page 1 textobject.setFont("Helvetica", 12) p_name = f'Name: {participant.first_name} {participant.middle_initial} {participant.last_name}' textobject.textLine(p_name) sig = f'Signature:' textobject.textLine(sig) ----insert signature here---- # write created text to canvas p.drawText(textobject) # close the pdf canvas p.showPage() p.save() buffer.seek(0) # get content of buffer pdf_data = buffer.getvalue() # save to django File object file_data = ContentFile(pdf_data) # name the file file_data.name = f'{participant.last_name}.pdf' # participant.pdf = file_data participant.save() Model: class Participant(models.Model): first_name … -
Django - object has no attribute 'object' when injecting POST form data
Goal I'm trying to inject the "Send BCC" Job Site email addresses/objects into the form as the initial default value. The difficulty seems to be how it's interpreting super().get_context_data(**kwargs) and the view somehow is missing the object() it's looking for. I can't seem to figure out what's wrong, despite checking for duplicate names, defining self.object inside of post and get. GitHub: https://github.com/varlenthegray/wcadmin/blob/dev/communication/views.py#L21 Referenced the following StackOverflows in attempts to find the solution: 'CheckoutView' object has no attribute 'object' Django: object has no attribute 'object' Django Test: type object has no attribute 'objects' Django: AttributeError: "Object has no attribute" Error Environment: Request Method: POST Request URL: http://localhost:3003/email/compose_email Django Version: 4.0.6 Python Version: 3.8.10 Installed Applications: ['customer', 'equipment', 'service', 'supplier', 'users', 'qb', 'communication', 'main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'dateutil', 'widget_tweaks', 'intuitlib', 'quickbooks', 'rest_framework', 'rest_framework_datatables', 'markdownify'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/wcadev/public_html/lib/python/Django-4.0.6-py3.8.egg/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/wcadev/public_html/lib/python/Django-4.0.6-py3.8.egg/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/wcadev/public_html/lib/python/Django-4.0.6-py3.8.egg/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "/home/wcadev/public_html/lib/python/Django-4.0.6-py3.8.egg/django/contrib/auth/mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) File "/home/wcadev/public_html/lib/python/Django-4.0.6-py3.8.egg/django/views/generic/base.py", line 119, in dispatch return handler(request, *args, **kwargs) … -
Django&Echart Uncaught SyntaxError: missing ) after argument list
I'm learning to use echart to draw in Django's template, I'm trying to pass my database data to the template via the view function and then store the data into an array for drawing via a for loop, but I'm finding that my time field can't be stored into the array via a for loop because it loses the quotes error mycode var seris_data = []; var xAxis_data = []; {% for data in activity_detail %} seris_data.push({{ data.heart_rate }}) xAxis_data.push({{ data.timestamp }}) {% endfor %} -
Docker not showing the port number for running container
Hi I am running a web app in Docker but I do not have the container port showing on docker ps -a ➜ pansible git:(master) ✗ docker container ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ead78f0f8a8c ask_webapp "sh /usr/src/app/sp_…" 20 seconds ago Restarting (0) 2 seconds ago ask_dashboard_web 4e9ef2611f7f sp_ask_dashboard_celery_worker "sh /usr/src/app/sp_…" 20 seconds ago Exited (0) 18 seconds ago pansible_celery_worker_1 ec72e473ef8d sp_ask_dashboard_celery_flower "sh /usr/src/app/sp_…" 20 seconds ago Exited (0) 18 seconds ago pansible_flower_1 31fc39e60a34 sp_ask_dashboard_celery_beat "sh /usr/src/app/sp_…" 20 seconds ago Exited (0) 18 seconds ago pansible_celery_beat_1 69c87984ebfc postgres:14.0-alpine "docker-entrypoint.s…" 21 seconds ago Up 19 seconds 5432/tcp pansible_db_1 f536a781e2ed redis:6-alpine "docker-entrypoint.s…" 21 seconds ago Up 19 seconds 6379/tcp pansible_redis_1 f92d2f110227 ask_webapp "sh /usr/src/app/sp_…" 5 minutes ago Exited (0) 5 minutes ago pansible_web_run_be8a8e63e09d I am looking for the ask_webbapp and I don't see the port. In docker-compose.yml I specified port 8000 version: '3.3' services: db: image: postgres:14.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_PASSWORD=postgres networks: - djangonetwork redis: image: redis:6-alpine web: container_name: ask_dashboard_web build: context: . dockerfile: ./sp_dashboard/DockerfileBuild image: ask_webapp restart: always command: > sh -c "python sp_dashboard/manage.py runserver 0.0.0.0:8000" volumes: - .:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev networks: - djangonetwork environment: - lh3_salt=jasdjfst - lh3_scheme=https - POSTGRES_PASSWORD=postgres … -
Urlpattern regular expression not working
So i'm trying to make url like so re_path(r'^product_list/(?P<category_slug>[\w-]+)/(?:(?P<filters>[\w~@=]+)?)$', views.ProductListView.as_view(), name='filtered_product_list'), and at this point it works with things like: /product_list/sdasdadsad231/bruh=1~3~10@nobruh=1~4 bruh=1~3~10@nobruh=1~4 - those are filters but later i want to implement search by word functionality so i want it recognize things like /product_list/sdasdadsad231/?filters=bruh-1~3~10&nobruh-1~4&search_for=athing /product_list/sdasdadsad231/?filters=bruh-1~3~10&nobruh-1~4 /product_list/sdasdadsad231/?search_for=athing /product_list/sdasdadsad231/ so in different situations it will get filters and/or search_for or nothing at all -
How to fix "django.core.exceptions.FieldError: Unknown field(s) (username) specified"
I have an app that uses a custom User model called MyUser, a custom User manager, and a custom UserCreationForm. I'm trying to add the rest of the fields from the MyUser model to the UserCreationForm, but I keep getting the error: django.core.exceptions.FieldError: Unknown field(s) (username) specified for MyUser. What is the proper way to set a custom UserCreationForm? Why am I getting this error? Here's my code. Models.py from django.db import models from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin import uuid class UserManager(BaseUserManager): def create_user(self, fname, lname, email, phone, password=None): if not email: raise ValueError('You must enter an email address') user = self.model( fname=fname, lname=lname, email=self.normalize_email(email), password=password, is_superuser=False ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): user=self.create_user(self, fname, lname, email, phone, password) user.staff=True user.save(using=self._db) return user def create_superuser(self, email, password): user=self.create_user(self, fname, lname, email, phone, password) user.staff=True user.admin=True user.is_superuser=True user.save(using=self._db) return user class MyUser(AbstractBaseUser, PermissionsMixin): fname=models.CharField(max_length=100) lname=models.CharField(max_length=100) email=models.EmailField(max_length=200, unique=True) phone=models.CharField(max_length=15) password=models.CharField(max_length=200) user_id=models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4) is_active=models.BooleanField(default=True) staff=models.BooleanField(default=False) admin=models.BooleanField(default=False) USERNAME_FIELD='email' required_fields=['fname', 'lname', 'email', 'password'] @property def is_staff(self): #is the user staff? return self.staff @property def is_admin(self): #is the user an admin? return self.admin objects = UserManager() Forms.py from django import forms from django.forms import ModelForm from django.contrib.auth.forms import … -
Django - How can I "upgrate" user type?
I have two models, Buyer and Merchant with the default user type after the account creation being Buyer. # Abstract User class User(AbstractUser): is_buyer = models.BooleanField(default=False) is_merchant = models.BooleanField(default=False) date_created = models.DateTimeField(default=timezone.now) # Buyer class Buyer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) pin = models.CharField(max_length=6, blank=True) items = models.ManyToManyField(Product, blank=True) # items = models.ManyToManyField(Product, blank=True) def __str__(self): return f'{self.user.username}' # Merchant class Merchant(models.Model): # items user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) pgp = models.CharField(max_length=150, blank=True) # image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username}' And I have a become-a-merchant.html template in which I would like to make the Buyer be able to become a Merchant after checking a checkbox and pressing a button. {% extends 'base.html' %} {% block content %} <input type="checkbox" name="checkbox" value="check"> <label for="checkbox">Become a merchant.</label> <br><br> <button type="submit">Upgrade</button> {% endblock %} I don't know what to type of view to use or how to do a form that upgrades my user type. -
CSS and JAVASCRIPT files don't work in my django project
I did not really try much because I am a beginner, but I searched and did not find a solution to my problem. I did everything as required, I created the static file and called it in the "template/base.html" but only the HTML files worked and static files including CSS and JAVASCRIPT did not work -
Django Rest Framework Serializer - How to return value of data in response?
I am using dj-rest-auth and docs say I can serialize extra fields with the RegisterSerializer My serializer: from dj_rest_auth.registration.serializers import RegisterSerializer class CustomRegistrationSerializer(RegisterSerializer): user_id = serializers.SerializerMethodField('get_user_id') def get_user_id(self, obj): o = obj['username'] user_id = User.objects.get(username=o).id print(user_id) return Response(user_id) My settings: REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'users.serializers.CustomRegistrationSerializer' } I am able to print the id in my console, but in the api response, it's only returning the token and not the id Appreciate any help! Don't know what I am doing wrong. -
ERROR: Could not install requirements.txt packages due to an OSError?
I am getting errors please tell me what is wrong with this, I am not able to find a solution anywhere! I am working on one project but when other members try with install -r rquirements.txt they get this error! please tell what should be the action to handle or remove this error? -
django-'str' object has no attribute 'ppoi'
i install django-versatileImageField package and it's working very well but when i want change model or add new model in admin it show this error 'str' object has no attribute 'ppoi'. 'str' object has no attribute 'ppoi' -
hwo to fetch upper data and then delete in one action in Django?
I just want to fetch the upper data only and then delete it in one action. I tried this code: `def Data(request): data = Plan.objects.get(id = 1) data.delete() context = {'data':data} return render(request,'data.html',context)` But didn't work. see Database column