Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using the URLconf defined in crm1.urls, Django tried these URL patterns, in this order:
hi im new to django and i am wondering why django is saying "Using the URLconf defined in crm1.urls, Django tried these URL patterns, in this order: admin/ The current path, about, didn't match any of these." urls file: from django.urls import path from django.http import HttpResponse def home(request): return HttpResponse('Home page') def contact(request): return HttpResponse('contact page') urlpatterns = [ path('admin/', admin.site.urls), path('', home), path('about/',contact), ] im following a tutorial on youtube and this is all the guy told me to write so far- thankyouuu -
HyperlinkedModelSerializer working only in detail view but not working in simply list view
This is the error I am getting: Could not resolve URL for hyperlinked relationship using view name "api-blog-post". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. class BlogPostFrontPageSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='api-blog-post', read_only=True) class Meta: model = BlogPost fields = ['id', 'url', 'image', 'categories', 'tags', 'date_created'] # fields = '__all__' path('api/blog-post', views.BlogPostListFrontAPIView.as_view(), name='api-blog-post'), class BlogPostListFrontAPIView(ListAPIView): permission_classes = [AllowAny] queryset = BlogPost.objects.all().order_by('-date_created')[:3] # queryset = BlogPost.objects.all.order_by('-date_created')[:3] serializer_class = BlogPostFrontPageSerializer Here, in above code, my url is not returned, instead lookup error is shown. But in the following detail view, the url shows up. class BlogPostDetailsListAPIView(ListAPIView): permission_classes = [AllowAny] # queryset = BlogPost.objects.all() serializer_class = BlogPostDetailSerializer class BlogPostDetailSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='api-blog-post_details', read_only=True) class Meta: model = BlogPost fields = ['id', 'url', 'image', 'categories', 'description', 'content', 'tags', 'date_created'] # fields = '__all__' path('api/blog-post/<int:pk>', views.BlogPostDetailsListAPIView.as_view(), name='api-blog-post_details'), What is the problem? -
django form does not submit unless you submit twice
Form submits fine on first go if I do not trigger Add More button. If I press Add More button and the fields are empty then I would have to submit form twice to submit, but if I press Add More and fill out the fields then form will submit on one go. Here is my template: {% extends "recipe/base.html" %} {% block container %} <form method="post" action=""> {% csrf_token %} <div class="row spacer"> <h2>Recipe</h2> </div> {% for form in recipeform %} <div class="row spacer"> <div class="col-4"> <label>{{form.label}}</label> </div> <div class="col-10"> <div class="input-group"> {{ form }} </div> </div> </div> {% endfor %} <h3 class="row spacer">Ingredients</h3> {{ formset.management_form }} {% for form in formset %} <div class="row form-row spacer"> {% for f in form %} <div class="col-10"> <label>{{ f.label }}</label> </div> <div class="col-10"> <div class="input-group"> {{ f }} </div> </div> {% endfor %} </div> {% endfor %} <div class="input-group-append row spacer"> <td><button class="btn btn-success add-form-row">Add More</button></td> </div> <div class="row spacer"> <div class="col-4 offset-2"> <button type="submit" class="btn btn-block btn-primary">Update</button> </div> </div> </form> {% endblock %} {% block custom_js %} <script type="text/javascript"> function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var name = … -
NoReverseMatch problem with my tutorial for Django
Going through the Django Tutorial in Python Crash Course and am facing a wall. The error I get is 'Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topics/(?P<topic_id>\d+)/$']'. This is my urls.py from django.conf.urls import URL from . import views urlpatterns = [ # the actual url patter is a call to the url () function, which takes three arguments # Home page url(r'^$', views.index, name='index'), #Show all topics url(r'^topics/$', views.topics, name='topics'), # Detail page for a single topic url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'), ] app_name= 'learning_logs' views.py from django.shortcuts import render from .models import Topic def index(request): """The home page for Learning Log""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics.""" topics = Topic.objects.order_by('date_added') context = {'topics' : topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) topic.html {%extends 'learning_logs/base.html' %} {%block content%} <p>Topic: {{topic}}</p> <p>Entries:</p> <ul> {% for entry in entries %} <li> <p>{{entry.date_added|date:'M d, Y H:i'}}</p> <p>{{entry.text| linebreaks}}</p> </li> {% empty %} <li> There are no entries for this topic yet. </li> {% endfor %} </ul> {%endblock content%} I've read through some of … -
How can I redirect a user from the login page to the signup page in a different app Django?
So, I have been trying to do this problem for a couple of days, but I seem to be having no luck, in actually solving it. For my side-project, I am creating a student grade management system in Django, and the problem that I am getting is that everytime the user clicks on the signup button on the homepage/login page, I get an error, because I haven't re-routed the user successfully. Specifically, the error I get is that it says, Page not Found. The page that I am trying to re-route the user to is in another app. So, I'm trying to route the user to the base url of that app, which from there, it will pop open a view. Here is the code for my urls.py on the loginpage/homepage (App1) from django.urls import re_path from django.shortcuts import redirect # import signUpPage.views as signupview from . import views urlpatterns = [ re_path(r'^$', views.login, name='login'), # re_path('signUpPage', signupview.register, name='signUpPage') # re_path('') ] Here is the code for my forms.py on the loginpage/homepage (App1) from crispy_forms.helper import FormHelper from crispy_forms.layout import Fieldset, Layout class loginForm(forms.Form): UserName = forms.CharField( label="Username", help_text="Please enter your username", widget=forms.TextInput(attrs={"placeholder":"Username"}), required=False ) Password = forms.CharField( label="Password", help_text="Enter … -
How get data from database to modal popup page in Django?
I am developing an ecommerce website with Django.I bought this ready template and try write backend with Django. In my home page displayed product cards and as you see in the below image when I hower over (marked with red) from this cards I can click search icon which open modal page(quick view) as in next below image. home page modal popup page Modal page opens fine, but with static dates. I want take data from my models, for example image from my Product_image model, product name from my Product model. In my other pages for example in home.html page or in product_detail.html (single product page) I already can get datas from models, but in modal popup page I don't know how get data from my models. Please help me. My modal page codes in base.html file. base.html <!-- Quick-view modal popup start--> <div class="modal fade bd-example-modal-lg theme-modal" id="quick-view" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered" role="document"> <div class="modal-content quick-view-modal"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <div class="row"> <div class="col-lg-6 col-xs-12"> <div class="quick-view-img"><img src="{% static 'product/images/pro3/1.jpg' %}" alt="" class="img-fluid blur-up lazyload"></div> </div> <div class="col-lg-6 rtl-text"> <div class="product-right"> <h2>Women Pink Shirt</h2> <h3>$32.96</h3> <ul class="color-variant"> <li class="bg-light0"></li> </ul> <div class="border-product"> … -
FileInput does not update in UpdateView when using InlineFormSets
I'm trying to make a website to allow students to post study materials online. In this piece of code, I intended to create a View using django's UpdateView for users to update their posts. These posts are called 'Materiais' and referenced in models.py as: class Materiais(models.Model): id_materia = models.ForeignKey(Materia, on_delete=models.CASCADE) topico_mas = models.CharField(max_length=200) descr_mas = models.CharField(max_length=200, null=True, blank=True) data_mas = models.DateTimeField(auto_now=True) # data da última edição id_user = models.ForeignKey(User, on_delete=models.CASCADE, default=7) is_active = models.BooleanField(default=True) def __str__(self): return self.topico_mas def get_absolute_url(self): return reverse('materiais-detalhe', args=(self.id,)) For each 'Materiais', the user can upload any number of files to the server, to which I created a One to Many relationship in models.py: class Arquivo_materiais(models.Model): id_materiais = models.ForeignKey(Materiais, on_delete=models.CASCADE) nome_arq = models.CharField(max_length=200) file_mat = models.FileField( upload_to='materiais/', null=True, blank=True) is_active = models.BooleanField(default=True) In forms.py there are the forms for these fields and an InlineFormset: class EditarMateriaisForm(forms.ModelForm): class Meta: model = Materiais fields = ['id_materia', 'topico_mas', 'descr_mas']#, 'files_mas'] widgets = { 'topico_mas': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'topico', 'name': 'topico', 'placeholder': 'Tópico do material'}), 'descr_mas': forms.Textarea(attrs={'class': 'form-control', 'id': 'descr', 'name': 'descr', 'rows': '3', 'placeholder': 'Descrição do material'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['id_materia'].queryset = Materia.objects.filter(is_active=True) self.fields['id_materia'].widget.attrs.update({'class': 'form-control' , 'id': 'mat'}) class ArquivosForm(forms.ModelForm): class Meta: model = … -
Get count of records even if zero
I have below query in my script which returns me the number of records added today per source name. I have added a filter created_at__gte=today. Using this information I am creating one table. Now the problem is if there are no media records for any particular source name, it doesn't appear in the output. I would like that too to appear with count as zero. Can you please guide me how can I achieve that? media_queryset = Media.objects.filter( created_at__gte=today ).values('source__name').annotate( total=Count('id'), last_scraped=Max('created_at') ).order_by('source__name') -
Message Object has no attribute 'fields' when updating model field across apps
I have two apps menu and table. In app table, I have this model: class Table(models.Model): available = models.BooleanField(verbose_name="Availability", default=True) def set_availability(self, avail=False): self.fields['available'] = avail self.save() def __str__(self): return "Table " + str(self.id_num) In one of the views of app menu, I have the following call: from table.models import Table def menu_category_view(request, table_pk): table = Table.objects.get(pk=table_pk) if table.available: table.set_availability(False) ... return render(request, ...) When my template calls this view, I receive this error message 'Table' object has no attribute 'fields'. Here, I am trying to update the value of field available of the instance being called (from True to False). And I got this implementation suggested from a book. Is this the right way to update model instance field value? Thanks. -
Tracking user visited page in a Django Project
I have added a new app to my Django Project to track users visited pages, so I have followed a tutorial step by step but I am now receiving an error: 'PostListView' object has no attribute 'get_object' My questions are: What is the reason behind it so I need some guidance on how to fix it. Is there another easier way to get the user's activity on the website or is this the best way to do it? Here is the models.py: from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.conf import settings from django.contrib.auth.models import User from .signals import object_viewed_signal class History(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True) # product, post object_id = models.PositiveIntegerField() # 1,2,3 content_object = GenericForeignKey() # is the actual object viewed_on = models.DateTimeField(auto_now_add=True) def __str__(self): # return "%s viewed: %s" %(self.content_object, self.viewed_on) return self.user class Meta: verbose_name_plural = "History" def object_viewed_receiver(sender, instance, request, *args, **kwargs): new_history = History.objects.create( user = request.user, content_type = ContentType.objects.get_for_model(sender), object_id = instance.id, ) object_viewed_signal.connect(object_viewed_receiver) Here is the signal.py from django.dispatch import Signal object_viewed_signal = Signal(providing_args=['instance', 'request']) Here is the mixin.py from .signals import object_viewed_signal class ObjectViewMixin: def dispatch(self, request, *args, **kwargs): try: … -
Efficiency of Django filter that mixes indexed and nonindexed fields?
Suppose I have a model like: class Widget(models.Model): a = models.CharField(db_index=True, unique=True) b = models.CharField() and then I perform a filter like: Widgets.objects.filter(a=a, b=b).get() would you expect the performance of this to be (1) the same; or (2) worse ? - than if the model was instead defined as: class Widget(models.Model): a = models.CharField(db_index=True, unique=True) b = models.CharField(db_index=True) # <--- now b is indexed I mean, logically, because a is indexed and unique, at most one result could be found for some value of a, so the engine could just do the lookup on a and then check that the results b field is the expected value, without using any index on b. But in practice, will the generated SQL and underlying SQL engine be smart enough at query planning to figure that out? Is such query planning trivial? -
How to fix QuerySet' object has no attribute 'userrole_set' in django?
When I Adds the specified model objects to the related object set. Like as My view.py: role = UserRole.objects.get(id=user_role_id) s = SbTitle.objects.filter(user_role=1) d = s.userrole_set.add(role) # Associates Entry role with SbTitle s. Then QuerySet' object has no attribute 'userrole_set' error will occur. please tell me how to fix it. MY model.py: class SbTitle(models.Model): sb_title = models.CharField(max_length = 100, blank=True, null=True) user_role = models.ForeignKey(UserRole, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.sb_title -
override create_user() function used by third party app social-auth-app-django
Hello I have a project where I have created my own User model inheriting from BaseUserManager. Now I also want to add the option for users to log via facebook but it is giving me an exception saying that create_user() missing 2 required positional arguments: 'first_name' and 'last_name' because I modified the model to ask for those fields instead of username and other changes. How do I make it so that it can work correctly with my custom user model? -
How to manipulate SubFactory object post generation of DjangoModelFactory?
I've got a DjangoModelFactory like this: class Hello(models.Model): fk = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE) class HelloFactory(DjangoModelFactory): class Meta: model = Hello class BlahFactory(DjangoModelFactory): class Meta: model = Blah hello = factory.SubFactory("path.to.HelloFactory") where hello is a foreign key to Django model Hello. I use a path to HelloFactory since I have a circular import to HelloFactory. When hello is created by doing BlahFactory.create() and then getting hello.fk, you get None because it's not created. How would I create that object in BlahFactory, NOT HelloFactory using something like @post_generation (i.e. I only want to create fk during BlahFactory generation and not during HelloFactory generation)? Just note that Hello's foreign key is a self referencing foreign key. -
Django update some fields in page
I have a problem when I want to update one field in profile view. The problem is when I update social content in the profile the rest data change to empty. For instance, I have a user name called "waad" and Lastname 'WAADABDURHMA', and I have social content like Twitter and Instagram when I update Instagram and Twitter the user name and last name change to empty, and I have tow forms in my HTML one for the personal information and one for social accounts. model.py: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) following = models.ManyToManyField(User,related_name='following',blank=True) bio = models.CharField(max_length=400) profile_image=models.ImageField(null=True,blank=True,default='defult.png') Twitter = models.CharField(max_length=100,blank=True) Facebook = models.CharField(max_length=100,blank=True) Instagram = models.CharField(max_length=100,blank=True) LinkedIn = models.CharField(max_length=100,blank=True) Athr = models.CharField(max_length=100,blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) Forms.py: class FormUpdateUser(forms.ModelForm): class Meta: model=User fields=['first_name','last_name','email'] class FormUpdateBio(forms.ModelForm): class Meta: model=Profile fields=['bio','profile_image','Athr','Facebook','Twitter','LinkedIn','Instagram'] Views.py: class ProfileUpdateView(LoginRequiredMixin, TemplateView): user_form = FormUpdateUser profile_form = FormUpdateBio template_name = 'profile/profile_update.html' def post(self, request): post_data = request.POST or None file_data = request.FILES or None user_form = FormUpdateUser(post_data, instance=request.user) profile_form = FormUpdateBio(post_data, file_data, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, 'تم تحديث ملفك الشخصي بنجاح') return HttpResponseRedirect(reverse_lazy('update_bio')) context = self.get_context_data(user_form=user_form, profile_form=profile_form) return self.render_to_response(context) def get(self, request, *args, **kwargs): return self.post(request, *args, **kwargs) -
AWS copilot with Django never finishes deploying
I've followed the this short guide to create a django app with docker https://docs.docker.com/compose/django/ and then following copilot instructional to push up the container to ECS: https://aws.amazon.com/blogs/containers/introducing-aws-copilot/ I've also used this sample to test everything -- which works out fine: https://github.com/aws-samples/aws-copilot-sample-service The deploy completes and outputs and URL endpoint. In my case, the everything is successfully built, but once the test environment is being deployed it just continuously builds at this: 72ff4719 size: 3055 ⠏ Deploying load-bal:7158348 to test. and never finishes. I've even downsized my requirements.txt to a bare minimum. My Dockerfile FROM python:3.7.4 ENV PYTHONUNBUFFERED=1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt EXPOSE 80 COPY . /code/ docker-compose.yml version: "3.8" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db requirements.txt Django==3.0.8 djangorestframework==3.11.0 gunicorn==20.0.4 pipenv==2020.6.2 psycopg2-binary==2.8.5 virtualenv==16.7.6 Instructions I follow: sudo docker-compose run web django-admin startproject composeexample . Successfully creates the Django App copilot init Setup naming for app and load balancer Choose to create test environment Everything builds successfully and then just sits here. I've tried a number of variations, but the only … -
I'm trying to graphic with django using python but jump IndentationError: expected an indented block
Looks like simple but I'm starting code and I don't know what to do or why this error happened. What I'm trying is to make an example graphic in django that's all not with success, all the information showed is confusing me. this is my views.py from django.shortcuts import render import matplotlib.pyplot as plt def home(request): plt.plot(range(10)) return render(request, 'app1/home.html') def about(request): return render(request, 'app1/about.html', {'title': 'About'}) and jump the next error Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 950, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.9/importlib/__init__.py", line … -
Django annotation filter by annotated value
here is my models: Seller (user, name) Order (seller, customer, amount) Discount (seller, required_amount, value) I need to annotate some current customer stats to each seller (amount sum from customer orders and max discount value with required_amount less then total customer amount) Sellers.objects.filter(orders__customer=request.user).annotate( customer_amount=models.Sum( 'orders__amount', filter=models.Q(orders__customer=request.user) ), discount_value=models.Max( 'discounts__value', filter=models.Q(discounts__required_amount__lte=models.F('customer_amount')) ) ) And I have an error aggregate functions are not allowed in FILTER LINE 1: ...ue") FILTER (WHERE "clients_discount"."amount" <= SUM("order... -
Django: Why isn't my url path using the namespace I've created?
When trying to render my url "http://127.0.0.1:8000/welcomeLiteApp/new", I get the error TemplateDoesNotExist at /welcomeLiteApp/new . My templates all live inside of a namespaced directory in my templates file, i.e. the directory that holds my new.html file is Documents/Code/welcomeLite/welcomeLiteApp/templates/welcomeLiteApp Django is not including the namespace directory when it looks for my new.html template. I can tell this from this error message: Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: Documents/Code/welcomeLite/welcomeLiteApp/templates/new.html (Source does not exist) I tried to set up my views/urls very similarly to in the Django documentation on namespacing (https://docs.djangoproject.com/en/3.1/intro/tutorial03/) I think the namespaced directory is properly included in the new.html file and my urls.py file. new.html file: <li><a href="{% url 'welcomeLiteApp:new' %}">"This is the new.html template"</a></li> urls.py file: from django.contrib import admin from django.urls import include, path from . import views app_name = 'welcomeLiteApp' urlpatterns = [ path('', views.index, name='index'), path('new', views.create, name='new'), ] I tried simply taking my new.html file out of the name spaced directory so it was in the directory that Django said it was looking for it in originally (Documents/Code/welcomeLite/welcomeLiteApp/templates/new.html), and at least was able to get a different error (NoReverseMatch at /welcomeLiteApp/new Reverse for 'new' not found. 'new' is not … -
Sub categories Django
I am new to Django and i came across this blog project. The blog is categorized into 3 category. There are posts already organized into each category. I wanted to add subcategory to further classify the post. Admin should be able to add new subcategories through the admin portal. I made class SubCategory model and register it to the admin and add foreign key = Post 2.Admin should be able to specify which subcategory a post belongs to through the admin portal. [Nice to have] Admin should be able to select which subcategory a post belongs to through the post list in the admin portal (/admin/blog/post). 3.A post can exist with or without a subcategory. Users on a blog category page should see a dropdown where they can select a subcategory and the results get filtered to display posts under that subcategory. “All” should be selected by default. The dropdown should look nice on all screen sizes (mobile, tablet, desktop). [Nice to have] The subcategories are displayed in the dropdown in an alphabetical order. [Nice to have] If a category does not have subcategories, the dropdown is not displayed. How do i proceed further ? Especially bring the filter to … -
Serializing a Django object
I am trying to serialize an object so that I can use it to build an API. The model I want to serialize is my Profile model. The problem is when I go to the url: \users the output is: ["[{\"model\": \"network.profile\", \"pk\": 2, \"fields\": {\"friends\": []}}, {\"model\": \"network.profile\", \"pk\": 3, \"fields\": {\"friends\": []}}, {\"model\": \"network.profile\", \"pk\": 4, \"fields\": {\"friends\": []}}]"] I was expecting something like: [{"user": "one", "friends":["foo", "bar", "baz"]}, {"user": "two", "friends":["one", "bar"]}] models.py class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True) friends = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False) def serialize(self): return { "user": self.user, "friends": [user.username for user in self.friends.all()] } @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): try: instance.profile.save() except Profile.DoesNotExist: Profile.objects.create(user=instance) class Post(models.Model): creator = models.ForeignKey("Profile", on_delete=models.CASCADE) content = models.TextField(max_length=250, blank=True) created = models.DateTimeField(auto_now_add=True) likes = models.PositiveIntegerField(default=0) def serialize(self): return { "id": self.id, "creator": self.creator.user.username, "content": self.content, "created": self.created.strftime("%d %b %Y, %H:%M"), "likes": self.likes } views.py def allUsers(request): if request.method == "GET": profiles = serializers.serialize("json", Profile.objects.all()) else: return JsonResponse({"error": "Error displaying all users"}, status=400) return JsonResponse([profiles], safe=False) def allPosts(request): if request.method == "GET": posts = Post.objects.all() else: return JsonResponse({"error": "Error displaying all posts"}, status=400) posts = posts.order_by("created").all() return JsonResponse([post.serialize() for post in posts], safe=False) … -
Data Manager Role in Django
I'm a beginner in Django and I'm building a prison management system. I require three types of users -- superuser, data manager, and police officer. The superuser should be able to add any kind of user. The data manager should be able to add a police officer and perform CRUD on prisoner details. The police officer should only be able to view prisoner details. Nobody should be able to register themselves to the website. Here's part of my models.py file for the prison app: from django.db import models as md class User(AbstractUser): is_police = md.BooleanField(default=False) is_data_manager = md.BooleanField(default=False) After doing this, I found that the superuser can no longer add any users, they can only add groups. It would also be desirable for the data manager to be able to use the django-admin interface. -
UnicodeDecodeError at / 'utf-8' codec can't decode byte 0xcf in position 27: invalid continuation byte
Good afternoon! I'm Learning Django. I'm writing my first website in Visual Studio. The following problem occurred. I CAN't solve it. Can you please tell me what to do. When the site starts, the server outputs the following: UnicodeDecodeError at / 'utf-8' codec can't decode byte 0xcf in position 27: invalid continuation byte Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.1.2 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0xcf in position 27: invalid continuation byte Exception Location: C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.17 76.0_x64__qbz5n2kfra8p0\lib\codecs.py, line 322, in decode Python Executable: C:\Users\DNS\AppData\Local\Microsoft\WindowsApps\PythonSoftw areFoundation.Python.3.8_qbz5n2kfra8p0\python.exe Python Version: 3.8.6 Python Path: ['C:\\Users\\DNS\\djangoset1\\learning_log', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0\\python38.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\DNS\\AppData\\Local\\Microsoft\\WindowsApps\\Pyt honSoftwareFoundation.Python.3.8_qbz5n2kfra8p0', 'C:\\Users\\DNS\\AppData\\Local\\Packages\\PythonSoftwareFou ndation.Python.3.8_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python38\\site-packages', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0\\lib\\site-packages'] Server time: Sat, 31 Oct 2020 21:15:37 +0000 -
clone a specific attribute from Class A to Class B OneToOneField Django
i want to clone some attributes from user class from django, to an "Employee" class, so when i register a new user with the fields: "First Name" and "Last Name" clone and save on the "Employee" class too. The idea is something like this. class Employee(models.Model): id_em= models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = ATTRIBUTE "FIRST_NAME" FROM DJANGO USER AUTH MODEL. last_name = ATTRIBUTE "LAST_NAME" FROM DJANGO USER AUTH MODEL. bye! -
Django: Referencing uploaded file name in django web pages
Hello I am very new to python / django and I am working on a web app that will take a file that a user uploads, push it to a public S3 bucket and return a link to the file that the user can use elsewhere. After lots of trial and error I was able to get the basic functionality of the system to work. The one part I am struggling with is returning the link of the file that has been uploaded. Here is my views.py: def index(request): """The home page for the upload tool""" if request.method == 'POST': uploaded_file = request.FILES['image'] fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) get_uploaded_file() return render(request, 'upload_tool_app/success.html') return render(request, 'upload_tool_app/index.html') Here is my sucess.html file that I want to contain the link to the uploaded file: {% block content %} <h1>SUCCESS!</h1> <h2>Your image can be accessed from the following link:</h2> <a href="https://{bucket_name}.s3.amazonaws.com/{{ uploaded_file }}"> https://{bucket_name}.s3.amazonaws.com/{{ uploaded_file }}</a> {% endblock %} My question is how do I reference the request.Files['image'] from views in the HTML? I would really appreciate any input on this matter.