Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Changing admin site codes to another app in Django
I am learning django I would like to move admin to another app that I created but I couldn't do and don't know how to do it. How can I move all admin site codes to another app? Simply moving or creating admin codes in that app didn't work. -
Getting a "Django can only handle ASGI/HTTP connections, not websocket." error when hosting ASGI on heroku?
Been scrolling though every question on StackOverflow and Youtube to find an answer. I'm deploying both WSGI and ASGI/websockets via Django channels on Heroku. It works locally, but it's been giving me trouble during production. Setup Here's my procfile: web: daphne API.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker background -v2 Settings.py: # Redis Setup ASGI_APPLICATION = 'API.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [(HEROKU_URL, 6379)], }, }, } asgi.py: import os import django from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'API.settings') django.setup() application = get_asgi_application() And finally, routing.py: application = ProtocolTypeRouter({ 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^timer/$", TestConsumer.as_asgi()), ] ) ) ) ,'channel':ChannelNameRouter({ 'background':BackgroundConsumer.as_asgi() }) }) Problem/logs Heroku logs when connecting to the websocket: 2021-07-02T19:42:42.209398+00:00 app[web.1]: IP - - [02/Jul/2021:19:42:42] "GET /chat_switch/1/" 200 10480 2021-07-02T19:43:02.708851+00:00 app[web.1]: IP - - [02/Jul/2021:19:43:02] "WSCONNECTING /timer/" - - 2021-07-02T19:43:02.709658+00:00 app[web.1]: 2021-07-02 19:43:02,709 DEBUG Upgraded connection [IP, 32183] to WebSocket 2021-07-02T19:43:03.058159+00:00 app[web.1]: 2021-07-02 19:43:03,057 ERROR Exception inside application: Django can only handle ASGI/HTTP connections, not websocket. 2021-07-02T19:43:03.058167+00:00 app[web.1]: Traceback (most recent call last): 2021-07-02T19:43:03.058168+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/asgi.py", line 143, in __call__ 2021-07-02T19:43:03.058168+00:00 app[web.1]: raise ValueError( 2021-07-02T19:43:03.058169+00:00 app[web.1]: ValueError: Django can only handle ASGI/HTTP connections, not websocket. 2021-07-02T19:43:03.059813+00:00 app[web.1]: 2021-07-02 19:43:03,059 INFO … -
How to share validation and schemas between a DRF FilterBackend and a Serializer
I am implementing some APIs using Django Rest Framework, and using the generateschema command to generate the OpenApi 3.0 specs afterwards. While working on getting the schema to generate correctly, I realized that my code seemed to be duplicating a fair bit of logic between the FilterBackend and Serializer I was using. Both of them were accessing and validating the query parameters from the request. I like the way of specifying the fields in the Serializer (NotesViewSetGetRequestSerializer in my case), and I would like to use that in my FilterBackend (NoteFilterBackend in my case). It would be nice to have access to the validated_data within the filter, and also be able to use the serializer to implement the filtering schemas. Are there good solutions out there for only needing to specify your request query params once, and re-using with the filter and serializer? I've reproduced a simplified version of my code below. I'm happy to provide more info on ResourceURNRelatedField if it's needed (it extends RelatedField and uses URNs instead of primary keys), but I think this would apply to any kind of field. class NotesViewSet(generics.ListCreateAPIView, mixins.UpdateModelMixin): allowed_methods = ("GET") queryset = Note.objects.all() filter_backends = [NoteFilterBackend] serializer_class = NotesViewSetResponseSerializer def … -
Passing a callable to the default option of a model field fails
I have a model named Package. It has fields named, diagnosis, treatment, patient_type, mf and tp. The fields diagnosis, treatment and patient_type have foreign keys defined in separate individual classes, making diagnosis, treatment and patient_type choice fields. Now, what I intend to achieve is that whenever the user chooses the treatment and patient_type from the choices, I want certain figure to appear in mf as a default value. It should be dependant on both the above fields. I have defined a function that takes treatment and patient_type as its arguments, applies the suitable conditions and returns the relevant figure. But when I assign the function to the default option to the mf field, run the migrations and open the webpage and fill in the details in treatment and patient_type, the mf does not return the desired value. What is going on here, is there something that I am doing wrongly? The models: class Diagnosis(models.Model): diagnosis=models.CharField(max_length=30, blank=True) def __str__(self): return self.diagnosis class Treatment(models.Model): treatment=models.CharField(max_length=15, blank=True) def __str__(self): return self.treatment class PatientType(models.Model): patient_type=models.CharField(max_length=15, blank=True) def __str__(self): return self.patient_type class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) max_fractions=models.IntegerField(default=max_fraction(treatment, patient_type)) total_package=models.DecimalField(max_digits=10, decimal_places=2) The function that is added to the default option in … -
Error while trying to connect Django to SQL Server using django-mssql-backend
Windows 10 SQL Server 2019 Python 3.9.1 Django 3.2.5 pip freeze: asgiref==3.4.1 Django==3.2.5 django-mssql-backend==2.8.1 djangorestframework==3.12.4 pyodbc==4.0.30 pytz==2021.1 sqlparse==0.4.1 DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'dbForDjango', 'USER': 'sa', 'PASSWORD': 'sdf874sd21', 'HOST': 'DESKTOP-AR76KF2\SQL_SERVER', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } I can run the server without any problem also py manage.py shell is working but Django can't communicate with the database at all. The command "py manage.py dbshell" occurs this error: Please ignore the directory name "playingWithFastAPI", am using Django not FastAPI :) py manage.py migrate occurs that error: -
Django GET request result for data not in API
Context I am using django to take user input via a form. This data, city_name, is then used to call an API for weather data. The request works fine when an actual city name is given. Blocker/Obstacles However, these 2 specific cases result in the following error. Invalid city name Search button is clicked without entering anything into the form I have tried using some conditional logic to no avail. Any help will be greatly appreciated. Views.py from django.shortcuts import render import requests def index(request): if 'city' in request.GET: city = request.GET['city'] # Query API with user input payload = {'q': request.GET['city'], 'appid': 'API_KEY'} response = requests.get('http://api.openweathermap.org/data/2.5/weather', params=payload) # Parse json output for key value pairs e = response.json() context = { 'city_name': e['name'], 'weather':e['weather'][0]['main'], 'description' : e['weather'][0]['description'], 'temp' : e['main']['temp'], 'pressure':e['main']['pressure'], 'humidity':e['main']['humidity'], 'visibility':e['visibility'], 'wind_speed':e['wind']['speed'], 'wind_deg':e['wind']['deg'] } # successfull response code search_was_successful = (response.status_code == 200) # 200 = SUCCESS context['success'] = search_was_successful return render(request, 'index.html', {'context': context}) else: context = None return render(request, 'index.html', context) HTML(index.html) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WeatherApp</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"> </head> <body> <div align="center"> <h1>Weather in your city</h1> <form action="" method="get"> <input type="text" id="city" name="city" placeholder="Enter a city"> <input type="submit" name="send" value="Search"> … -
AttributeError: module 'django.db.models' has no attribute 'CharFiled'
class Profile(models.Model): File "C:\Users\Billal's PC\Desktop\Django-stuff\My_Ecom\App_Login\models.py", line 78, in Profile username = models.CharFiled(max_length=10, blank=True) AttributeError: module 'django.db.models' has no attribute 'CharFiled' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') username = models.CharFiled(max_length=10, blank=True) full_name = models.CharFiled(max_length=264, blank=True) address_1 = models.TextField(max_length=300, blank=True) city = models.CharFiled(max_length=40, blank=True) zipcode = models.CharFiled(max_length=30, blank=True) country = models.CharFiled(max_length=50, blank=True) phone = models.CharFiled(max_length=20, blank=True) date_joined = models.DateTimeField(auto_now_add=True) -
Dynamic carousel slider with django and bootstrap
I was trying to make image carousel slider of product in my product detail page but I cant make it work properly i tried for loop counter but that doesn't work either I think I have to do some changes in views.py for carousel slider please suggest me some solutions This is my code <div class="container-fluid px-0" style="background-image: url(/static/images/wallpaperflare.com_wallpaper.jpg);background-size: cover; background-repeat: no-repeat;" > {% for product in product%} <div class="row" style="margin-right:0px"> <div class="col-md-6 box "> <!-- Create slider --> <div class="carousel slide" data-ride="carousel" id="abcd"> <!-- Carousel Indicators --> <ul class="carousel-indicators"> <li class="active" data-target="#abcd" data-slide-to="0"></li> <li data-target="#abcd" data-slide-to="1"></li> <li data-target="#abcd" data-slide-to="2"></li> <li data-target="#abcd" data-slide-to="3"></li> </ul> <div class="carousel-inner"> <div class="carousel-item {% if forloop.counter0 == 0 %}active{% endif %}"> <img src="/media/{{product.images.0}}" class="" alt="" id="lol"> </div> <!-- Carousel COntrol --> <a href="#abcd" class="carousel-control-prev" data-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a href="#abcd" class="carousel-control-next" data-slide="next"> <span class="carousel-control-next-icon"></span> </a> </div> </div> </div> <div class="col-md-6 box2 pl-5"> <div class=" mt-4"> <p style="color: rgb(82, 81, 81);margin-top: 120px;" >{{product.brand|upper}}</p> <h1 class="mt-3 st" >{{product.name}}<i class="pl-2 product-favourite far fa-heart" id="dtheart{{product.id}}" onclick="add_to_favorite('{{product.id}}')", data-toggle="tooltip" data-placement="top" title="Add to wishlist"></i></h1> <h3 class="mt-3" style="color: rgb(255, 7, 123);"></h3> <p class="mt-3" style="color: rgb(82, 82, 82);font-size: large;">{{product.description}}</p> <p style="font-size: 20px; font-weight: bolder;">Size: {{product.size}}</p> <p style="font-size: 20px; font-weight: bolder;">Color: {{product.color}}</p> <h3>Price: {% if … -
Django - Page redirect showing as empty page after saving?
I'm working through a Wiki project for CS50's web course and I'm having an issue with my edit entry implementation. I'm able to edit an entry and it saves properly but for some reason, redirecting the user to the newly edited entry is only showing an empty entry page like this: here's my views. py: def edit(request, title): content = util.get_entry(title) if request.method == "GET": return render(request, "encyclopedia/edit.html", { "title": title, "content": content }) elif request.method == "POST": title = request.POST.get("title") content = request.POST.get("content") util.save_entry(title, content) html = md_converter(util.get_entry(title)) return render(request, "encyclopedia/entry.html", { "title": title, "content": html }) else: return render(request, "encyclopedia/edit.html", { "title": title, }) and my urls.py: from . import views app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", views.entry_page, name="entry"), path("wiki/edit/<str:title>", views.edit, name="edit"), path("search", views.search, name="search"), path("random", views.random_page, name="random"), path("create_landing",views.create_landing_page, name="create_landing"), path("create_entry",views.create_entry, name="create_entry") ] Is there something wrong with my redirect? When I revisit the entry page, the page shows the edits I made Thanks so much for reviewing. -
NoReverseMatch at / Reverse for 'foroshande' with arguments '('',)' not found. 1 pattern(s) tried: ['foroshande/(?P<prof_id>[^/]+)$']
idk what to do with this. looks like ineedto pass prof_id in home but i dont need an id in my url this is home views.py from django.shortcuts import render from .models import * from .forms import * def home(request): form = DatasetForm(request.POST or None) if form.is_valid(): form.save() return render(request, 'main/home.html', {'form': form}) def foroshande(request, prof_id): prof = DatasetModel.objects.get(pk=prof_id) return render(request, 'main/foroshande.html', {'prof': prof}) home.html {% block content %} <form method="POST" action="{% url 'foroshande' form.id %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save" /> </form> {% endblock %} foroshande.htlm {% block content %} <form method="POST"> {% csrf_token %} {{ prof }} <input type="submit" value="save" /> </form> {% endblock %} models.py from django.db import models class DatasetModel(models.Model): open_or_close_CHOICES = ( ("baaz", "baaz"), ("basteh", "basteh") ) name = models.CharField(max_length=100) address = models.CharField(max_length=500) open_or_close = models.CharField( max_length=20, choices=open_or_close_CHOICES, default="baaz" ) forms.py class DatasetForm(forms.ModelForm): class Meta: model = DatasetModel fields = ['name', 'address', 'open_or_close'] idk what to do with this. looks like ineedto pass prof_id in home but i dont need an id in my url this is home -
how do i get crispy form to visibly show an error message?
i have django 3.2, latest crispy forms. with bs template: CRISPY_TEMPLATE_PACK = "bootstrap5" from here I am using a ModelView and Model form. class HspRegistrationForm(ModelForm): def __init__(self, *args, **kwargs): super(HspRegistrationForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'id-hspr' self.helper.layout.append(Submit('save', 'save')) class Meta: model = HomeServiceProvider fields = [...] class HspRegistrationView(CreateView, UserPassesTestMixin): form_class = HspRegistrationForm # sepcify name of template template_name = "mainss/hsp_registration.html" success_url = "/" def test_func(self): return self.request.user.is_active def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) the form is being generated correctly sample below: <form id="id-hspr" method="post" > <input type="hidden" name="csrfmiddlewaretoken" value="..."> <div id="div_id_bus_name" class="mb-3"> <label for="id_bus_name" class="form-label requiredField">Business Name<span class="asteriskField">*</span> </label> <input type="text" name="bus_name" maxlength="200" class="textinput textInput form-control" required id="id_bus_name"> <small id="hint_id_bus_name" class="form-text text-muted">Name of the HSP business</small> </div> .... </form> and when i try submit with something invalid like a required field it will auto take me to that field to indicate it needs filled out. however, there isn't any visible change like an error message or highlighting like i would expect given tutorials and documentation i read. -
Create a token with customer saved card
I want to charge users only when a product has been marked as ready to dispatch. Currently, I can't seem to find a way to create a token for payment server side. Is there a way to do this at all? This is what I've tried so far. All except for token creation works. def charge(request, subscription): stripe.api_key = STRIPE_SECRET_KEY subscription = Subscription.objects.get(id=subscription) user = subscription.customer customer = stripe.Customer.retrieve(user.stripe_id) card_id = user.card token = stripe.Token.create(card=card_id) charge = stripe.Charge.create( amount=500, currency='usd', description='description', source=card_id ) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Custom django admin change form
Hi guys I added a custom change form to one of my models in the admin portal, how can I get access to the current model in the template? I need to prefil fields and create a dropdown for a many to many Also on save how do I redirect to the list view? The form I have submits to a custom view -
pytest fixture to make an AIPClient that I have information for
I am trying to make a fixture that returns an APIClient object that is authenticated for a user that I can pass a parameter to if I need. I have a DjangoModelFactory object called CustomerFactory that can create a customer and a user, the user of which is created with a UserFactory factory. I want to be able to access the data in the customer that is created, but also have a fixture to make an authenticated API request. This api_customer_client is what I came up with, and it doesn't work. @pytest.fixture def api_client(): return APIClient() @pytest.fixture def api_customer_client(app_customer, api_client): def _api_customer_client(test_customer=app_customer): refresh = RefreshToken.for_user(test_customer) api_client.credentials(HTTP_AUTHORIZATION=f"JWT {refresh.access_token}") return api_client return _api_customer_client I am calling the fixture with this test: def test_client_cant_view_users_without_token(self, api_customer_client, app_customer): client = api_customer_client(test_customer=app_customer.user) result = client(reverse("api:user-list"), format="json") assert result.status_code == 401 I keep getting the error TypeError: 'APIClient' object is not callable, and I can't figure out why. I originally thought it might be having trouble going through the api_customer_client fixture and returning a different fixture, but I have tried to just use APIClient directly in the api_customer_client fixture, and that didn't work either. I have another fixture that is nearly identical, except for the sub-method thing, … -
Twilio Unable to send fax
Hope you are having a nice day. I am getting following error on twillion fax api HTTP Error Your request was: POST /Faxes Twilio returned the following information: Unable to create record: The requested resource /Faxes was not found Here is the code . def __init__(self): self.client = Client( settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN, ) self.sender = settings.FAX_SENDER self.receiver = settings.FAX_RECEIVER self.callback_url = settings.TWILIO_CALLBACK_URL i am sending a fax in function with this code fax = self.client.fax.faxes.create( from_=self.sender, to=self.receiver, media_url=pdf_url, status_callback=self.callback_url, ) Is there something I am doing wrong ? -
django tmeplate view is loading slow
I have a template view temrinal management that hs 2 forms and 2 querysets, i am not doing any sorting stuff only a filtering method. I have no idea why the page goes slow, can it happen because of internet connection? I am using a mysql database that is on a separate server. class TerminalManagementView(LoginRequiredMixin, TemplateView): template_name = "app/terminal_management.html" def post(request): pass def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tb_terminal_categories'] = TbTerminalCategory.objects.all() context['tb_terminal_caregory_form'] = TbTerminalCategoryForm() context['tb_terminal_register_form'] = TbTerminalRegisterForm() filter = self.request.GET.get('category') if filter: terminals = TbTerminal.objects.all().filter(category__category_name=filter) else: terminals = TbTerminal.objects.all() page = self.request.GET.get('page', 1) paginator = Paginator(terminals, 9) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) context['terminals'] = data return context from django import forms from .models import TbDepartment, TbTerminal, TbTerminalCategory class TbDepartmentForm(forms.ModelForm): department_name = forms.CharField( max_length=60, required=True) class Meta: model = TbDepartment fields = ['customer', 'department_name', 'parent'] class TbTerminalCategoryForm(forms.ModelForm): class Meta: model = TbTerminalCategory fields = ['category_name', 'category_desc'] class TbTerminalRegisterForm(forms.ModelForm): class Meta: model = TbTerminal fields = ['terminal_name', 'terminal_desc', 'room', 'device_model'] -
(django) I want to create a specified model instance when user was created based on their role
(i.e. if user role is passenger create instance for passenger and if user is driver create respective instance for driver and etc.)I think it's a matter of signals but I need someone to show me the logical ways todo it.) class MyUser(AbstractUser): first_name = models.CharField(max_length=100,null=True) last_name = models.CharField(max_length=100,null=True) email = models.EmailField(null=True) ROLE = ( ('Passenger', 'Passenger'), ('TSHO', 'TSHO'), ('Employee', 'Employee'), ('Driver', 'Driver'), ) role = models.CharField(max_length=200, choices=ROLE) --this the model in which I want to create the instance if user role is driver class Driver(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on delete=models.CASCADE, related_name='employee') occupation=models.CharField(max_length=200,null=True) address=models.CharField(max_length=100,null=True) house_no=models.CharField(max_length=100,null=True) --and this the model in which I want to create the instance if user role is passenger class Passenger(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,related_name='passenger') sex = models.CharField(max_length=200, choices=(('male', 'male'), ('female', 'female')),null=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) -
VM125:1 Uncaught (in promise) SyntaxError: Unexpected token K in JSON at position 0
, I am working on this project which is of an e-commerce site using django. I created a view which will process the order of the user with respect to different scenarios if the user is authenticated or not. Here is the code for the view. transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) else: customer, order = guestOrder(request, data) total = float(data['form']['total']) order.transaction_id = transaction_id if total == order.get_cart_total: order.complete = True order.save() if order.shipping == True: ShippingAddress.objects.create( customer=customer, order=order, address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], zipcode=data['shipping']['zipcode'], ) return JsonResponse('Payment submitted..', safe=False) Note: there are some functions which are in some other files if you want to check them do let me know. enter image description here in this image there are two bugs the first one is referring to process_order view (code above). i am not able to resolve this issue. and when i am trying to POST the data to the database var url = "/process_order/" fetch(url, { method:'POST', headers:{ 'Content-Type':'applicaiton/json', 'Accept': 'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'form':userFormData, 'shipping':shippingInfo}), }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); alert('Transaction completed'); with this code also it in not sending data. Can anybody help? -
Django - Is it better to store user information by customising the default User model, or should I create a separate Model for this?
This is for a practice project I am building to learn Django. The site will need to track certain data about the user. Should I customise the default User model? Or create a new model like - class UserData(models.Model): '''holds user info''' owner = models.ForeignKey(User) # data I couldn't find a clear answer. -
How to delete a django object from multi-form button submission?
Im working on a django app and im fairly sure ive got this wrong but i cant workout how to delete a django object from a form button. Ive got the edit/update fields working but im not sure how to use the same form (or the one below it) to also process a delete. my experience with django is limited and i havent setup the logging yet properly. Ive tried the below. What am i doing wrong? the Model: class Tier(models.Model): number = models.PositiveSmallIntegerField(default=0) description = models.TextField(max_length=800, verbose_name='Description') price = models.IntegerField(verbose_name='Price') can_message = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='tier_user') def __str__(self): return 'Tier ' + str(self.number) def save(self, *args, **kwargs): amount = Tier.objects.filter(user=self.user).count() self.number = amount + 1 return super().save(*args, **kwargs) def delete(sender, instance, *args, **kwargs): tier = instance tier.delete() EditTierForm: <div> <form method="post" action="" role="form" class="col s12"> <h4>Edit Tier</h4> {% csrf_token %} <div class="input-field col s12"> ... </div> <div class="input-field col s12>"> <button class="btn waves-effect waves-light" type="submit" name="action">Save <i class="material-icons right">add</i> </button> </div> </form> <form action="{% url 'tier_delete' tier_id=tier.number %}" method="delete" role="form" class="col s12"> {% csrf_token %} <div class="input-field col s12>"> <button class="btn waves-effect waves-light btn red" type="submit" name="action">Delete Tier <i class="material-icons left">delete</i> </button> </div> </form> </div> urls: path('mytiers/', … -
TypeError when trying to create a model instance
I have a project where I need to create a Django command to upload multiple images at a time. I have a base class Image that defines the file, and subclass Icon that associates a word and a description to the icon. My issue is that I get an error when I call Icon.objects.create(). It works in a single upload context, but not here in the bulk uploader. What should I do about it? models.py class Image(TimestampedModel): """ Abstract model containing an image, a hash of that image, and operation methods. """ class Meta: """ The metaclass defining its parent as abstract. """ abstract = True # Static variables RELATIVE_PATH = 'img' BLOCK_SIZE = 2**16 # Attributes image = models.ImageField( blank=True, null=True, default=None, upload_to=RELATIVE_PATH) _hash = models.BinaryField( _('MD5 hash'), editable=False, null=True, default=None, max_length=16) class Icon(Image): """ Image file associated with a word, a descriptor, and (for verbs) tense. """ # Static variables TENSE_CHOICES = [ (None, 0), ('1', 1), # present ('c', 2), # present participle ('p', 3), # past ('pp', 4), # past participle ] BLOCK_SIZE = 2**12 # Attributes word = models.CharField(max_length=32) descriptor = models.CharField(blank=True, null=True, max_length=32) tense = models.PositiveSmallIntegerField( blank=True, null=True, default=None, choices=TENSE_CHOICES) is_approved = models.BooleanField(default=False) bulk_uploader.py … -
Accessing profile info through user model Django
Hello I am a beginner with the django python framework. I need to display a user's image and bio on a file named user_posts.html in my blog app. I have it where I can access the user's image and bio by looping over the posts for the user. However, I need it so it only displays the bio and the image once. I have a separate profile.html in a users app. In that file, I can do just src="{{ user.profile.image.url }}" and {{ user.profile.bio }} to access the users information but that does not seem to work in my user_posts.html because of the structure of my project. I can't figure out how to tell the for loop to just go over once to access the users information. users_post.html {% extends "blog/base.html" %} {% block content %} <hr size="30"> <div class="row"> <div class="column left"> {% for post in posts %} <img style= "float:left" src="{{ post.author.profile.image.url}}" width="125" height="125"> <h5 style="text-align: left;">{{ post.author.profile.bio }}</h5> {% endfor %} </div> views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') models.py from django.db import models from django.contrib.auth.models … -
how to add variable to value in django templates
i got the problem , im trying to add variable to input Value , i found some solution to this but is not working for some reason, any idea what i wrong ? html <input id="city" name="city" type="text" value="{{ form.country }}"/> <br> {{ form.country }} and this what im getting -
Can't make migrations
I write python3 manage.py makemigrations (I have a mac), migrations are not done, I get a lot of errors, but I don't understand anything about the project at all, here is the traceback Traceback (most recent call last): File "/Users/work/Projects/ims/api/manage.py", line 21, in <module> main() File "/Users/work/Projects/ims/api/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/work/Projects/ims/api/ims/settings.py", line 35, in <module> hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) socket.gaierror: [Errno 8] nodename nor servname provided, or not known teamlead in the team did something like migrations and they were applied, now, after I added indexes to models.py, to optimize sql queries, I needed to make migrations, but it did not work, but the server … -
Parsing nested dictionaries in Html (django)
Models.py class Subject(models.Model): name = models.CharField(max_length = 20) class Student(models.Model): name = models.CharField(max_length = 20) hometown =models.CharField(max_length = 20) class Classes(models.Model): name = models.CharField(max_length = 20) Views.Py def admin_main(request): Student_data = Student.objects.all() Subject_data = Subject.objects.all() Classes_data= Classes.objects.all() New_dict = {"Student_data":Student_data, "Subject_data",Subject_data, "Classes_data",Classes_data} return render(request,"admin_main.html",New_dict) How to display all names from Student in admin_main.html admin_main.html