Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
when I showdown my laptop it's ok. but now my code give me error
Hello I by Django writing a blog and I get this error can you help me? It's my view: class CategoryList(ListView): paginate_by = 3 template_name = "blog/category_list.html" def get_queryset(self): global category slug = self.kwargs.get("self") category = Category.objects.active().filter(slug= slug) return category.articles.published() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["category"] = category return context it's my model and model manager: class CategoryManager(models.Manager): def active(self): return self.filter(status= True) class Category(models.Model): parent = models.ForeignKey('self' , default=None , null=True , blank=True , on_delete= models.SET_NULL , related_name='children' , verbose_name="زیر دسته" ) title = models.CharField(max_length = 200 , verbose_name = "عنوان دسته بندی") slug = models.SlugField(max_length = 100 , unique = True , verbose_name = "آدرس دسته بندی") status = models.BooleanField(default = True , verbose_name = "آیا نمایش داده شود؟") position = models.IntegerField(verbose_name = "پوزیشن") class Meta: verbose_name = 'دسته بندی' verbose_name_plural = 'دسته بندی ها' ordering = ["parent__id","-position"] def __str__(self): return self.title objects = CategoryManager() I check everything but it doesn't fix -
Style django form without bootstrap
im currently new to django. I have search for many tutorial how to style django form without using any bootstrap. Can i style django form without bootstrap and using pure 100% css?. If it can be please show some example I dont want use bootstrap with django form because it limited for me to style it. So i want to know the method to style django form with no bootstrap -
How to list all objs and retrieve single obj using django drf generic views
I am trying to create a single class based view for retirving, listing, and creating all of my orders. I have gotten create and retirve to work but listing is giving some problems. I am using DRF generic views to extend my view and have added the generics.ListApiView to my class. Once I added this however my retirve route started acting unusal. It is returning to me a list of all the orders when I just want a speific one. I tried to just add the generics.ListApiView to my class and override the list and get_queryset functions but that just started to affect my retrive view. class Order(generics.ListAPIView, generics.CreateAPIView, generics.RetrieveAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = addOrderSerializer def get_queryset(self, **kwargs): user = self.request.user return Order.objects.filter(user=user) def get_object(self): pk = self.kwargs['pk'] obj = Order.objects.get(pk=pk) return obj def get_item_serializer(self, *args, **kwargs): return addItemSerializer(*args, **kwargs) def get_shipping_serializer(self, *args, **kwargs): return addShippingSerializer(*args, **kwargs) def create(self, request, *args, **kwargs): user = request.user data = request.data orderItems = data.get('orderItems') print(data) if not bool(orderItems): return Response('No Order Items', status=status.HTTP_400_BAD_REQUEST) else: # TODO - Create Order orderSerializer = self.get_serializer(data=data) orderSerializer.is_valid(raise_exception=True) order = orderSerializer.save(user=user) # TODO - Create Shipping Address shippingSerializer = self.get_shipping_serializer(data=data) shippingSerializer.is_valid(raise_exception=True) shippingSerializer.save(order=order) # TODO - Create Order … -
Django AWS Elastic Beanstalk: Web services not running
I have a Django project that I got up and running on an EC2 instance via Elastic Beanstalk. I have been attempting to connect my site to MySQL on RDS and have been running into problem after problem. I started by following AWS's docs, but very quickly had issues that were resolved by adding an 01_packages.config file under .ebextensions per some other questions on here. Currently my environment is "Degraded" and I honestly can't figure out why... My settings.py has correct DATABASE information, the ALLOWED_HOSTS is correct. When I go to "Causes" for the degradation it tells me: Following services are not running: web. Here are some of the last 100 lines of the logs right after I tried to deploy my project once again. What is causing the issue? /var/log/nginx/error.log 2022/12/10 03:44:52 [error] 27428#27428: *15 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.0.56, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "assignment-env.eba-gx7qabzc.us-west-2.elasticbeanstalk.com" 2022/12/10 03:44:52 [error] 27428#27428: *15 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.0.56, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "assignment-env.eba-gx7qabzc.us-west-2.elasticbeanstalk.com", referrer: "http://assignment-env.eba-gx7qabzc.us-west-2.elasticbeanstalk.com/" 2022/12/10 03:44:53 [error] 27428#27428: *15 connect() failed (111: Connection refused) while connecting to upstream, client: … -
Djano template: Could not parse the remainder: '[]' from '[]'
I'm trying to do something like this to create a new list and append elements to it within a block of template code. {% with my_list=[] %} {% for item in items %} {{ item }} {% with my_list=my_list|add:item %} {# my_list now contains the current item #} {% endwith %} {% endfor %} {% endwith %} But Django says Could not parse the remainder: '[]' from '[]' -
TypeError at /check 'ModelBase' object is not iterable in django
I am trying to print data from database in command prompt(terminal) when i run program it gives error showing TypeError at /check 'ModelBase' object is not iterable i dont understand what the proble is please help me to solve it. this is my views.py here the table name is dish and i want to print name of that dish ` def check(request): dishs = dish.objects.all() for dishs in dish: print(dishs.dish_name) params = {'dish': dishs} return render(request, "card/check.html", params) this is my urls.py urlpatterns = [ path('index', views.index, name="index"), path('check', views.check, name="check"), path('delete/<int:id>', views.delete, name='delete'), path('update/<int:id>', views.update, name='update'), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) this is my models.py class dish(models.Model): dish_id = models.AutoField dish_name = models.CharField(max_length=255, blank=True, null=True) dish_category = models.CharField(max_length=255, blank=True, null=True) dish_size = models.CharField(max_length=7, blank=True, null=True) dish_price = models.IntegerField(blank=True, null=True) dish_description = models.CharField(max_length=255, blank=True, null=True) dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) dish_date = models.DateField() def __str__(self): return self.dish_name ` -
Django forms.py phone number charfield only accept number/integer, I did it but the validation error not working, go to def validate(self)
my forms.py from django import forms from .models import Account FRUIT_CHOICES= [ ('Afghanistan', 'Afghanistan'), ('Albania', 'Albania'), ('Algeria', 'Algeria'), ('Andorra', 'Andorra'), ('Angola', 'Angola'), ('Antigua and Barbuda', 'Antigua and Barbuda'), ('Argentina', 'Argentina'), ('Armenia', 'Armenia'), ('Australia', 'Australia'), ('Austria', 'Austria'), ('Azerbaijan', 'Azerbaijan'), ('Bahamas', 'Bahamas'), ('Bahrain', 'Bahrain'), ('Bangladesh', 'Bangladesh'), ('Barbados', 'Barbados'), ('Malaysia', 'Malaysia'), ] class RegistrationForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) confirm_password=forms.CharField(widget=forms.PasswordInput()) phone_number=forms.CharField(widget=forms.TextInput(attrs={ 'placeholder':'Enter Phone Number' })) country=forms.CharField(widget=forms.Select(choices=FRUIT_CHOICES)) email=forms.EmailField(help_text="We'll never share your email with anyone else") class Meta: model=Account fields=['first_name','last_name','email','phone_number','password'] def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['first_name'].widget.attrs['placeholder']='Enter First Name' self.fields['last_name'].widget.attrs['placeholder']='Enter last Name' self.fields['email'].widget.attrs['placeholder']='Enter Email' self.fields['password'].widget.attrs['placeholder']='Enter Password' self.fields['confirm_password'].widget.attrs['placeholder']='Repeat Password' for abc in self.fields: self.fields[abc].widget.attrs['class']='form-control' def clean(self): cleanned_data=super().clean() password=cleanned_data.get('password') confirm_password=cleanned_data.get('confirm_password') enter image description here if password != confirm_password: raise forms.ValidationError("Password and confirm password does not match") **def validate(self): cleanned_data=super().clean() phone_number=cleanned_data.get('phone_number') if phone_number.is_number() == False: raise forms.VallidationError("Please enter valid phone number, Example=012111111")** okay, regarding this function def validate(self): #this is working, the charfield only accept integer cleanned_data=super().clean() phone_number=cleanned_data.get('phone_number') if phone_number.is_number() == False: raise forms.VallidationError("Please enter valid phone number, Example=012111111") Supposedly I shall get the error when the phone number contain alphabet "Please enter valid phone number, Example=012111111" , right? But the output came out phone_number “gbfhbgf” value must be an integer. May I know any solution to edit this error? enter image description here -
How to fix Django website showing 404 errors on all website links online
so i recently uploaded a my first django website on cpanel . After uploading i realised the website is showing 404 errors on all website links ... let me show the links and urls `from .views.home import Index , shop, about urlpatterns = [ path('', Index.as_view(), name='homepage'), path('store', shop, name='store'), path('about-us', about , name='about-us'), ] ` The design of the website is supposed to automatically go to example.com/shop as the main page but its showing 404 errors instead so .views is a folder under shop app Need assistance on urls and how to correctly configure my website to show content after page load -
RecursionError: maximum recursion depth exceeded while calling a Python object
I have a pretty large Django backend that runs perfectly fine on my Debian Linux server but always throws the following error on my local Windows machine: File "F:\Python\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1138, in _find_and_load_unlocked File "F:\Project\env\Lib\site-packages\imageio\plugins\__init__.py", line 54, in __getattr__ return importlib.import_module(f"imageio.plugins.{name}") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Python\Lib\importlib\__init__.py", line 117, in import_module if name.startswith('.'): ^^^^^^^^^^^^^^^^^^^^ RecursionError: maximum recursion depth exceeded while calling a Python object Can anyone tell me why this error only appears on my local windows machine? The error appears right after starting the server. -
bootstrap offline not working, only via CDN [closed]
<link rel="stylesheet" href="/csvtoppt/bootstrap-offline/css/bootstrap.css"> <script src="/csvtoppt/bootstrap-offline/js/bootstrap.bundle.js"></script> This is the bootstrap code I'm testing out, pulled directly from their webpage: <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled">Disabled</a> </li> </ul> <form class="d-flex" role="search"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> local server complains the file is not found. I'm positive it is right there where I put it. I even right clicked and copied the path. Not Found: /csvtoppt/static/webpages/bootstrap-offline/css/bootstrap.min.css Not Found: /csvtoppt/static/webpages/bootstrap-offline/js/bootstrap.bundle.js [09/Dec/2022 21:46:53] "GET /csvtoppt/static/webpages/bootstrap-offline/css/bootstrap.min.css HTTP/1.1" 404 2890 [09/Dec/2022 21:46:53] "GET /csvtoppt/static/webpages/bootstrap-offline/js/bootstrap.bundle.js HTTP/1.1" 404 2893 I'm using the latest stable release of bootstrap 5.2.3 I've experienced this with another version of bootstrap (5.0.2) It works fine when I used bootstrap delivered via CDN I'm working on a Django project. I use Pycharm as … -
intern_profile_view() missing 1 required positional argument: 'request'
Can anyone tell me what I've done wrong? I'm trying to create a simple multi users app in django and I can quite tell what I'm missing in my view. Here's what I have so far. views.py @method_decorator([login_required, intern_required], name='dispatch') def intern_profile_view(request): if request.method == 'POST': user_form = InternSignUpForm(request.POST, prefix='UF') profile_form = InternProfileForm(request.POST, prefix='PF') if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.save() user.intern_profile.bio = profile_form.cleaned_data.get('bio') user.intern_profile.location = profile_form.cleaned_data.get('location') user.intern_profile.save() else: user_form = InternSignUpForm(prefix='UF') profile_form = InternProfileForm(prefix='PF') return render(request, 'interns/intern_profile.html',{ 'user_form': user_form, 'profile_form': profile_form, }) models.py class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_intern = models.BooleanField(default=False) class InternProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='intern_profile') bio = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=30, blank=True) traceback Traceback (most recent call last): File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mikha\issue_env\lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) TypeError: intern_profile_view() missing 1 required positional argument: 'request' -
django import-export how to add foreing key
I am using django-import-export to import an excel to my model, what I do is that I create a form with some inputs from where it loads the file, then in form_valid() I process the file to load it to the database, the model has two foreign keys 'id_order' and 'gestion'; 'id_orden' comes in the excel and 'gestion' I get it with gestion= Gestion.objects.get(idgestion=obj.pk) which is the id of the form that I am saving, but what I want to know is how I can pass 'gestion' to ModelResource and then save it to the database view.py class GestionView(CreateView): model = Gestion form_class = GestionForm template_name = 'asignacion/gestion.html' success_url = reverse_lazy('asignacion_url:gestion') def form_valid(self, form): isvalid = super().form_valid(form) obj = form.save() gestion= Gestion.objects.get(idgestion=obj.pk) file = self.request.FILES['file'] item_gestion =ItemResourceResource() dataset = Dataset() imported_data = dataset.load(file.read(), format='xls') result = item_gestion.import_data(dataset, dry_run=True) if not result.has_errors(): item_gestion.import_data(dataset, dry_run=False) model.py class ItemGestion(models.Model): idgestion = models.AutoField(primary_key=True) numero_imagenes = models.CharField(max_length=45, blank=True, null=True) id_orden = models.ForeignKey('Asignacion', models.DO_NOTHING) aviso_sap = models.CharField(max_length=45, blank=True, null=True) poliza = models.CharField(max_length=45, blank=True, null=True) observacion_cierre = models.CharField(max_length=250, blank=True, null=True) gestion=models.ForeignKey('Gestion', models.DO_NOTHING) resources.py class ItemResourceResource(resources.ModelResource): id_orden = fields.Field(column_name='id_orden', attribute='id_orden', widget=ForeignKeyWidget(Asignacion,'id_orden')) class Meta: model = ItemGestion import_id_fields = ('id_orden',) exclude = ('idgestion', ) -
Django Ajax Dropdown Select2 not return data
There is a dropdown form that I created with ajax. The form works without using the Select2 tag and returns data. But when I enter the select2 tag, it does not show the detail that should be displayed according to the selection. I use select2 for all select fields in the system. That's why I defined the select2 tag on my layout template like this. <script> $('.select').select2({ allowClear: true }); </script> Here is my ajax code : <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_worksite_id").change(function () { const url = $("#subunitForm").attr("data-subunit-url"); const worksiteId = $(this).val(); $.ajax({ url: url, data: { 'worksite_id': worksiteId }, success: function (data) { $("#id_upper_subunit_id").html(data); } }); }); Thank you for your help, best regards -
Form fields not showing when including form template
The form fields don't show when including form in another template. This is the form: class ClinicSearchForm(forms.Form): q = forms.CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['q'].label = 'Search for' self.fields['q'].widget.attrs.update( {'class': 'form-control'}) This is the template: <form method="get"> {{ form.as_p }} <input type="submit" class="btn btn-primary my-1" value="Search"> </form> And the view: def clinic_search(request): form = ClinicSearchForm results = [] if 'q' in request.GET: form = ClinicSearchForm(request.GET) if form.is_valid(): q = form.cleaned_data['q'] results = Clinic.objects.filter(name__icontains=q) context = { 'form' : form, 'results' : results, } return render(request, 'guide/clinic/clinic_search.html', context) I'm including the form with the include tag but I only get rendered the button, not the field. The form shows when in its own url, but not when included in another template (this other template has no other forms). What am I missing? -
Website on Django . how to display similar products on the product card id page. As in the picture let's say
Website on Django . how to display similar products on the product card id page. As in the picture let's say models.py class Whatches(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=250, verbose_name='Название') description=models.TextField(verbose_name='Описание',blank=True) collections=models.ForeignKey(Collections_watches, on_delete=models.CASCADE, verbose_name='Коллекция часов' ,blank=True,null=True,related_name='watches_collections') price=models.DecimalField(max_digits=7,decimal_places=0,verbose_name='Цена в рублях' ,blank=True ,null=True) image = models.ImageField( help_text='150x150px', verbose_name='Ссылка картинки') slug=models.SlugField(max_length=255,unique=True,db_index=True,verbose_name="URL") ` views.py def watch_card(request, watch_slug): watch_card = get_object_or_404(Whatches, slug=watch_slug) return render(request,'mains/about/catalog/watches/watch_card.html',context={ 'watch_card': watch_card, }, ) enter image description here -
Introspect related model to determine name of attribute for reverse descriptor?
Given schema: class User(models.Model): name = models.CharField(max_length=50) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) User objects will end up having a post_set attribute of type: django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager Which returns a RelatedManager based on Post's default manager. Cool. Q: But if you're trying to introspect on a schema, how do you determine that the attribute name is "post_set"? When I call User._meta.get_fields(), I see a field called "post", not "post_set". (Of type: django.db.models.fields.reverse_related.ManyToOneRel) I've explored nearly all of ManyToOneRel's API, and can't find any attribute or method that will return the value "post_set", only "post". -
NextJS using Django API - How to choose best pattern
I have GeoDjango running on a digital ocean droplet and I'm rewriting project from VueJs to NextJs hosted on Vercel. In Vue we have service pattern connected with store that is responsible for fetching and updating data. I figured out the fetching part which is quite good but I'm still trying to figure out the best way to update data. How should I construct the CRUD layer without using the NextJs API folder ( I don't want to have another backend calling my Django backend). Should I use context? Should I use middleware? Should I create custom services? How to call them then? Is there an equivalent of store in NextJs? I'm asking because I want to avoid cluttering as right now I'm using fetch POST on pages. I'm using NextAuth that gives me a context with jwt token. Thank you for any hints -
navigations and dropdowns are very laggy on ios devices but work fine on android and windows. any Ideas?
Django web app on Pythonenywhere, farhood.pythonanywhere.com, navigations and dropdowns are very laggy on ios devices but work fine on android and windows. any Ideas on what might cause this? I've searched online and did not find any relevant info -
Document more than one repos with MkDocs
I got a special situation where I have a few Django packages that work closely together, and I want to document them together at one place. medux-common: common used models, views, etc. medux: main application medux-online: web interface for certain functions medux-docs: the documentation package Both medux-online and medux use the common module, and I don't want to have 3 documentation homepages, but just one where all is documented at one place. Is there a possibility in MkDocs to "load" external packages? I use the mkdocstrings plugin to load the docstrings from my code. Its docs says, that the path must be set so that the module to document must be importable. In my medux-docs package, I import all the other packages using pip install -e ../medux etc., which works fine. But MkDocs does not find them: $ mkdocs serve [...] ERROR - mkdocstrings: medux.core.middleware could not be found ERROR - Could not collect 'medux.core.middleware' How do I do that? I don't want to merge all repositories into one, as medux and medux-online should be 2 pypi packages too. I just want MkDocs to find the imported medux, medux-online, and medux-common. Do I completely think the wrong way? -
Django-Quill-Editor not rendering text into webpage
I added Quill Editor to my admin panel to post blogs on my django project. But the text doesn't render. once I add the .html and |safe I get a parser error. If I remove the .html it just doesn't render. Any ideas? Strange thing is that this is working on my production server, but not local, which isn't ideal as I would like it working for testing. Here is the code im using: <body> <header>{% include 'navbar.html' %}</header> <div class="blog-container"> <div class="col-md-10" id="bloggrid1"> <div class="row"> {% for post in posts %} <div class="col-md-4" id="bloggrid2"> <div class="blog-post"> <div class="blog-content"> <img class="blog-img" src="{{post.blog_image.url}}" alt="My image" /> <h2 class="blog-title">{{post.blog_title}}</h2> <article class="blog-article"> <p>{{post.blog_article.html|safe}}</p> </article> <a href="{% url 'viewblog' post.id %}" class="btn btn-secondary" type="button" >Read More...</a > <p class="blog-date">Posted on: {{post.blog_date}}</p> </div> </div> </div> {% empty %} <h3>No Blog Uploads</h3> {% endfor %} </div> </div> </div> {% comment %} {% include 'footer.html' %} {% endcomment %} </body> </html> -
Django: Can I change one request in the template and then call the view again? It shall be a loop betwen view and template where one attribute changes
In views.py I use a POST request that specifies the settings for the game. The game function starts the game with these settings. In the template, I want to call the game function again after every round and increase the value of the current round. So in the template I need to submit the form again with the same values from the former request and only increase the value of currentround. I tried to insert the same form in the template and fill it with the values that were put into the former form. Then, only change the value of the current round. Should I create a model for every game that is set up instead and increase the counter in there or is it possible to change the request from round to round for one attribute while maintaining all the other ones? -
Is it possible to get N number of records per a value in a joined table WITHOUT multiple queries?
So I have three tables: article_page - (for my articles) represented by the model Page article_page_category - glue table between article_page and article_category as they're many to many article_category - category information, represented by the model Category I want to make a query to the database that gets N number of records (10 to 20 probably) PER category, preferably in one query, as I can have a lot of categories at once, and this can be quite expensive. I've been trying all sorts of different types of queries and I'm having no luck - I've even tried various subqueries but that didn't translate amazingly well to Django, and raw sql queries were difficult to get working. To give an example: So let's say I have the categories of business, technology, sports I want to get 10 articles from business, 10 from technology, and 10 from sports - all of which are categories in article_category Is there a way to do that with one query? I've got something like this right now, but I really think this isn't the right approach: class GroupedArticleListView(APIView): def get(self, request): categories = Category.objects.filter(taxon=1) categories = categories.annotate( top_articles=Subquery( Page.objects.filter( category=OuterRef("pk") ).order_by("-date").values_list("id", flat=True)[:10].first(), output_field=IntegerField() ) ) The … -
Django admin models not showing in production
I've put my django project into production. Every time a add an admin model it does not update and show on my admin panel. The migrations and collectstatic commands are all going through fine. I have tried to source a fix but I just can't get it to work. Works completely fine in local server. Here is my code although: models.py class PostImage(models.Model): image = models.ImageField(null=False, blank=False, upload_to="images", default="default.png") image_title = models.CharField(max_length=100, null=False, blank=False, default="") def __str__(self): return self.image_title class BlogPost(models.Model): blog_title = models.CharField(max_length=255, null=True, blank=True) blog_article = QuillField(null=True, blank=True) blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") blog_date = models.DateField(auto_now_add=True) def __str__(self): return self.blog_title class EnterImage(models.Model): enter_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") enter_image_title = models.CharField(max_length=100, null=False, blank=False, default="") def __str__(self): return self.enter_image_title class QuillPost(models.Model): content = QuillField() def __str__(self): return self.content class AboutMe(models.Model): about_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") about_image_title = models.CharField(max_length=100, null=False, blank=False, default="") def __str__(self): return self.about_image_title urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', include('martinhensonphotography.urls')), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT) admin.py from django.contrib import admin from . models import PostImage, EnterImage, … -
Login page is showing errors on redirect instead of showing errors on login
I'm completely stumped here. So I copied and pasted this code from another project but on this project for some reason when I enter an incorrect user/pass combo it redirects to anther page then shows the errors there instead of just reloading the login page and displaying the errors there. On the other project, the view reloads the login view with the errors. I'm using Django 3.2 on both projects class LoginView(FormView): form_class = LoginForm template_name = 'users/forms/login.html' success_url = reverse_lazy('blog:index') def dispatch(self, request, *args, **kwargs): if self.request.user.is_authenticated: return redirect('blog:index') return super(LoginView, self).dispatch(request, *args, **kwargs) def form_valid(self, form): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(self.request, user) return redirect('blog:index') else: messages.error(self.request, "Your account is not active, please contact an administrator", extra_tags='alert alert-danger') else: messages.error(self.request, "Username/Password is invalid", extra_tags='alert alert-danger') return super(LoginView, self).form_valid(form) I am displaying the messages in the login template. The messages are working, they're just not reloading the login view, instead it takes me to the success url! What am I missing? This is literally the exact same code I'm using on another project and it's working as expected. -
requests.get generates a continuous loop of the webhook
I built a simple webhook listener in django. The webhook sends me a JSON. I am able to get all the info stored in the JSON correctly. Then I need to download locally an image file from url. from django.views.decorators.csrf import csrf_exempt import requests @csrf_exempt def webhook(request): if request.method == 'POST': print('Webhook received') # I extract all the information I need and I initialize an object received_data = get_all_data_from_json(request.body) x = requests.get(received_data.url) open("myimage.jpg", "wb").write(x.content) ..... ..... ..... return HttpResponse("Webhook received!") The problem is that the requests.get causes the webhook listener to loop endlessly. If I remove it, everything works just fine. Where am I wrong?