Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't load static image in django when using a loop
I cant get an image to load in django when i use a for loop, the image will load if i specify the path for each file. Works: when I try to use a loop it won't load the images. view.py: operators = [] directory = os.path.join(os.path.join(os.path.join(os.path.join(settings.BASE_DIR) ,'static'),'images'),'operators') for file in os.listdir(directory): if file.endswith(".png") or file.endswith(".jpg"): operators.append(file) then i try to return image using context. html file: {% if operators %} There are {{ operators|length }} records: {% for operator in operators %} <div class="media"> <img src="{{operator}}" class="align-self-center mr-3" alt="..."> </div> {{operator}} {% endfor %} {% else %} There are no records in the system {% endif %} It would be amazing if someone had an idea on how to fix my code. settings.py: STATIC_URL = '/static/' # Pointing django to the static file location. STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) -
Is there a way to add an aggregated field to an annotated Queryset
I have a queryset with two objects in it like below: fake = queryset({'id':1, 'price': 10, 'relation_field_id':5}, {'id':1, 'price': 15, 'relation_field_id':5}) All relation_field_ids have number 5. I want to have a Queryset or Dic that aggregated with sum of the price field and just one of the relation_field_id in it like: queryset({'total_price': 25, 'relation_field_id':5 }) I would be glad anyone answer to this question. Thank you. -
Dockerized django app don't run in the browser
I'm getting a problem when I run my docker image what I built with the next Dockerfile: FROM ubuntu:18.04 RUN apt update RUN apt install -y python3 python3-pip RUN mkdir /opt/app COPY Ski4All/ /opt/app/ COPY requirements.txt /opt/app/ RUN pip3 install -r /opt/app/requirements.txt COPY docker-entrypoint.sh / EXPOSE 8000 ENTRYPOINT /usr/bin/python3 /opt/app/manage.py runserver 0.0.0.0:8000 With the commando docker run -p 8000:8000 -it --rm skiapi Everything run Ok and I receive the message about the server is running at 127.0.0.1:8000 but when I try to access via browser it says that the connection has been restarted and I can't access to the web. Any tip? Thanks -
How do I universally connect to Redis both in Docker and PyTest?
One of the Django views in code I test connects to Redis using a redis.Redis class. red = redis.Redis(host='redis-map', port=6379) Obviously, this method isn't good when testing because it uses the same DB as when opening it outside of testing. I found a library called pytest-redis and replaced all the redis.Redis constructors with calling a function I created: import sys, redis from pytest_redis import factories def create_redis(): if not 'pytest' in sys.modules: return redis.Redis(host='redis-map', port=6379) else: return factories.redisdb('redis_proc')() However, when I run the test, it returns this error: web_1 | Failed: Fixture "redisdb_factory" called directly. Fixtures are not meant to be called directly, web_1 | but are created automatically when test functions request them as parameters. web_1 | See https://docs.pytest.org/en/latest/fixture.html for more information about fixtures, and web_1 | https://docs.pytest.org/en/latest/deprecations.html#calling-fixtures-directly about how to update your code. I don't want to rewrite what is pretty much all of my code - lots of code in my WebSocket consumer in Django Channels also uses Redis. What should I do? -
How dynamically define and create custom "through" model with specific fields and structure for all custom manytomanyfield
I have a model with a lot of m2m fields: class Model1(models.Model): useful_data = models.TextField(null=True) class Model2(models.Model): useful_data = models.TextField(null=True) class Entity(models.Model): field1 = CustomManyToManyField('entities.Model1') field2 = CustomManyToManyField('entities.Model2') field3 = CustomManyToManyField('entities.Model2') ... I want dynamically created model "through" for all CustomManyToManyField with specific fields. So for every CustomManyToManyField I need to dynamically create new model with this structure. For example for field1 field this model will be created: class CustomThroughModel(models.Model): entity = models.ForeignKey('entities.Organization') model1 = models.ForeignKey('entities.Model1') data_source = models.CharField() updated_at = models.DateTimeField(auto_now=True) deleted_at = models.DateTimeField(null=True) created_at = models.DateTimeField(auto_now_add=True) I don't want to copy paste similar models for every manytomanyfields -
How to convert this category_detail function-based view to a CBV (DetailView)
I have this function-based view doing what I need it to do - get the list of all Posts filed under s specific Category and reach that list by going to example.com/economics/ (where economics is the slug od that specific Category). There I would find the list of all my posts filed under Economics category and create links so I can click on them and go to a single post page. Currently, my FBV looks like this: def category_detail(request, category_detail_slug=None): categories = Category.objects.all() #Show only published posts posts = Post.objects.filter(status__exact='1') if category_detail_slug: category = get_object_or_404(Category, slug=category_detail_slug) posts = posts.filter(category=category) return render(request, 'blog/category/single.html', {'category_detail_slug': category_detail_slug, 'category': category, 'categories': categories, 'posts': posts}) I started creating my CBV like this: class CategoryDetailView(DetailView): model = Category template_name = 'blog/category/single.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context I know I need to pass some context, but somehow this keeps failing me. My URL for this is defined as such: path('<slug:category_detail_slug>/', views.CategoryDetailView.as_view(), name="single_category") -
How to embed Bokeh(2.x) server in Django(2.x) application/view
I have been beating the problem for a very long time and I can 't find a solution. In general, need to embed bokeh server in Django app. There are a lot of examples on flask in the documentation, but there are no examples on django from the beginning to the end. The situation is next: I have a form of dropdown selection with strings as option values. For example MSFT, TSLA, GOOG, OLOLO. I select the option from dropdown form, then redirecting to select/{str: option} page. In the views.py that processes the page I want to embed bokeh server. I have another file visualization.py with class that contains all settings for plots. #visualization.py import pandas as pd from bokeh.io import curdoc from bokeh.models import ColumnDataSource, Legend, NumeralTickFormatter from bokeh.plotting import figure doc = curdoc() class BokehPlot: def __init__(self, data): self.data = data self.df = self.collect_dataframe() self.tools = 'pan,crosshair,wheel_zoom,reset' self.plot_width = 1000 self.width = 0.5 self.xaxis_dt_format = '%d %b %Y' if self.df['datetime'][0].hour > 0: self.xaxis_dt_format = '%d %b %Y %H:%M' self.major_x_axis = {i: date.strftime(self.xaxis_dt_format) for i, date in enumerate(pd.to_datetime(self.df["datetime"]))} self.inc_color = '#15aaba' self.dec_color = '#7F7F7F' def collect_dataframe(self): if self.data is None: raise Exception df = pd.DataFrame(self.data) df['datetime'] = pd.to_datetime(df.begin, format='%Y-%m-%d … -
how to call scrapy spider from view.py of my django application?
My aim is to check wether a particular javascript is present in the lis of URLs that the user enters in the front end of my application. I want to take that url and pass it to my spider and want to return two list. One which contains list of urls in which the javascript is present and the other list which doesn’t contain javascript. I want to display these lists back onto the html of the my application. When i run my spider from the terminal using command i get the desired output but want the front end of it. My django application view.py file from concurrent.futures import process from django.shortcuts import render from scrape.scrape.spiders import ScrapeSpider from scrapy.crawler import CrawlerProcess # Create your views here. def base(request): return render(request, "base.html") def home(request): search = request.POST.get("search") process.crawl(ScrapeSpider) data = { "search": search } return render(request, "scraping/home.html", data) My spider file looks like this. import scrapy class ScrapeSpider(scrapy.Spider): name = "scrape" allowed_domains = ["smolnarod.ru"] start_urls = [ "https://fribbla.com/en/20-dog-breeds-you-might-want-to-reconsider-getting/", ] def parse(self, response): data = response.xpath("//script[contains(., 'xyz')]").extract_first(default="not-found") if data == "not-found": print("Not Exists") else: print("Exists") The directory in which my spider is present scrape/scrape/spider/scrape.py While running the application i am facing … -
How to loop a function in python using a class?
I'm currently working on minesweeper using python and I have a function that goes through the buttons surrounding the clicked button and shows them if the clicked button's value is 0. My problem is, what if there is a 0 in the surrounding buttons. How do I apply the function then? class Gumb: def __init__(self, ID, broj): self.id = ID self.rednibroj = int(self.id[1])*10 +int(self.id[3]) self.r = self.rednibroj//10 self.s = self.rednibroj % 10 self.b = broj return def __repr__(self): return f'(ID:{self.id} \n Vrijednost: {self.b})' def postavljanje(): bombe=sample(range(0, 81), 10) bombe.sort() r={} for i in range(9): for j in range(9): r[f'r{i}s{j}']=0 for t in bombe: r[f'r{t//9}s{t%9}']='bomba' for i in range(9): for j in range(9): if r[f'r{i}s{j}'] != 'bomba': l=[f'r{i}s{j+1}', f'r{i}s{j-1}', f'r{i+1}s{j-1}', f'r{i+1}s{j}', f'r{i+1}s{j+1}', f'r{i-1}s{j-1}', f'r{i-1}s{j}', f'r{i-1}s{j+1}'] for t in l: if t in r and r[t]=='bomba': r[f'r{i}s{j}']+=1 print(r) return r r=postavljanje() def okolni(gumb,gumbi): i = gumb.r j = gumb.s l=[f'r{i}s{j+1}', f'r{i}s{j-1}', f'r{i+1}s{j-1}', f'r{i+1}s{j}', f'r{i+1}s{j+1}', f'r{i-1}s{j-1}', f'r{i-1}s{j}', f'r{i-1}s{j+1}'] for t in l: if t in r and r[t]!='bomba': g = Gumb(t, r[t]) gumbi.append(g) return gumbi def klik(request): ID = request.POST['ID'] vr = r[ID] print(ID) print(vr) print('bruh') gumbi = [] g = Gumb(ID, vr) gumbi.append(g) provjereni = [] provjereni.append(g) if vr == 0: okolni(g, … -
Using Muliple Model with Class based View Django 2.0
I'm building a warehouse management application in which I required to pass multiple models to class based views. For Example, I have a list of all the order with Product and fulfilment status. But I'm not able to pass multiple models form my class-based view to be displayed and use in my Template my Order Model class Order(models.Model): Order_id = models.IntegerField(primary_key=True) Product = models.ManyToManyField(Product) Shipping_addreess_1 = models.CharField(max_length=1000, blank=False) Shipping_addreess_2 = models.CharField(max_length = 1000,blank= True) Shipping_addreess_3 = models.CharField(max_length=1000, blank=True) Pin_Code = models.IntegerField(blank=False) City = models.CharField(max_length=256, blank=True) State = models.CharField(max_length=256, blank=False) Order_date = models.DateField Order_status = models.CharField(choices = order_status,max_length=2) Payment_method = models.CharField(choices = Payment_type,max_length=3) my Product model class Product(models.Model): SKU = models.CharField(max_length=365, unique=Tr) product_title = models.CharField(max_length=1000, blank = False) FSN = models.CharField(max_length=365,blank=True) Listing_ID = models.CharField(max_length=100, blank=True) ASIN = models.CharField(max_length=1000, blank=True) Price = models.IntegerField(blank=False) Product_category = models.CharField(max_length=256) #poster,t-shirt,notebook def __str__(self): return self.product_title I try passing through get_context_data method. As mention in some answer here. Views.py class OrderListView(ListView): def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['order'] = Order.objects.all() context['Product'] = Product.objects.all() return context But I got the error. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/orders/ Django Version: 2.2 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'orders'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', … -
How to change "Add user" in the navbar of User Add Page of Django Admin?
I'm working on Django and I want to change the "Add user" in the navbar of the User Add Page as marked in the pic with some other text. my admin.py file is this : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So it can be changed?? If yes then how?? Thanks in advance!! -
Failled to install Pillow using Pycharm
I am using Pycharm on windows 7 32bit, i am learning to make a website using django. i am trying to make imagefield, so i tried to install Pillow in the command window and it give me this error: (venv) C:\Users\مرحبا\PycharmProjects\TryDjango>py -m pip install Pillow Collecting Pillow Exception: Traceback (most recent call last): File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\basecommand.py", line 228, in main status = self.run(options, args) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\commands\install.py", line 291, in run resolver.resolve(requirement_set) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\resolve.py", line 103, in resolve self._resolve_one(requirement_set, req) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\resolve.py", line 257, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\resolve.py", line 210, in _get_abstract_dist_for self.require_hashes File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\operations\prepare.py", line 245, in prepare_linked_requirement req.populate_link(finder, upgrade_allowed, require_hashes) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\req\req_install.py", line 307, in populate_link self.link = finder.find_requirement(self, upgrade) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\index.py", line 484, in find_requirement all_candidates = self.find_all_candidates(req.name) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\index.py", line 442, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\index.py", line 587, in _get_pages page = self._get_page(location) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\index.py", line 705, in _get_page return HTMLPage.get_page(link, session=self.session) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\index.py", line 814, in get_page "Cache-Control": "max-age=600", File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_vendor\requests\sessions.py", line 521, in get return self.request('GET', url, **kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\download.py", line 397, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_vendor\requests\sessions.py", line 508, … -
Django - passing variable from function into html view
Good afternoon, I have a problem and i can't figure it out how to do it. I try to display in html view weather from api but it't not working. Views.py from urllib.request import Request, urlopen from django.shortcuts import render from django.http import HttpResponse from django.views.generic import TemplateView from django.template.response import TemplateResponse # Create your views here. class DashboardView(TemplateView): template_name = "index.html" def index(request, template_name="index.html"): headers = { 'Authorization': 'my_private_api' } args={} request = Request('https://avwx.rest/api/metar/KJFK', headers=headers) response_body = urlopen(request).read() args['metar'] = response_body return TemplateResponse(request,template_name,args) index.html (template) {%block content %} <div> <h1>Metary</h1> <p> {{ metar }}</p> </div> {%endblock content%} urls.py from django.urls import path from . import views from dashboard.views import DashboardView urlpatterns = [ path('', DashboardView.as_view()), ] So what i want to do is display data from api into view using variable "metar". Thank you very much for help. -
Testing schemas in multi tenant django app
I have multi tenant Django application with a Postgres DB, that follows a shared db and isolated schema approach as detailed here: https://books.agiliq.com/projects/django-multi-tenant/en/latest/shared-database-isolated-schema.html I'm trying to create a test to see if data is properly segregated with users that have the same username but are in different schemas. For example: Schema Tenant A has user John Schema Tenant B has user John I need some guidance on how to setup a test that checks the schema and users associated with that schema. -
How to create a search box in django which can recommend similar movies the movies
This code can recommend the movies in jupyer notebook but now I get stuck while creating search box which can display movies in webpage def recommendations(title, cosine_sim=cosine_sim): # Get the index of the movie that matches the title idx = indices[title] # Get the pairwsie similarity scores of all movies with that movie sim_scores = list(enumerate(cosine_sim[idx])) # Sort the movies based on the similarity scores sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) # Get the scores of the 10 most similar movies sim_scores = sim_scores[1:11] # Get the movie indices movie_indices = [i[0] for i in sim_scores] # Return the top 10 most similar movies return df['title'].iloc[movie_indices] Here I tried to recommend a movie but failed can anyone can help me to display in web browser by using get method in Django def recomm(request): if request.method == 'GET': query="" movie = recommendations('movie') movie = movie.recommendation(str(query)) return render(request, 'home.html', movie) else: return render(request, 'home.html') return redirect(request, 'home.html') -
Customizing email_confirmation_message.txt of allauth django project gives error what to do?
Invalid block tag on line 7: 'endblocktrans', expected 'endautoescape'. Did you forget to register or load this tag? {% load account %}{% user_display user as user_display %}{% load i18n %}\ {% autoescape off %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Hi from {{ site_name }}! You're receiving this e-mail because user {{ user_display }} has given yours as an e-mail address to connect their account. To confirm this is correct, go to {{ activate_url }} {% endblocktrans %}{% endautoescape %} {% blocktrans with site_name=current_site.name site_domain=current_site\ .domain %}Thank you from {{ site_name }}! {{ site_domain }}{% endblocktrans %} -
How I can use django MedalForm object and Queryset to do login authentication function
My following question is about how I can develop a function that I can compare a POST request data (MedalForm) and existing data of model in queryset. This is mi models.py: class Employee(models.Model): dni = models.CharField(max_length=9, null=False, blank=False, default="12345678R") name = models.CharField(max_length=7) surname = models.CharField(max_length=8) email = models.CharField(max_length=20) telefone_number = models.IntegerField() user_nick = models.CharField(max_length=10, null=False, blank=False, default="user") password = models.CharField(max_length=20, null=False, blank=False, default="password") ticket = models.ManyToManyField(Ticket) forms.py (EmployerLoginForm only to user_nick and password): class EmployerForm(forms.ModelForm): class Meta: model = Employee fields = "__all__" class EmployerLoginForm(forms.ModelForm): class Meta: model = Employee exclude = ['dni', 'name', 'surname', 'email', 'telefone_number', 'ticket'] In this case, to develop login function I am using the EmployerLoginForm in views.py: _logger = nexus_services_logs.Logging(statics.NEXUS_VIEWS_LOGGING_NAME) _views_manager_service = nexus_services_views_manager.ViewsManagerService() _auth = nexus_services_auth.Authentication() class IndexView(View): def post(self, request, *args, **kwargs): form = EmployerLoginForm(request.POST) if(_auth.check_model_employer_authentication(form, _logger, _views_manager_service)): if(_views_manager_service.validate_form(form, _logger)): _views_manager_service.save_form(form, _logger) return redirect('employerPortal') else: return redirect('index') check_model_employer_authentication(form, _logger, _views_manager_service) is the function where I want compare form data and queryset. I find the problem when I cannot compare the objects using for loop (in auth.py): class Authentication(): def __init__(self): self.employer_exist = False def check_model_employer_authentication(self, model, logger, views_manager_service): queryset_all_employers = Employee.objects.order_by("id") context_exployers = views_manager_service.build_context_queryset_employers(queryset_all_employers) for employer in context_exployers["employers"]: if(employer.user_nick == model.user_nick and employer.password == … -
how to check wheater user is logged in or not
I am working on invoice management system in which user can add invoice data and it will save in database and whenever user logged in the data will appear on home page but whenever user logout and try to access home page but it is giving following error. TypeError at / 'AnonymousUser' object is not iterable i tried AnonymousUser.is_authenticated method but still not working. i want if user is logged in then home.html should open otherwise intro.html here is my code views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Invoicelist def home(request): if request.user.is_authenticated(): context = { 'invoices': Invoicelist.objects.all() } return render(request, 'invoicedata/home.html', context) else: return render(request, 'invoicedata/intro.html', context) home.html {% extends "invoicedata/base.html" %} {% block content %} {% for invoice in invoices %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <small class="text-muted">{{ invoice.date_posted|date:"F d, Y" }}</small> <h2><a class="article-title" href="{% url 'invoice-detail' invoice.id %}">{{ invoice.issuer }}</a></h2> </div> <p class="article-content">{{ invoice.invoice_number }}</p> <p class="article-content">{{ invoice.date }}</p> <p class="article-content">{{ invoice.amount }}</p> <p class="article-content">{{ invoice.currency }}</p> <p class="article-content">{{ invoice.other }}</p> <div class="article-metadata"> <small class="text-muted">{{ invoice.author }}</small> </div> </div> </article> {% endfor %} {% endblock content %} intro.html {% … -
Django pre_save or post_svae is not triggered on through model but post_delete is
So I am working on a google calendar integration. I have users and shifts and in the through model I want to add a google_calendar_id. So right now I have a through model class ShiftUser(models.Model): shift = models.ForeignKey("shift.Shift", models.DO_NOTHING, related_name="shift_users") user = models.ForeignKey(User, models.DO_NOTHING, related_name="user_shifts") google_calendar_id = models.CharField(max_length=1024, null=True) class Meta: unique_together = (("shift", "user"),) But the save method does not work on through model so I added a pre_save on the model: @receiver(pre_save, sender=ShiftUser) def shift_user_change(instance, **kwargs): GoogleIntegration.create_event(instance) I tried this approach with pre_save and post_save but both are not triggered. But when I use post_delete it does work. Does anybody know why this is? For the record. I tried m2m_changed but I need to know which users changed and from what I gathered I can't do that without doing two queries per change in the relationship. This is of course not the worst but I think the pre_save is a cleaner solution. -
Django functional Based view to FormView
I have my code written in functional-based views and I came to know about the generic views which are built into Django. I have made changes using Views, TemplateViews but I got stuck at FormView. Functional Based View: def NewTeam(request): form = NewTeamForm() if request.method == 'POST': form= NewTeamForm(request.POST, request.FILES) if form.is_valid(): form.save(commit = True) return teams(request) else: print("Invalid Form") return render(request,'teamform.html', {'form':form}) FormView I tried class NewTeam(FormView): template_name = 'teamform.html' form_class = NewTeamForm success_url = '.' def get_context_data(self,**kwargs): context = super(NewTeam, self).get_context_data(**kwargs) form = NewTeamForm() if request.method == 'POST': form= NewTeamForm(request.POST, request.FILES) if form.is_valid(): form.save(commit = True) return teams(request) else: print("Invalid Form") context['form'] =form return context I can understand that I need to get the context in the first function and create a new function form_valid. I have seen the documentation and other stack answers but I couldn't get it like how to validate the form with in it. Thanks in Advance. -
Instance of 'ForeignKey' has no 'price' member
I get an error when i try to use the price and discount_price objects from the Equipment class in the EquipmentOrderItem class here is the class in my models.py file class EquipmentOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) equipment = models.ForeignKey(Equipment, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) objects = models.Manager() def __str__(self): return f"{self.quantity} of {self.equipment.name}" def get_total_equipment_price(self): return self.quantity * self.equipment.price def get_total_discount_equipment_price(self): return self.quantity * self.equipment.discount_price here is the class i want to get the object from class Equipment(models.Model): name = models.CharField(max_length=200) pic = models.ImageField(upload_to='gallery') description = models.TextField(default='about item') price = models.FloatField(default=0) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=3, default='VID') label = models.CharField(choices=LABEL_CHOICES, max_length=1, default='P') slug = models.SlugField() objects = models.Manager() def __str__(self): return self.name def get_absolute_url(self): return reverse('create:equipment_detail', kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("create:add_to_cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("create:remove_from_cart", kwargs={ 'slug': self.slug }) -
Override generics.RetrieveAPIView called with slug field
I'm using generics.RetrieveAPIView in DRF to return details using a slug lookup field. I get the slug from the url www.../slug, and then fetch the required data from the API: http://...api/slug/. It works fine when the user enters the 'slug' in the url however when they login, they don't enter the slug so I set it with code. In my code, I set the slug to anonymous. At this points, I use the User in request to fetch the details but it's not working. Please help. Here's my generics view: class StoreDetail(generics.RetrieveAPIView): lookup_field = 'slug' serializer_class = StoreSerializer def get_queryset(self): if self.kwargs: slug = self.kwargs['slug'] if slug != 'anonymous': # means slug is in URL return Store.objects.filter(slug=slug) else: # manually get slug from db id = self.request.user.id store = Store.objects.get(account=id) slug = store.slug # Everything up to here works however it returns 404(Not found) return Store.objects.filter(slug=slug) -
Updating User and extended User Profile in one API Call in Django Rest Framework
I have a form on my frontend where the user can update some info - part of the fields are supposed to update the default Django User Model, while others should update the User Profile model, which has a One-To-One Relationship to the User. I am running the code below but get the following error: AttributeError: 'str' object has no attribute '_meta' api.py # Get and Update User API class UserAPI(generics.RetrieveUpdateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(request.user) return Response(serializer.data) def update(self, request, *args, **kwargs): user_data = request.data['user'] profile_data = request.data['profile'] user_serializer = self.serializer_class(request.user, data=user_data, partial=True) user_serializer.is_valid(raise_exception=True) user_serializer.save() if profile_data: profile_serializer_class = ProfileSerializer profile_serializer = ProfileSerializer(request.user.username, data=profile_data, partial=True) print(profile_serializer) profile_serializer.is_valid(raise_exception=True) profile_serializer.save() response = {'user': user_serializer.data, 'profile': profile_serializer.data} return Response(response) # UserProfile API class ProfileAPI(generics.RetrieveAPIView): lookup_field = 'user' serializer_class = ProfileSerializer queryset = Profile.objects.all() serializers.py # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'first_name', 'last_name') # Profile Serializer class ProfileSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField(read_only=True, slug_field="username") class Meta: model = Profile fields = '__all__' I am making a patch request in the following format: { "user": { "username": "testuser" }, "profile": { "bio": "hello this is my bio" } … -
Form attributes not displaying on webpage
I am trying to add classes to my forms but the classes are not being applied. I cannot find what I'm doing wrong. Any help would be greatly appreciated. I'm hoping to set bootstrap classes, so I'd like , if possible. class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, default='') surname = models.CharField(max_length=200, default='') dob = models.DateTimeField('Date of birth (mm/dd/yyyy)', null=True, default=now) preferred_subjects = models.CharField('Are there subjects you would prefer doing?', max_length=200, default='') class PersonalInformationForm(forms.ModelForm): OPTIONS = ( ("ANI", "Animals"), ("ART", "Art"), ("COM", "Communication"), ) preferred_subjects = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple( attrs={ 'class' : 'not working', 'id' : 'not working' } ), choices=OPTIONS) class Meta: model = PersonalInformation fields = ['first_name', 'surname', 'dob', 'preferred_subjects'] widgets = { 'dob': DatePickerInput( options={ "format": "MM/DD/YYYY", "showClose": False, "showClear": False, "showTodayButton": False, } ), } Thank you. -
Django MYSQL Application Deployment in AWS EB
could someone guide me how I can upload my Django application with mysql connectivity on AWS. I have checked many videos and forums but i am still not getting the solution to it. App Tree: . │ .gitignore │ db.sqlite3 │ manage.py │ requirements.txt │ ├───.ebextensions │ django.config │ ├───.elasticbeanstalk │ config.yml │ └───aquaponics │ settings.py │ urls.py │ wsgi.py │ __init__.py │ └───__pycache__ settings.cpython-36.pyc urls.cpython-36.pyc wsgi.cpython-36.pyc __init__.cpython-36.pyc Here is my .ebextensions\django.config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: aquaponics/wsgi.py Requirements.txt: awsebcli==3.18.0 botocore==1.15.46 cement==2.8.2 certifi==2020.4.5.1 chardet==3.0.4 colorama==0.4.3 Django==2.1.5 docutils==0.15.2 future==0.16.0 idna==2.7 jmespath==0.9.5 mysqlclient==1.4.6 numpy==1.18.3 opencv-python==4.2.0.34 pathspec==0.5.9 pypiwin32==223 python-dateutil==2.8.0 pytz==2019.3 pywin32==227 PyYAML==5.3.1 requests==2.20.1 semantic-version==2.5.0 six==1.11.0 termcolor==1.1.0 urllib3==1.24.3 wcwidth==0.1.9 Error: 2020-04-26 10:57:12 INFO Environment update is starting. 2020-04-26 10:57:15 INFO Deploying new version to instance(s). 2020-04-26 10:57:29 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2020-04-26 10:57:30 ERROR [Instance: i-055a8412cc9b0dd5e] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2020-04-26 10:57:30 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2020-04-26 10:57:30 ERROR Unsuccessful command execution on instance …