Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am facing this problem in my about page if i remove my css then it works well otherwise it gives me an error whenever i use to display images
I am facing this problem in my about page if i remove my css then it works well otherwise it gives me an error whenever i use to display images please reply as soon as possible please reply fast for this question if anyone can Django Version: 3.0.5 Python Version: 3.7.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysiteapp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\newproject\mysite\mysiteapp\views.py", line 27, in about return render(request,'about.html') File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loaders\base.py", line 24, in get_template contents = self.get_contents(origin) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loaders\filesystem.py", line 24, in get_contents return fp.read() File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) … -
django Templates does not exists execpt home url
I am creating a simple website.and having kinda odd error TemplateDoesNotExist at /about/ but my homepage working fine without TempaletDoesNotExist error. mine both home.html and about.html in same directory and I tried many solutions with the reference of this answer the actual problem is one URL is working and another one is not. please help me out thanks TemplateDoesNotExist at /about/ about.hmtl Request Method: GET Request URL: https://www.appname./about/ Django Version: 2.2.9 Exception Type: TemplateDoesNotExist Exception Value: about.hmtl Exception Location: /home/name/virtualenv/appname/3.5/lib/python3.5/site-packages/django/template/loader.py in get_template, line 19 Python Executable: /home/name/virtualenv/appname/3.5/bin/python3.5_bin Python Version: 3.5.7 Python Path: ['/home/name/appname', '/opt/passenger-5.3.7-4.el6.cloudlinux/src/helper-scripts', '/home/name/virtualenv/appname/3.5/lib64/python35.zip', '/home/name/virtualenv/appname/3.5/lib64/python3.5', '/home/name/virtualenv/appname/3.5/lib64/python3.5/plat-linux', '/home/name/virtualenv/appname/3.5/lib64/python3.5/lib-dynload', '/opt/alt/python35/lib64/python3.5', '/opt/alt/python35/lib/python3.5', '/home/name/virtualenv/appname/3.5/lib/python3.5/site-packages'] Server time: Sun, 3 May 2020 04:48:46 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /home/name/virtualenv/appname/3.5/lib/python3.5/site-packages/django/contrib/admin/templates/about.hmtl (Source does not exist) django.template.loaders.app_directories.Loader: /home/name/virtualenv/appname/3.5/lib/python3.5/site-packages/django/contrib/auth/templates/about.hmtl (Source does not exist) django.template.loaders.app_directories.Loader: /home/name/appname/mysite/templates/about.hmtl (Source does not exist) My templates<dir> /home/name/appname/mysite/templates/home.html /home/name/appname/mysite/templates/about.html app<views.py> from django.shortcuts import render from django.http import HttpResponse def homepage(request): return render(request=request,template_name='home.html') def about(request): return render(request=request,template_name='about.hmtl') app<urls.py> from django.conf.urls import include, url from django.contrib import admin from django.urls import path from . import views app_name = "bugengine" urlpatterns = [ url(r'^$', views.homepage, name="homepage"), url(r'^about/',views.about, name="about"), ] setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
Vue.js img src using absolute path (django+webpack)
I am using django + Vue.js & webpack for development. In my App.vue file i try to load img: <img src="/static/webapp/img/logo.png" alt="logo"> In production I use nginx which is directing /static path into static folder that I share and it's working. But in the development when i run my django on localhost:8000 and load this js from my App.vue it's trying to get the image from localhost:8000/static/webapp/img/logo.png. I would like it to take from localhost:8082/static/webapp/img/logo.png (localhost:8082 is where webpack is running) where it can be found. I tryied to change publicPath in my webpack.config.js: if (process.env.NODE_ENV === 'development') { module.exports.output.publicPath = 'http://localhost:8082/' } but it does not change default behaviour and the img asset src is still localhost:8000/static/webapp/img/logo.png. How can I change img assets default base path to another url to make it work? Cheers. -
How do you create a custom ChoiceField widget in Django?
I am trying to create a custom select field widget that includes at bootstrap input group. I can get the select element to render, but none of the options get rendered. The only documentation I can find is on creating custom widgets using text inputs. I have copied some of the below code from the Django source code hoping that would solve the issue, but the options are still not generated. Any help would be appreciated. widgets.py from django.forms import widgets from django.template import loader from django.utils.safestring import mark_safe class Select2(widgets.Select): template_name = 'widgets/select2.html' option_template_name = 'widgets/select2-options.html' def render(self, name, value, attrs=None, renderer=None): context = self.get_context(name, value, attrs) template = loader.get_template(self.template_name).render(context) return mark_safe(template) select2.html <select class="form-control select2" name="{{ widget.name }}">{% for group_name, group_choices, group_index in widget.optgroups %}{% if group_name %} <optgroup label="{{ group_name }}">{% endif %}{% for option in group_choices %} {% include option.template_name with widget=option %}{% endfor %}{% if group_name %} </optgroup>{% endif %}{% endfor %} </select> <div class="input-group-append"> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#modal-xl"><i class="fa fa-plus"></i></button> </div> select2-options.html <option value="{{ widget.value|stringformat:'s' }}">{{ widget.label }}</option> -
Django admin: using extra field to filter dropdown values
I have a treebeard model like this (simplified version) from django.db import models from treebeard.mp_tree import MP_Node class CompanyHierarchy(MP_Node): department = models.CharField(max_length=30) employee_title = models.CharField(max_length=300) employee_name = models.CharField(max_length=300) It has 6 levels of depth and thousand of records. Now I'd like to add a new model with relationships between employees class Links(models.Model): from = models.ForeignKey("CompanyHierarchy", related_name='source', verbose_name='Документ', on_delete=models.CASCADE) to = models.ForeignKey("CompanyHierarchy", related_name='destination', verbose_name='Ссылка', on_delete=models.CASCADE) Now, CompanyHierarchy has thousands of records, so adding new Links through django admin panel is very cumbersome, as you have to pick one record from thousands in dropdown menu. How can I make this more user friendly? I was thinking of adding extra fields in django admin so that dropdown menu options could be filtered down. For example, adding extra field department, so that I can pick it first, and then dropdown menu for from would be filtered to include only that department. Or (even better) adding an extra field for setting depth first (treebeard creates this field), then having an extra field that will show only records of this selected depth, then filtering options in dropdown menu to include only records that are children of selected item (using path field that treebeard also creates). Is … -
Django not sending emails to local
I am very new to django and previously had emails sending to my terminal using: python -m smtpd -n -c DebuggingServer localhost:1025 I am trying to access the PasswordResetConfirmView template but cannot access the url as it is not appearing in my terminal. I believe it is now not sending an email. Here is what I used before in my settings: EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 Here are my urls: urlpatterns = [ # Homepage path('', views.home, name='home'), # Login/Logout path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), # Register path('register/', views.register, name='register'), # Profile path('profile/', views.view_profile, name='view_profile'), # Edit profile path('profile/edit/', views.edit_profile, name='edit_profile'), # Edit password path('change-password/', views.change_password, name='change_password'), # Password reset path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'), name='reset_password'), path('reset-password/done/', PasswordResetDoneView.as_view(template_name= 'accounts/reset_password_done.html'), name='password_reset_done'), path('reset-password/confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset-password/complete/', PasswordResetCompleteView.as_view(template_name= 'accounts/reset_password_complete.html'), name='password_reset_complete') ] And a change_password view: def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user= request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect(reverse('view_profile')) else: return redirect(reverse('change_password')) else: form = PasswordChangeForm(user= request.user) args = {'form' : form} return render(request, 'accounts/change_password.html', args) I am not sure why this has stopped sending emails and I am getting no errors on any page. Any ideas? -
Deserializing Nested JSON API response with Django
I'm pretty new to the DRF and serializing/deserializing. I'm slowly building a dashboard for my business during the corona virus and learning to code. I am in a little deep, but after spending more than $10k on developers on upwork and not really get much result, I figured, what do I have to lose? Our software provider has a full API for our needs https://developer.myvr.com/api/, but absolutely no dashboard to report statistics about our clients reservation data. The end result will be a synchronization of some of the data from their API to my database which will be hosted through AWS. I chose to do it this way due to having to do some post processing of data from the API. For example, we need to calculate occupancy rates(which is not an endpoint), expenses from our accounting connection and a few other small calculations in which the data is not already in the provided API. I originally wanted to use the data from the API solely, but I'm hesitant due to the reasons above. That's the backstory, here are the questions: The API response is extremely complex and nested multiple times, what is the best practise to extract a replication … -
I have deployed my Django App on Microsoft Azure and Static files are not displaying, only html
I've deployed a Django app on Azure and run it, everything was working fine css, images, js. After i run Gunicorn to automate the site then Only skeleton HTML displayed, css, images and js disappeared. this is the Erro: /home/honest/venv/lib/python3.6/site-packages/django/core/handlers/base.py:58: FutureWarning: TemplateForDeviceMiddleware is deprecated. Please remove it from your middleware settings. mw_instance = mw_class() /home/honest/venv/lib/python3.6/site-packages/django/core/handlers/base.py:58: FutureWarning: TemplateForHostMiddleware is deprecated. Please upgrade to the template loader. Not Found: /static/images/sample/slider/img7.png/ May i know if i need to configure WhiteNoise for gunicorn on Azure? Do i Need to edit my HTML templates to point to static folder in Azure? I tried some of the solutions i saw here like setting DEBURG to True set path for static files in Settings.py but it couldn't help. I will be glad receiving a step by step solution to this. Thanks for the assistence. -
advantages of MVT(Model View Template) over MVC(Model View Controller)
Any one explain advantages of MVT(Model View Template) over MVC(Model View Controller)? -
Google Places API - Getting an error on POST request when using domain restricted apikey
Google Places API - Getting an error on POST request when using domain restricted apikey. My code works fine for Google Places api when I'm using an unrestricted apikey for both the GET and POST request. When I use the apikey with the following HTTP referrers restriction: stage.myapp.com/* it seems to work fine for GET request, however for post request from stage.myapp.com/mypage/ I get a 500 error. Any recommendation on how to fix this. -
Django PATCH request update password using set_password method
I have below setup, view.py class UserViewSet(viewsets.ModelViewSet): queryset = apis_models.User.objects.all().order_by('-date_joined') serializer_class = apis_serializers.UserSerializer permission_classes = [HasPermPage] http_method_names = ['get', 'patch'] Serializer.py class UserSerializer(CustomSerializer): group = GroupSerializer(read_only=True) class Meta: model = apis_models.User fields = '__all__' models.py class User(DFModel, AbstractBaseUser): GENDER_CHOICES = [ ('m', 'Male'), ('f', 'Female'), ('n', 'Not sure'), ] email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255, null=True) company = models.CharField(max_length=255, null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) date_of_birthday = models.DateField(null=True) job_title = models.CharField(max_length=255, null=True) description = models.TextField(null=True) credit_card = models.CharField(max_length=255, null=True) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) group = models.ForeignKey('Group', on_delete=models.PROTECT, null=True) Using REST API I am doing PATCH request on User model and trying to update the password. The password is getting stored as plain text. I found that set_password method store it as encrypted. Can anybody please help me to implement that. I am not sure where to include that method. In viewset or serializer? And how? Any help would be appreciated. -
DRF ListAPIView custom return not an object
I'm trying to customise ListAPIView in order to return custom object. By default DRF returns object in an array, I want just a customized object. class PostDetailApiView(ListAPIView, CreateAPIView): serializer_class = PostSerializer permission_classes = [AllowAny] def get_queryset(self, request, *args, **kwargs): response = super().get_queryset(request, *args, **kwargs) return Response({ 'status': 200, 'message': 'Post delivered!!', 'data': response.data }) I'm getting error: lib/python3.7/site-packages/django/template/response.py", line 120, in __iter__ 'The response content must be rendered before it can be iterated over.' **django.template.response.ContentNotRenderedError: The response content must be rendered before it can be iterated over.** [03/May/2020 02:34:14] "GET /en-us/blog/api/posts/VueJS%20blog%20in%20progress HTTP/1.1" 500 59 The error dissappears when I return an empty array e.g.: def get_queryset(self): queryset = [] queryset.append(Post.objects.get(title=self.kwargs["title"])) return queryset How could I return an object like this from Class-based views?: { "status": 200, "message": "Post created!", "data": {} } Thank you -
Requests download to media server in django
I have this module that I imported into django. It uses request to download files from specific urls. This works well given that the host is my system. If I move to a server, this would mean the files would get downloaded to the server and that is not efficient or good at all. How can I use this module to download and automatically upload to media server or better still, download directly to the media server and from there, serve it up to user to download. This is the script's code def download_course_file(self, course): username = self._login_data["username"] p = Path(f"{username}-{course}.txt").exists() if not p: self.get_download_links(course) statime = time.time() with open(f"{username}-{course}.txt", "r") as course_link: data = course_link.read().splitlines(False)[::2] p.map(self.download, data) def download(self, url): response = self._is_downloadable(url) if response: name = response.headers.get('content-disposition') fname = re.findall('filename=(.+)', name) if len(fname) != 0: filename = fname[0] filename = filename.replace("\"", "") print(filename) else : filename = "Lecture note" with open(filename, 'wb') as files: for chunk in response.iter_content(100000): files.write(chunk) I omitted the self._is_downloadable() logic since it doesn't apply here def download_course(request, id): course = course = get_object_or_404(Course, id=id) course_name = (course.course_name)[:6] person, error = create_session(request) if "invalid" in error: data = {"error":error} return JsonResponse(data) person.download_course_file(course_name) data = {"success":"Your … -
Deploying a Django App to GitHub - Landing page isn't being displayed
I'm trying to deploy my Django application on github. Files have been uploaded successfully, the url works fine, but when I go the site https://qasim-khan1.github.io/blog/ It doesn't direct me to my landing page. It shows nothing, simply 'Blog' written in bold text. -
How to add correctly add JSONField to RegisterSerializer in Django?
I'm building a web app at the moment that lets people build pages. These pages should be stored as JSON in my Postgres Database. I've implemented a customer user manager/model in Django: from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.postgres.fields import JSONField class UserManager(BaseUserManager): def create_user( self, email, page, username, password=None, commit=True): """ Creates and saves a User with the given email, first name, last name and password. """ if not email: raise ValueError(_('Users must have an email address')) user = self.model( email=self.normalize_email(email), username=username, page=page ) user.set_password(password) if commit: user.save(using=self._db) return user def create_superuser(self, email, username, password, page=None): """ Creates and saves a superuser with the given email, first name, last name and password. """ user = self.create_user( email, password=password, username=username, commit=False, ) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name=_('email address'), max_length=255, unique=True ) # password field supplied by AbstractBaseUser # last_login field supplied by AbstractBaseUser username = models.CharField( max_length=30, blank=True, unique=True) page = JSONField(default=dict) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of … -
Django - making API call with user input
I'm creating a Django webapp where the user will input a zip code then the page will display a list of establishments in that area using the Yelp API. homepage.html <form method="GET" action="{% url 'homepage' %}"> {% csrf_token %} <label>Zip Code: </label> <input name="zip_code"> <button type="submit">Submit</button> </form> yelp.py def get_name(location): """ makes call to Yelp API and returns list of establishments within the given zip code """ restaurants = [] url = 'https://api.yelp.com/v3/businesses/search' params = { 'location': f'{location}' } headers = {'Authorization': f'Bearer {YELP_KEY}'} response = requests.get(url, params=params, headers=headers).json() for business in response['businesses']: restaurants.append(business['name']) return restaurants I'm super new to this so I'm unsure how to take the input from homepage.html and use it to make the API call in yelp.py. I know there are Views and Models and Forms, I'm just confused what each of them do and how to use them in this scenario. Let me know if there's more info I can provide. -
How to setup uWSGI vassal names for better log reference?
INFO: Framweork: Django 2.X < 3.x ; Services: supervisord; uWSGI Host: CentOS Linux 7 Hello, i am currently testing how to deploy multiple django apps with uWSGI on my host. I set everything up based on manuals provided by my Host & uWsgi and it works. However i would like to customized everything a bit further, so that i can understand everything a bit better. As far as i understand my uWSGI service uwsgi.ini currently works in an emperor mode and provides vassals for my two different app named baron_app.ini and prince_app.ini to handle my different apps. Question I noticed that the err.log is a kind of confusing for debugging with multiple apps. for instance... announcing my loyalty to the Emperor... Sat May 2 21:37:58 2020 - [emperor] vassal baron_app.ini is now loyal.... [pid: 26852|app: 0|req: 2/2]..... Question: Is there a way to give my vassals a name so that it will printed in the Log ? Or a way to tell uWSGI to set some kind of process & app log relation (Emperor - Vassals - Worker etc.) in the Log? For instance i could imagine something like this, could be easier when it comes to find errors. #baron_app: … -
TypeError: 'list' object is not callable | DRF exception handling
I am trying to parse Django model ValidationError into DRF ValidationError. But I keep getting the following output: TypeError: 'list' object is not callable Here is my custom exception handler: import logging from django.core.exceptions import ValidationError as DjangoValidationError from rest_framework.exceptions import ValidationError LOG = logging.getLogger(__name__) def transform_exception(exception): """Transform model validation errors into an equivalent \ DRF ValidationError. After reading the references, you may decide not to use this. References: https://www.kye.id.au/blog/understanding-django-rest-framework-model-full-clean/ https://www.dabapps.com/blog/django-models-and-encapsulation/ """ if isinstance(exception, DjangoValidationError): if hasattr(exception, "message_dict"): detail = exception.message_dict elif hasattr(exception, "message"): detail = exception.message elif hasattr(exception, "messages"): detail = exception.messages else: LOG.error("BAD VALIDATION MESSAGE: %s", exception) exception = ValidationError(detail=detail) return exception And here is my error log: Server Logs Where am I going wrong? -
For development purpose, how can I open a Django Jinjia2 template in browser with preliminary rendering (extending, including)?
Problem description I am starting working on a Django project and the server-side rendering template is a little hard to work with. Usually I develop the front-end application with hot module reload server so that I can see the rendered page during development. However, for Django project I can only view the site by serving and open from browser. If I open the template directly, the include, extends are not processed, hence CSS and JavaScript are not loaded in the base template. My question is, is there any tool or workflow that can help develop the Django template in offline so that the style and layout can be rendered properly during development? Thank you -
how get longitude and latitude of users geodjango
i'm new to geodjango i want to make real world gis project with geodjango to find locations i tried this class Place(models.Model): user= models.ForeignKey(Account,on_delete=models.CASCADE) address = models.CharField(max_length=100) slug = models.SlugField(unique=True,blank=True,null=True) description = models.TextField() location = models.PointField(srid=4326) views.py class PalceCreateApiView(CreateAPIView): queryset = Place.objects.all() serializer_class = PlaceCreateSerializer def perform_create(self,serializer): address = serializer.initial_data['address'] g = geocoder.google(address) lat = g.latlng[0] lon = g.latlng[1] point = f'POINT({lat} {lon})' serializer.save(user=self.request.user,location=point) but i want to get exact location ,because sometimes the user cant write the same address name , so the coordiantes been wrong how to access users location then assign to location field thanks i'm new to geodjango if someone can recommend me an open source project i appreciate it -
trying to submit a view and getting 405 error
I'm trying to implement a review section in a user profile but I keep getting this 405 error when i try to submit a review even tho when i create a review in the admin panel it shows on the profile normaly. if you could help. Thanks in advance Code: Model class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) expert = models.ForeignKey(Expert, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField() Form class ReviewForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={ 'rows':3, })) class Meta: model = Review fields = ('content',) View class ExpertDetailView(DetailView): model = Expert def expert(self, *args, **kwargs): form = ReviewForm(self.request.POST) if form.is_valid(): expert = self.get_object() review = form.instance review.user = self.request.user review.expert = expert review.save() print ('worked') print ('worked') def get_object(self, **kwargs): object = super().get_object(**kwargs) return object def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'form': ReviewForm() }) return context And finaly the Template <h4>Leave a comment below</h4> <form method='POST'> {% csrf_token %} {{ form|crispy}} <br> <button class='btn btn-primary' type='submit'>review</button> </form> <hr /> <h5>Comments</h5> {% for review in object.reviews %} <div> <p>{{ review.content }} <br /> <small>{{ review.timestamp|timesince }} ago</small> </div> <hr /> {% endfor %} -
orderin en el models de django no me devuelve el template de forma correcta
tengo un frontend que muestra cuadros de servicios de esta formaimagen del diseño original pero en el momento de hacer runserver se me muestra tipo cascada y no como tabla. como en el diseño original. diseño de lo que me devuelve el admin class Post(models.Model): title = models.CharField(max_length=200, verbose_name='Titulo') content = models.TextField(verbose_name='Contenido') image = models.ImageField(verbose_name='Imagen', upload_to='Projects') created = models.DateTimeField(auto_now_add='True', verbose_name="Fecha de creacion") updated = models.DateTimeField(auto_now='True', verbose_name="Fecha de edicion") class Meta: verbose_name = "Entrada" verbose_name_plural = "Entradas" ordering = ['created'] def __str__(self): return self.title ahora tengo el template asi. {% for projects in projects %} <div class="fullwidth-block"> <div class="container"> <div class="project-list"> <div class="project"> <div class="project-content"> <figure class="project-image"><img src="{{projects.image.url}}" alt=""></figure> <h3 class="project-title">{{projects.title}}</h3> <p>{{projects.content}}</p> <a href="project.html" class="button">Learn more</a> </div> </div> </div> </div> </div> </main> <!-- .main-content --> {% endfor %} como hago para que respete el diseño original de estilo tabla. gracias -
how can i solve this urls in Django
here is the code of my project url: from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('',include('calculator.urls')), path('admin/', admin.site.urls), ] here is the code of my app url: from django.urls import path from . import views urlpartterns = [ path('',views.Courses, name='home-page') ] code for views.py: from django.shortcuts import render from django.http import HttpResponse def Courses(request): return HttpResponse('Hello world') enter image description here Error: django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Django: Operate on User Input
I have created a django model with a Decimal field. I would like to make it so that when the user inputs a number, the value that is saved is multiplied by 2. I have tried updating the sqlite database with the python sqlite module but gave up after a while. Any ideas on how I can maybe use managers or something of the sort? -
grepelli issue with autocomplete_search_fields
class Billing1500(models.Model): Practice = models.ForeignKey('DemoPractice', on_delete=models.CASCADE) Provider = models.ForeignKey('DemoProvider', on_delete=models.CASCADE) PatiName = models.CharField(max_length=255, null=True, blank=True, help_text='Last Name, First Name') PatiDOB = models.CharField(max_length=255, null=True, blank=True) PatiSex = models.CharField(max_length=255, null=True, blank=True) ICD1 = models.CharField(max_length=8, null=True, blank=True) ICD2 = models.CharField(max_length=8, null=True, blank=True) ICD3 = models.CharField(max_length=8, null=True, blank=True) ICD4 = models.CharField(max_length=8, null=True, blank=True) ICD5 = models.CharField(max_length=8, null=True, blank=True) ICD6 = models.CharField(max_length=8, null=True, blank=True) ICD7 = models.CharField(max_length=8, null=True, blank=True) ICD8 = models.CharField(max_length=8, null=True, blank=True) ICD9 = models.CharField(max_length=8, null=True, blank=True) ICD10 = models.CharField(max_length=8, null=True, blank=True) ICD11 = models.CharField(max_length=8, null=True, blank=True) ICD12 = models.CharField(max_length=8, null=True, blank=True) CPT1 = models.CharField(max_length=8, null=True, blank=True) CPT6 = models.CharField(max_length=8, null=True, blank=True) @staticmethod def autocomplete_search_fields(): return ("Provider_icontains", ) @admin.register(Billing1500) class Billing1500(admin.ModelAdmin): raw_id_fields = ('Provider',) autocomplete_lookup_fields = { 'fk': ['Provider'], } class Media: js = ( 'js/admin/bootstrap.bundle.js', 'js/admin/bootstrap.js', ) css = { 'all': ( 'css/admin/bootstrap.css', 'css/admin/bootstrap-grid.css', 'css/admin/bootstrap-reboot.css', ) } pass i'm trying to have autocomplete search fields in my grapellie admin models, however im getting errors when trying to bind my foreignkeys to my grappelli function. i'm having the following issue ERRORS: ?: (grappelli.E001) Model Core.billing1500 returned bad entries for autocomplete_search_fields: Provider_icontains HINT: A QuerySet for {model} could not be constructed. Fix the autocomplete_search_fields on it to return valid lookups. reading the docs it …