Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 'GuideResource' object has no attribute '_meta'
I've upgraded a django project to the latest version 3.1.2 from an older version and one issue is Meta Classes imports. I have this model which intends to inherit meta classes like so class Guide(Contact): operator = models.ForeignKey('guides.SafariOperator', blank=True, null=True, on_delete=models.CASCADE) level = models.ForeignKey('guides.MembershipLevel', blank=True, null=True, on_delete=models.CASCADE) expiry_date = models.DateField(default=django.utils.timezone.now) language = models.ManyToManyField('guides.Language', blank=True) class Meta: ordering = ['name'] class GuideResource(resources.ModelResource): id = fields.Field(column_name='Bd/Sr', attribute="id") sortorder = fields.Field(column_name='Bd/Sr', attribute="sortorder") #description = fields.Field(column_name='Company', attribute="description") address = fields.Field(column_name='Wk PO Box', attribute="address") telephone = fields.Field(column_name='Tel', attribute="telephone") fax = fields.Field(column_name='Fax', attribute="fax") email = fields.Field(column_name='E-mail', attribute="email") class Meta(Guide): pass which then throws this error Traceback (most recent call last): File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "/home/sammy/webapps/kpsga/import_export/admin.py", line 154, in import_action context['fields'] = [f.column_name for f in resource.get_fields()] File "/home/sammy/webapps/kpsga/import_export/resources.py", line 113, in get_fields return [self.fields[f] for f in self.get_export_order()] File "/home/sammy/webapps/kpsga/import_export/resources.py", line 296, in get_export_order return self._meta.export_order or self.fields.keys() Exception Type: AttributeError at /admin/guides/guide/import/ Exception Value: 'GuideResource' object … -
Django Form: comma separated decimal numbers throwing validation errors
I have a form where user can enter decimal/integer values as comma separated like, 500,000 or 500,000.00. When I process the field using the Django ModelForm it raises the validation error like Enter a number, I want to remove those "," before the value makes into the DB. My Form: class EmployeeSalaryForm(forms.ModelForm): class Meta: model = Salary fields = [ 'basic_salary', 'convyence_allowance', 'medical_allowance', 'mobile_allowance', 'executive_allowance', 'gross_salary', 'epf', 'health_benefit', 'ctc', 'join_bonus', 'var_pay', ] basic_salary = forms.DecimalField(max_digits=11,decimal_places=2) convyence_allowance = forms.DecimalField(max_digits=11,decimal_places=2) medical_allowance = forms.DecimalField(max_digits=11,decimal_places=2) mobile_allowance = forms.DecimalField(max_digits=11,decimal_places=2) executive_allowance = forms.DecimalField(max_digits=11,decimal_places=2) gross_salary = forms.DecimalField(max_digits=11,decimal_places=2) epf = forms.DecimalField(max_digits=11,decimal_places=2) health_benefit = forms.DecimalField(max_digits=11,decimal_places=2) ctc = forms.DecimalField(max_digits=11,decimal_places=2) join_bonus = forms.DecimalField(max_digits=11,decimal_places=2, required=False) var_pay = forms.DecimalField(max_digits=11,decimal_places=2, required=False) def clean_basic_salary(self): basic_salary = self.cleaned_data['basic_salary'] return basic_salary.replace(',', '') def clean_convyence_allowance(self): convyence_allowance = self.cleaned_data['convyence_allowance'] return convyence_allowance.replace(',', '') def clean_medical_allowance(self): medical_allowance = self.cleaned_data['medical_allowance'] return medical_allowance.replace(',', '') def clean_mobile_allowance(self): mobile_allowance = self.cleaned_data['mobile_allowance'] return mobile_allowance.replace(',', '') def clean_executive_allowance(self): executive_allowance = self.cleaned_data['executive_allowance'] return executive_allowance.replace(',', '') def clean_gross_salary(self): gross_salary = self.cleaned_data['gross_salary'] return gross_salary.replace(',', '') def clean_epf(self): epf = self.cleaned_data['epf'] return epf.replace(',', '') def clean_health_benefit(self): health_benefit = self.cleaned_data['health_benefit'] return health_benefit.replace(',', '') def clean_ctc(self): ctc = self.cleaned_data['ctc'] return ctc.replace(',', '') def clean_join_bonus(self): join_bonus = self.cleaned_data['join_bonus'] return 0 if join_bonus == None else join_bonus.replace(',', '') def clean_var_pay(self): var_pay = self.cleaned_data['var_pay'] return 0 … -
How to rename default "id" field in django
Is there any way to rename the default Primary key(model) Value "id".(I am not talking about my own created fields)? admin.py class ShiftChangeAdmin(ImportExportModelAdmin): list_display=['id','ldap_id','Vendor_Company','EmailID','Shift_timing','Reason','last_updated_time'] -
Integrating Google Calendars API into Django
I found some examples on using the API in Python, but I was wondering if there is any guidance or examples on using the Calendars API in a Django project. For our website, we want users to be able to enter an event name, start time, and number of hours (event duration) into a form, and for this information to then be used to generate the appropriate Google Calendars event. One concern we had was that the start/end date strings look like they are very specifically formatted, so we were wondering how to translate the form input into start/end time strings. -
How can I call parent's parent class method withouting calling parent's method when using chaining inheritance?
I have a serializer class looks like this: class BargainOrdersAdminSerializer(BargainOrdersSerializer): def update(self, instance, validated_data): if validated_data.get('logistics_company') and validated_data.get('logistics_tracking_no'): validated_data.update(is_shipped=True) return super().update(instance, validated_data) # here, it will also call `BargainOrdersSerializer`'s update method which is not I am expected. As you can see, it inherits from another serializer class as below: class BargainOrdersSerializer(ModelSerializer): ...... def update(self, instance, validated_data): order = instance.order order.status = 'W' order.save(update_fields=['status']) wxpay_query.apply_async((order.id,), countdown=60, link_error=wxpay_error_handler.s(order.id)) return super().update(instance, validated_data) Which also override update method. And now, when I call super().update(instance, validated_data) in child class BargainOrdersAdminSerializer, it calls its parent class's overrided update also which is not I am expected. I want to ignore it. One approach I can figure out is copying the update source code in ModelSerializer and write some custom code in BargainOrdersAdminSerializer's update method. But, it is stupid right? How can I handle it properly? -
How to Access the Logic from a Docker Container?
I am working with a Django App now, and I am new with Docker and a Rookie who is trying turn the App into Microservices. The logics and models I am using are written in a common file. What approach do I have to follow so that I can make my loosely coupled as Microservice? -
Connecting Django models to database names with primary key name other than ID
I have a project where primary column name is 'N' in place of standard 'id'. I have no access to the original database to change it, so I hoped that the following code will do the trick: class ExSLoc(models.Model): id = models.IntegerField(primary_key=True, db_column='n') class Meta: db_table = original_db_table managed = False It actually does, but I run into a strange bug from Django model forms, telling that: 'ExSLoc' object has no attribute 'id' Here's the full traceback. | Traceback (most recent call last): website_1 | File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 174, in get_response website_1 | response = self.process_exception_by_middleware(e, request) website_1 | File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 172, in get_response website_1 | response = response.render() website_1 | File "/usr/local/lib/python2.7/dist-packages/django/template/response.py", line 160, in render website_1 | self.content = self.rendered_content website_1 | File "/usr/local/lib/python2.7/dist-packages/django/template/response.py", line 137, in rendered_content website_1 | content = template.render(context, self._request) website_1 | File "/usr/local/lib/python2.7/dist-packages/django/template/backends/jinja2.py", line 70, in render website_1 | return self.template.render(context) website_1 | File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 1090, in render website_1 | self.environment.handle_exception() website_1 | File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 832, in handle_exception website_1 | reraise(*rewrite_traceback_stack(source=source)) website_1 | File "/opt/project/templates/rfs_submission/rfs_new_0.html", line 1, in top-level template code website_1 | {% extends "rfs_submission/rfs_new.html" %} website_1 | File "/opt/project/templates/rfs_submission/rfs_new.html", line 9, in top-level template code website_1 | {% … -
I want to host my django webpage from my computer publically (Globally)
I've made a django app which I want to host from my own computer using my public IP such that anyone from any part of the world can access it through http://0.0.0.0:8000 where the 0's will be replaced by my public IP. In simple words, I want to make my computer the server for my website. Can anyone help? -
hide previous collapse when i press on other button and show button data - django
hello i want to hide previous collapse when i press on other button and show button data I'm using this format , my problem is data keep show when i press on other button ... i want show just the data when i press on some button and hide other data my html code : <div class="d-flex justify-content-center"> <div class="btn-group" role="group" aria-label="Basic example"> <button type="button" class="btn btn-secondary" data-toggle="collapse" data-target="#phone_pics" aria-expanded="true" style="background-color:#7952b3;border-radius:7px"> phone pics </button>&nbsp; <button type="button" class="btn btn-secondary" data-toggle="collapse" data-target="#space" aria-expanded="true" style="background-color:#7952b3;border-radius:7px"> phone space </button>&nbsp; <button type="button" class="btn btn-secondary" data-toggle="collapse" data-target="#review" aria-expanded="true" style="background-color:#7952b3;border-radius:7px"> review </button>&nbsp; </div> </div> <!-- this for phone pics --> <div id="phone_pics" class="collapse" aria-expanded="true"> <br> <div class="d-flex justify-content-center"> <div class="img"> {% for img in mobile_posts.mobile_images_set.all %} <div class="d-flex justify-content-center"> <img src="{{img.get_image}}" class="img-responsive img-thumbnail" width="50%" height="80%"> </div> {% endfor %} </div> </div> </div> <!-- this for review --> <div id="review" class="collapse" aria-expanded="true"> <br> <iframe width="100%" height="400px" src="{{mobile_posts.mobile_review_video}}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen> </iframe> </div> <!-- this for space --> <div id="space" class="collapse show" aria-labelledby="headingOne" > <br> </div> -
Get class name of descendant in mixin
I want to get the name of the descendant class in the mixin for GenericRelation in Django. Do you have any ideas on how to do that? class ItemMixin: items = GenericRelation(Item, related_query_name="Here I want to get name of a child class") -
How to resolve django react app with webpack?
I am creating django + react project.So instead of running npx create-react-app my-app I created this folder structure inside the frontend django app. To run react components I have webpack with script like this inside package.json file "scripts": { "dev": "webpack --mode development ./frontend/src/index.js -o ./frontend/static/frontend/main.js", "build": "webpack --mode production ./frontend/src/index.js -o ./frontend/static/frontend/main.js" } ├── src │ ├── components │ │ ├── App.js │ │ └── layout │ │ └── Header.js │ └── index.js ├── static │ └── frontend │ └── main.js ├── templates │ └── frontend │ └── index.html ├── tests.py ├── urls.py └── views.py so when I run npm run dev It will see main.js as package and it will create ./frontend/static/frontend/main.js/main.js** as the compiled output file. so when I run django server it will show static file main.js not found (means HTTP 404). So how do I resolve this issue? -
django orm cumulate values of count from group by function
I am new to Django and ORM, and I could not figure out ORM query for cumulate group by count value. Let's make a model simpler with columns with id, reg_dt. What I am trying to do is to get the number of registered users daily, and cumulate the counted number. id | reg_dt 1 | 2020-11-16 2 | 2020-11-16 3 | 2020-11-17 4 | 2020-11-17 5 | 2020-11-17 6 | 2020-11-18 Info.objects.values('reg_dt').annotate(tot_cnt=Count('reg_dt')).order_by('reg_dt') This orm query gives me reg_dt | tot_cnt 2020-11-16 | 2 2020-11-17 | 3 2020-11-18 | 1 And I finally want to make the result something like reg_dt | cumsum 2020-11-16 | 2 2020-11-17 | 5 2020-11-18 | 6 What would be the approach to get cumulated values? -
How to use Django ORM outside of a Django directory?
This is the file structure I want: ./overall_project_directory ./my_django_project ...django stuff ./my_gui ...gui stuff django_and_gui_meet.py Ideally, Django knows nothing about the GUI and the GUI knows nothing about Django for separation of concerns reasons. django_and_gui_meet.py is the only file that contains both Django models and GUI elements. I have read all of these questions: 1, 2, 3, 4, 5, 6. I've also looked at these templates: 7, 8. I've also looked at the Django Docs for using Django without an settings file. I still can't figure out if what I want to accomplish is possible. What I've Tried This is the current file structure I have for a test repo: django_standalone_orm/ ├── db # this is a django project made with `django-admin startproject db` │ ├── db │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── db.sqlite3 │ ├── __init__.py │ ├── manage.py │ ├── people │ │ ├── admin.py │ │ ├── apps.py │ │ ├── in_directory_ui.py # cannot load django models here │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── __init__.py │ │ ├── models.py │ … -
django-ckeditor: Is there a django config/setting to get <br> instead of <br />?
I'd like to have <br> elements from CKEditor instances like that, not <br />. I found this question with an answer, but I don't know where that code should go, in config.js? In my <script> element/JS file? And, actually, I want to know if I can use a config in CKEDITOR_CONFIGS to change this. Why the <br />? Also, why do I get a newline after the <br> element in the HTML? This causes me to get <br />\r\n in my model instance attributes and thus, in my database. The \r\n won't actually cause a problem, but it would be easier if I get rid of it; I think <br> should suffice. -
nginx 404 on root/homepage with Django + Gunicorn
I'm migrating my website from one host to another. The migration has been mostly 99% successful except for the fact that whenever I navigate to the home page of the site, I get nginx's 404 page. Every other page, static & media file is rendered properly. I've wracked my brain trying to find a solution but I haven't found any, let alone someone having a similar issue (instead, others have a working home page but 404 on all others). I have two different domains (one that my company owns, the other is owned by the city we're in). I've updated the DNS on the domain I own to ensure it's working with the new host and it is. When I navigate using the host (example.com) or the server's IP address, the website loads all pages correctly - except the homepage, which - again - returns nginx's 404. All other 404 errors display the 404 page I've set up via Django. Whenever this issue crops up, the gunicorn error log adds a line stating that the service is 'Booting worker with pid: ...' nginx.conf --> save for the paths and port, this conf is identical to the conf running on my … -
Django img src and variety of browsers / OS
I have html documents from django project on which pictures are displayed normally. <!DOCTYPE html> <html> <head> </head> <body> {% load static %} <img src="{% static '/img/bOGlcNacDB_Logo.png' %}"> </body> </html> This is working normally on Linux, Windows, Firefox/Chrome, but not on MacOS Safari/Chrome. Only Firefox. I found out that if I simply replace the src by a random image url, then it is working everywhere: <!DOCTYPE html> <html> <head> </head> <body> {% load static %} <img src="http://...jpg"> </body> </html> But then I am stuck and wonder if there is not something specific to django that I would not know. I tried: <img src="http://mywebsite/...png"> <img src="/...png"> <img src="../../static/img/...png"> No success. Thanks for helping to make this working on MacOS Safari/Chrome. -
How can I get converted data from a model and with validating still works in Serializer in a concise way?
I have a serializer class look like this: class ReceiverInfoSerializer(ModelSerializer): create_at = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M:%S') change_at = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M:%S') user_id = serializers.IntegerField(required=False) receiver_phone_num = serializers.SerializerMethodField() def get_receiver_phone_num(self, instance): secret_phone_num = get_encryption_phone_num(instance.receiver_phone_num) if instance.receiver_phone_num else None return secret_phone_num receiver_phone_num is also a model field. These are plain text form phone numbers store in db table. Now, I want to retrieve it with * replacing middle 4 digits. Like, from 18812345678 converting to 188****5678. And this is what get_receiver_phone_num does. But when I use this SerializerMethodField, the validating for receiver_phone_num becoming invalid, cause it is read-only. In that way, I have to make converting in to_representation method instead like below: def to_representation(self, instance): res = super().to_representation(instance) res['receiver_phone_num'] = get_encryption_phone_num( instance.receiver_phone_num) if instance.receiver_phone_num else None return res and I do not think it is convenient cause I have to override it. Do you have any other workaround about this, please show me. -
python SerpScrap library import issue
Hi python community im facing python SerpScrap library import issue its not install enter image description here -
Ajax Repeating form several time
I am trying to add Ajax to my like button, it is working perfectly fine except that when I press the first time i is added when I press to unlike on more time it starts to automatically repeat itself several times and the more I press the more repeated like and unlike. This the first time I have seen this error before Here is the models.py class Post(models.Model): likes = models.ManyToManyField( User, related_name='liked', blank=True) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) Here is the views.py class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment_qs = None comment = Comment.objects.create( post=post, user=self.request.user, content=content) comment.save() return HttpResponseRedirect("blog/post_detail.html") else: comment_form = CommentForm() context["comments"] = comments context["comment_form"] = comment_form context["total_likes"] = total_likes context["liked"] = liked return context def LikeView(request): # post = get_object_or_404(Post, id=request.POST.get('post_id')) post = get_object_or_404(Post, id=request.POST.get('id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True context = { 'total_likes': post.total_likes, … -
django-ckeditor: how to make carrige return insert a <br> instead of a new <p>?
In my CKEditor instances, I need ENTER to insert a <br> instead of a new <p> element, mainly because of the line separation. I found this question in the CKEditor forums and gave it a try (although they talk about fckconfig.js and not config.js), but it didn't work. Also found this question here, but I don't know how to apply the solution. How can I change this? -
Multiple Nested Serializers from Different Models with Django Rest Framework
My end goal is a json response similar to: { "card_id": "72e81de94dfc0373b006ca75e9c851a1", "item_id": "A.J.Burnett11610311269941028099991216231498183825508164480371614", "name": "A.J. Burnett", "playerattribute": { "team": "Marlins", "contact_l": 16, "power_l": 14 }, "playermarketlisting": { "buy": 420, "sell": 69, } }, Here is my model.py (simplified for the sake of this question): class PlayerProfile(models.Model): card_id = models.CharField(max_length=120, unique=True, primary_key=True) item_id = models.CharField(max_length=120) # used for matching with attributes table name = models.CharField(max_length=120) class PlayerAttribute(models.Model): player_profile = models.OneToOneField( PlayerProfile, on_delete=models.CASCADE, ) team = models.CharField(max_length=120) contact_l = models.IntegerField() power_l = models.IntegerField() class PlayerMarketListing(models.Model): player_profile = models.OneToOneField( PlayerProfile, on_delete=models.CASCADE, ) buy = models.IntegerField() sell = models.IntegerField() Here are the serializers. class PlayerMarketListingForProfileSerializer(serializers.ModelSerializer): class Meta: model = PlayerMarketListing fields = ( 'buy', 'sell', ) class PlayerAttributeForProfileSerializer(serializers.ModelSerializer): class Meta: model = PlayerAttribute fields = ( 'team', 'contact_l', 'power_l' ) class PlayerProfileSerializer(serializers.ModelSerializer): playermarketlisting = PlayerMarketListingForProfileSerializer() playerattribute = PlayerAttributeForProfileSerializer() class Meta: model = PlayerProfile fields = ( 'card_id', 'item_id', 'name', 'playermarketlisting' 'playerattribute' ) Relevant view: class PlayerProfileView(viewsets.ModelViewSet): serializer_class = PlayerProfileSerializer queryset = PlayerProfile.objects.all() filter_backends = (filters.DjangoFilterBackend,) filterset_class = PlayerProfileFilter def get_queryset(self): queryset = super(PlayerProfileView, self).get_queryset() order_by = self.request.query_params.get('order_by', '') if order_by: order_by_name = order_by.split(' ')[1] order_by_sign = order_by.split(' ')[0] order_by_sign = '' if order_by_sign == 'asc' else '-' queryset = queryset.order_by(order_by_sign + order_by_name) return … -
Django channels with Spring Boot Websockets (StompSession) do not work
Hey there we want to use Django just to execute python code and use channels for the results. Implemented everything the websockets are not working as they should. If I try to send something from our Angular frontend to Django it works fine. And otherwise our Spring Boot StompSession Websockets work fine with other Spring Boot Applications and Angular. But Django and Spring Boot do not. What I can see from the Django server logs: WebSocket HANDSHAKING /ws/card-detection/ [127.0.0.1:53209] i'm in connect method WebSocket CONNECT /ws/card-detection/ [127.0.0.1:53209] i'm in receive method text_data: CONNECT This gets executed as soon as the websocket request comes in. The django consumer (without the prints that are logged above): class MyConsumer(WebsocketConsumer): groups = ["broadcast"] def connect(self): self.accept() def receive(self, text_data=None, bytes_data=None): self.send(text_data="Hello world!") def disconnect(self, close_code): pass From Spring Boot we send an base64 encoded image. But also everything else does not work. As you can see the text_data is just CONNECT. Spring Boot: StompSessionHandler sessionHandler = new CardDetectionStompSessionHandler(request, user, webSocketMessagingService); createStompClient().connect(djangoServiceWSPath, sessionHandler); } private WebSocketStompClient createStompClient() { WebSocketClient client = new StandardWebSocketClient(); WebSocketStompClient stompClient = new WebSocketStompClient(client); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); return stompClient; } The stomp session handler to give you an idea how it looks. … -
ModuleNotFoundError: No module named 'register'
I am working on a Django project. I am working on the register page. When I try to import my register/views.py to my mysite/urls.py file I get an error message. ModuleNotFoundError: No Module named 'register'. Both files are are in the same directory. from django.contrib import admin from django.urls import path, include from register import views as v -
DJANGO initial values in form not shown in template (some do some don't)
I have these Models, Tipos, Prioridad and Estado, related to Tarea as defined below: class Tipos(models.Model): tipo = models.CharField(max_length=16, verbose_name='tipo') abrv = models.CharField(max_length=4, null=True, blank=True, default='') class Meta: verbose_name = "Tipo" verbose_name_plural = "Tipos" def __str__(self): return self.tipo class Prioridad(models.Model): prioridad = models.CharField(max_length=16, verbose_name='prioridad') abrv = models.CharField(max_length=4, null=True, blank=True, default='') orden = models.IntegerField(u'orden', blank=False) class Meta: verbose_name = "Prioridad" verbose_name_plural = "Prioridades" def __str__(self): return self.prioridad class Estado(models.Model): estado = models.CharField(max_length=16, verbose_name='estado') abrv = models.CharField(max_length=4, null=True, blank=True, default='') class Meta: verbose_name = "Estado" verbose_name_plural = "Estados" def __str__(self): return self.estado class Tarea(models.Model): numtar = models.AutoField(primary_key=True) cliente = models.ForeignKey(User, related_name='user_cliente', null=True, on_delete=models.DO_NOTHING) apoyo = models.ForeignKey(User, related_name='user_apoyo', null=True, on_delete=models.DO_NOTHING) asignado = models.ForeignKey(User, related_name='user_asignado', null=True, on_delete=models.DO_NOTHING) descorta = models.CharField(max_length=140) deslarga = models.TextField(max_length=8195) estado = models.ForeignKey(Estado, null=True, on_delete=models.SET_NULL) tipo = models.ForeignKey(Tipos, null=True, on_delete=models.SET_NULL) prioridad = models.ForeignKey(Prioridad, null=True, on_delete=models.SET_NULL) creacion = models.DateTimeField(auto_now_add=True) revision = models.DateTimeField(auto_now=True, blank=True) cierre = models.DateTimeField(null=True, blank=True) class Meta: verbose_name = "Tarea" verbose_name_plural = "Tareas" def __str__(self): return '%s' % (str(self.numtar)) and I call the following view: @login_required(login_url='/login') def newincid_view(request): perfil = ExUserProfile.objects.get(user=request.user) prioridad_media = Prioridad.objects.get(prioridad='Media') estado_abierta = Estado.objects.get(estado='Abierta') tipo_incidencia = Tipos.objects.get(tipo='Incidencia') datos_apertura = {'cliente': perfil.user, 'tipo': tipo_incidencia, 'prioridad:': prioridad_media, 'estado': estado_abierta } if request.method == 'POST': form = newincidForm(request.POST,initial=datos_apertura) if form.is_valid(): … -
Stylesheet location reference (?) causing Django NoReverseMatch error
I am currently working on a project in Django and I am having a strange issue. Before I go in depth about the details, here are the html documents and python functions in question: def editpage(request, name): page = util.get_entry(name) #Imported forms as django_forms as not to interfere with forms.py class WikiEditForm(django_forms.Form): title = django_forms.CharField(initial={"title":name}, label='Title:', required=True, widget=django_forms.TextInput(attrs={'placeholder':'Title'})) body = django_forms.CharField(initial={"body":page}, widget=django_forms.Textarea(attrs={'placeholder':'Enter Markdown Content','style':'text'}), required=True, label='Body') if request.method == "GET": search_form = forms.SearchWikiForm() return render(request, 'encyclopedia/editpage.html', { "search_form":search_form, "wiki_edit_form":WikiEditForm(), }) else: search_form = forms.SearchWikiForm() wiki_edit_form = WikiEditForm(request.POST) if wiki_edit_form.is_valid(): page_content = util.get_entry(name) util.save_entry(name, page_content) return HttpResponseRedirect(reverse('encyclopedia:wikipage', name)) layout.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'encyclopedia:findpage' %}" method="get"> {% csrf_token %} {% block search %}{% endblock %} </form> <div> <a href="{% url 'encyclopedia:index' %}">Home</a> </div> <div> <a href="{% url 'encyclopedia:newpage' %}">Create New Page</a> </div> <div> <a href="{% url 'encyclopedia:randompage' %}">Random Page</a> </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% endblock %} </div> </div> </body> </html> page.html: {% extends "encyclopedia/layout.html" …