Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to migrate to Posgresql?
return self.cursor.execute(sql) django.db.utils.DataError: NUMERIC precision 10440 must be between 1 and 1000 LINE 1: ...RIMARY KEY, "item" varchar(100) NOT NULL, "price" numeric(10... ^ -
Django WebRTC TURN/STUN/ICE Server
So I have a basic question about WebRTC with Python Django. Maybe I start at the beginning: So is it possible that Python Django can serve as a Server for WebRTC? I think in generell it shouldn't be that hard, because how I saw the WebRTC client only needs a Websocket connection. I hope anybody can help me with that. Btw. I use Django Channels, so I think it is possible to build this connection, but how? :) -
The django field to save the file path with id and show nonevideo.mp4 in the file extension
I tried to save the video file with id of the video but it show none instead of id and the file extension be like nonevideoauthor.mp4 my file extension in the video model def get_video_filepath(self, filename): return 'post-videos/' + str(self.id) + str(self.author) + 'video.mp4' the video model class Video(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) video = models.FileField(upload_to=get_video_filepath, validators=[validate_file_extension, validate_file_size]) -
How do I overcome this login page error from a downloaded template for Django
I wanted to test out a template and see all of its components (models, initial, migrate etc.) When I run python migrate.py runserver, I am taken to the login/ sign up page that is probably setup by the designers of the template. I cannot really seem to sign up with any details, since I get this error: OperationalError at /register/ no such table: auth_user Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 3.1.5 Exception Type: OperationalError Exception Value: no such table: auth_user Exception Location: C:\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute Python Executable: C:\Python39\python.exe Python Version: 3.9.0 Python Path: ['C:\Users\puru1\Downloads\django-datta-able-master\django-datta-able-master', 'C:\Python39\python39.zip', 'C:\Python39\DLLs', 'C:\Python39\lib', 'C:\Python39', 'C:\Users\puru1\AppData\Roaming\Python\Python39\site-packages', 'C:\Python39\lib\site-packages', 'C:\Python39\lib\site-packages\win32', 'C:\Python39\lib\site-packages\win32\lib', 'C:\Python39\lib\site-packages\Pythonwin'] Server time: Sat, 03 Apr 2021 22:35:54 +0000 Traceback Switch to copy-and-paste view C:\Python39\lib\site-packages\django\db\backends\utils.py, line 84, in _execute return self.cursor.execute(sql, params) … ▶ Local vars C:\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute return Database.Cursor.execute(self, query, params) … ▶ Local vars I have attached an image showing the files that the folder contains, as seen in visual studio code What part do I have to delete to just be able to view the webpage without going through the login page? Thanks! -
Manager isn't available; 'auth.User' has been swapped for 'accounts.User'
This is my first time customizing User, the app is working ok, I can edit user fields, sign up, sign in, visit the dashboard. However, when I want to visit another user I'm getting this error: AttributeError at /account/dashboard/10/ Any help on how to resolve this is more than welcome, thank you! urls: path('account/dashboard/', dashboard, name = 'dashboard'), path('account/dashboard/<pk>/', guest_dashboard, name = 'guest_user'), view: #Guest Dashboard @login_required def guest_dashboard(request, pk): user_other = User.objects.get(pk = pk) already_followed = Follow.objects.filter(follower = request.user, following = user_other) if guest_dashboard == request.user: return HttpResponseRedirect(reverse('dashboard')) return render(request, 'account/dashboard-guest.html', context = {'user_other' : user_other, 'already_followed' : already_followed}) settings: AUTH_USER_MODEL = "accounts.User" models: class MyUserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser Must have is_staff = True') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser Must have is_superuser = True') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null = False) username = models.CharField(max_length=264, null = True, blank = True) is_staff = models.BooleanField(ugettext_lazy('Staff'), default = False, help_text = ugettext_lazy('Designates whenever the … -
When I try to fetch data to a url with {% url %} for implementing PayPal checkout, urls are not found. Why?
I am implementing PayPal checkout for my website using Django, and having some trouble with url. Once the payment is complete I want to fetch data to 'payment_complete' view and then send the customer to 'payment_successful' page. But it does not work. The urls 'payment_complete' and 'payment_successful' are not found. Do you know why ? Thank you for your help. checkout.html {% extends 'main.html' %} {% load static %} {% block title %} Checkout {% endblock title %} {% block content %} <div> <div id = "proceed-to-payment-div"> <div id="paypal-button-container"></div> </div> </div> <script src="https://www.paypal.com/sdk/js?client-id=Ac7c5n8LPoPfEjQjK-PlndbIoLLYm5t5z7Pw8YSPVhMtpU5PJDLmjDxDXO5sYZGl4sBNX-AdgjbGxOuv&currency=EUR" ></script> <script type="text/javascript"> var basket_total = '{{basket.get_total_price}}'; console.log(basket_total); </script> <script type="text/javascript" src=" {% static 'js/payment/checkout-paypal.js' %} "></script> {% endblock content %} checkout-paypal.js function initPayPalButton() { paypal.Buttons({ style:{ color:'white', shape:'rect', size:'responsive' }, createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: parseFloat(basket_total).toFixed(2) } }] }); }, onApprove: function(data) { var url = "{% url 'payment:payment_complete' %}" return fetch(url, { method:'POST', headers: { 'content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ orderID: data.orderID }) }).then(function () { location.href = "{% url 'payment:payment_successful' %}"; }); }, }).render('#paypal-button-container'); }; initPayPalButton(); urls.py (core of the website) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static … -
React Router redirects to BASE_URL when I try to load a page in a new tab
I have been working on a react project and I ran into a problem about 4 days ago. When I try to open a link in a new tab, it redirects to the home/BASE url. Please I need assistance fixing the bug. render route method export const renderRoutes = (routes = []) => ( <Suspense fallback={<Loader />}> <Switch> {routes.map((route, i) => { const Guard = route.guard || Fragment; const Layout = route.layout || Fragment; const Component = route.component; return ( <Route key={i} path={route.path} exact={route.exact} render={(props) => ( <Guard> <Layout> {route.routes ? renderRoutes(route.routes) : <Component {...props} />} </Layout> </Guard> )} /> ); })} </Switch> </Suspense> ); GuestGuard const GuestGuard = (props) => { console.log(props, BASE_URL) if (props.isLoggedIn) { console.log(BASE_URL) return <Redirect to={BASE_URL} />; } return ( <React.Fragment> {props.children} </React.Fragment> ); }; GuestGuard.propTypes = { isLoggedIn: PropTypes.bool.isRequired } const mapStateToProps = (state) => ({ isLoggedIn: state.auth.isLoggedIn }) export default connect(mapStateToProps, )(GuestGuard); AuthGuard const AuthGuard = ({ children, isLoggedIn }) => { // console.log(children, 393) if (!isLoggedIn) { return <Redirect to="/auth/signin-1" />; } console.log("LOGGED IN", children.props) return ( <React.Fragment> {children} </React.Fragment> ); }; AuthGuard.propTypes = { isLoggedIn: PropTypes.bool.isRequired } const mapStateToProps = (state) => ({ isLoggedIn: state.auth.isLoggedIn }) export default connect(mapStateToProps, )(AuthGuard); App … -
Azure Web App - Python: can't open file 'manage.py': [Errno 0] No error
I am trying to deploy my Django application with Azure DevOps as a Azure Web App. The application is pipelined and build to the web app but it will not run. When I am trying to run py manage.py runserver in the Diagnostic Console i get the error below: D:\Python34\python.exe: can't open file 'manage.py': [Errno 0] No error Does anyone have a clue on what the issue might be? This is the first project I am trying to deploy with Azure so my knownledge is not very good. The project files are stored on the following location on the server D:\home\site\wwwroot\<applicationName> Thank you for your help. -
Django How to Add Custom Location Field?
In my profile model I want to hold country or city, country values in custom location field. Also country value must be provided. So I made a LocationField which implements MultiValueField. I'm not advanced at Django, so how can I make only country required? Also I'm not sure this code is totally right. P.S: I can make city and country fields in Profile but holding in them in one field seems more neat. models.py from cities_light.models import City, Country class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') first_name = models.CharField(verbose_name='first name', max_length=10, null=False, blank=False, default='baris') last_name = models.CharField(verbose_name='last name', max_length=10, null=False, blank=False, default='baris') profile_photo = models.ImageField(verbose_name='profile photo', ) #TODO add upload to about = models.CharField(verbose_name='about', max_length=255, null=True, blank=True) spoken_languages = models.CharField(verbose_name='spoken languages', max_length=255, null=True, blank=True) location = LocationField() class LocationField(MultiValueField): def __init__(self, **kwargs): fields = ( Country(), City() ) super.__init__(fields=fields, require_all_fields=False, **kwargs) -
BSModalDeleteView (django-bootstrap-modal-form) ignors get_success_url
My BSModalDeleteView is just ignoring what I have entered into my get_success_url(self). Whatever I try, I'll be redirected to the url of the deleted element (http://127.0.0.1:8000/rentals/part/delete/34/) which leads logically to an error since the object was just deleted. Has anybody an idea of what is wrong? Everything works as expected (the reverse_lazy provides the expected url) views.py class ConstituentPartsDeleteView(LoginRequiredMixin, BSModalDeleteView): model = ConstituentParts success_message = 'Part deleted.' template_name = 'modal_delete.html' def get_success_url(self): return reverse_lazy('rentals:rental', kwargs={'pk': self.object.rental_unit.pk, 'tab': 'home'}) There is no get_abslute_url() in this model. Here is how it is called in the template script block: $(".bs-modal-part").each(function () { $(this).modalForm({ formURL: $(this).data('part-url'), isDeleteForm: true, }); }); Thank you in advance. -
How to send JSON to Django URL using AJAX? [duplicate]
I have the following data: data = [ { "topics": [ "2.12", "2.13", "2.14", "2.15", "2.16", "2.17", "2.18", "2.19" ] }, { "filters": "[{"QType_id":"1","QSubType_id":"6","QCount":"10"}]" } ] I want to send it to Django URL. I tried the following java code: jQuery.ajax( { 'type': 'POST', 'url': "http://127.0.0.1:8001/recievejson", 'contentType': 'application/json', 'data': [ { "topics": [ "2.12", "2.13", "2.14", "2.15", "2.16", "2.17", "2.18", "2.19" ] }, { "filters": "[{"QType_id":"1","QSubType_id":"6","QCount":"10"}]" } ], 'dataType': 'json', 'success': "" } ); The following is django function to receive that request: def recievejson(request): if request.method == 'POST': print("SUCCESS") for key, value in request.POST.items(): print(key, value) return JsonResponse({"status": 'Success'}) I get nothing on receiving end Any recommended solution? -
Why cant i change the error_message of a form in Django?
class Rezervaciaform(forms.Form): keresztnev=forms.CharField(label="Meno:",error_messages={'required': 'Prosim vyplnte'},validators[validators.MinLengthValidator(2,'Prosim podajte cele meno')]) #the validator shows up,but the error_message doesnt change -
'Custom user with this Email address already exists' error when trying to update email using forms. Django
please read through my code, my question with screenshots and things i've already tried are after my code. managers.py: from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_feilds): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_feilds) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_feilds): extra_feilds.setdefault('is_staff', True) extra_feilds.setdefault('is_superuser', True) extra_feilds.setdefault('is_active', True) if extra_feilds.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff = True')) if extra_feilds.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True')) return self.create_user(email, password, **extra_feilds) models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser, StripeConnectSetup from django import forms class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('email', 'first_name', 'last_name') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('email','first_name', 'last_name') views.py from django.shortcuts import render, redirect from .forms import CustomUserCreationForm, CustomUserChangeForm, StripeConnectSetupForm from .models import CustomUser from django.contrib.auth import login, logout from … -
how can i get the nearest prods depending on user's location?
i'm using geodjango .. i Installed Python 3 then GeoDjango Dependencies (GEOS, GDAL, and PROJ.4) , of course i had Set up a Spatial Database With PostgreSQL and PostGIS i want to get the nearest prods to my user's location ..this is the model class Prod(models.Model): userr = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) name_business = models.ForeignKey(Page, on_delete=models.CASCADE, null=True, blank=True) description = models.CharField(max_length=5000, default="") disponibilite = models.BooleanField(default=True) prix = models.DecimalField(decimal_places=2, max_digits=10, null=True, blank=True) Title = models.CharField(max_length=5000, default="") quantité = models.CharField(max_length=1000, default="") date_posted = models.DateTimeField(default=timezone.now) principal_image = models.FileField(blank=True) location = models.PointField(null=True,default=Point(0.0,0.0)) def __str__(self): return str(self.Title) class User(AbstractUser): geo_location = models.PointField(null=True,default=Point(0.0,0.0)) class Meta: db_table = 'auth_user' -
Django forms User form not summited
I need help with my code. I have read through the code several times and I didn't see anything wrong with it. The user is expected to submit a job application and redirect the user to the dashboard, but it did not submit the job application neither does it direct the user to the dashboard. here is my code: mode.py from django.db import models from django.contrib.auth.models import User class Job(models.Model): title = models.CharField(max_length=255) short_description = models.TextField() long_description = models.TextField(blank=True, null=True) created_by = models.ForeignKey(User, related_name='jobs', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) changed_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Application(models.Model): job = models.ForeignKey(Job, related_name='applications', on_delete=models.CASCADE) content = models.TextField() experience = models.TextField() created_by = models.ForeignKey(User, related_name='applications', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) Views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import AddJobForm, ApplicationForm from .models import Job def job_detail(request, job_id): job = Job.objects.get(pk=job_id) return render(request, 'jobs/job_detail.html', {'job': job}) @login_required def add_job(request): if request.method == 'POST': form = AddJobForm(request.POST) if form.is_valid(): job = form.save(commit=False) job.created_by = request.user job.save() return redirect('dashboard') else: form = AddJobForm() return render(request, 'jobs/add_job.html', {'form': form}) @login_required def apply_for_job(request, job_id): job = Job.objects.get(pk=job_id) if request.method == 'POST': form = ApplicationForm(request.POST) if form.is_valid(): application = form.save(commit=False) application.job = job application.created_by = … -
How to make Django Form repeatedly submit in background while user is filling it in?
Background information about my project: I'm building a CV/Resume generator that automatically creates a CV/Resume based on the user filling out a form. I'm using a Django Crispy Form which has a submit button at the end that, when clicked, submits the user's input to a SQL database and redirects the user to their newly built CV/Resume (as a PDF). What I need help with: The goal is to have a form on the left side of the screen and a live view (HTML/CSS) of the CV/Resume on the right side, where the live view updates as the user is filling out the form. I've seen this kind of thing before, but never for a Django project (they tend to use JavaScript/React). What I'm thinking: Could I have a background process that does something like, when the user makes a change (e.g. is filling out the form), submit any new inputs to the SQL database every 5 seconds? Then the live view can extract any new inputs from the database and display it in real time? -
Hi! I'm not able to connect with "heroku redis" on django
I've followed all the steps in the following video: https://www.youtube.com/watch?v=fvYo6LBZUh8&t=166s However, I'm not able to connect with "heroku redis", I am using celery to implement periodic tasks. The error is the following: [2021-04-02 22:00:05,622: ERROR/MainProcess] consumer: Cannot connect to redis://:**@ec2-54-160-13-161.compute-1.amazonaws.com:12880//: Error while reading from socket: (10054, 'Se ha forzado la interrupción de una conexión existente por el host remoto', None, 10054, None). So, any idea of what could be happening would be great. ¡Thank you so much! -
How can I fetch attributes from User model using UserProfile's OneToOneField relationship?
I'd love to write a form where a user can change their data. So I have a User model and a UserProfile extension model, the last one looks like this: from django.db import models from django.contrib.auth.models import User from django.urls import reverse class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) info = models.TextField('информация') def get_absolute_url(self): return reverse('user_profile', args=[str(self.user.username)]) How to generate a form where my user attribute would have all its parameters like username, email, first_name, last_name to be changed? So I could do something like this in the template: {% extends "layout.html" %} {% block content %} <h2>{{ title }}</h2> <div class="row"> <form method="POST" action="{% url 'profile_edit' user.username %}" class="col s12"> {% csrf_token %} {{ form.non_field_errors }} <div class="row"> <div class="input-field col s6"> {{ form.user.username }} {{ form.user.username.label_tag }} {% if form.user.username.errors %} <span class="helper-text">{{ form.user.username.errors }}</span> {% else %} <span class="helper-text">{{ form.user.username.help_text }}</span> {% endif %} </div> <div class="input-field col s6"> {{ form.user.email }} {{ form.user.email.label_tag }} {% if form.user.email.errors %} <span class="helper-text">{{ form.user.email.errors }}</span> {% else %} <span class="helper-text">{{ form.user.email.help_text }}</span> {% endif %} </div> </div> <div class="row"> <div class="input-field col s6"> {{ form.user.first_name }} {{ form.user.first_name.label_tag }} </div> <div class="input-field col s6"> {{ form.user.last_name }} {{ form.user.last_name.label_tag }} … -
how to display mapbox location in django template?
i created a django mapbox app my models.py class is : class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL ,blank=True,null=True) location2 = LocationField(map_attrs={"center": [51.42151,35.69439], "marker_color": "blue"},null=True, blank=True) and this is my views.py : def profile_page(request,id,slug): user_id=request.user.id profile = get_object_or_404(Profile,id=id,slug=slug) post = Post.objects.filter(profile=profile) mapbox_access_token = 'pk.eyJ1IjoibWlzdGVyZmgiLCJhIjoiY2tteHNmcjllMHJ4OTJwJ3-SkFRpWJtDDDwfrpg' context={ 'profile': profile, 'mapbox_access_token': mapbox_access_token } return render(request,'profile_page.html',context) and this is templates: <div class="col-12 col-xl-12 pr-0 pr-md-4 "> {{ profile.location2 }} <div class="border" id="map" width="100%" style='height:400px'></div> </div> <script> mapboxgl.accessToken = {{ mapbox_access_token }}; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v10', center: [35.69439, 51.42151], zoom: 9, // bearing: 180 }); </script> mapbox location {{ profile.location }} shows like this (46.30637816268069, 38.065254395567706) in template but graphical mapbox doent show in template -
ModelChoiceField on django-filter
I created a django-filter class to use on my dashboard, but the ModelChoiceField dropdown is showing all 'colocador' objects and not just those that is related to the current user Colocador is a user profile that is related to another user profile on class Colocador(models.Model): user = models.OneToOneField( MyUser, on_delete=models.CASCADE, primary_key=True) work_for = models.ForeignKey(Dono, models.CASCADE, blank=True, null=True) I have a model like this class Venda(models.Model): name = models.CharField(max_length=50, verbose_name='Nome') colocador = models.ForeignKey( Colocador, on_delete=models.CASCADE, verbose_name="Colocador") And in my filters.py class VendaFilter(django_filters.FilterSet): foo colocador = django_filters.ModelChoiceFilter( queryset=Colocador.objects.filter(work_for=3)) class Meta: model = Venda fields = ['search', 'status', 'colocador'] I hardcoded the work_for to 3 but obviously I don't want a hardcoded value, I already passing the actual user and tried this but doesn't work class VendaFilter(django_filters.FilterSet): search = django_filters.CharFilter( method='search_filter', label='Procurar') # colocador = django_filters.ModelChoiceFilter( # queryset=Colocador.objects.filter(work_for=3)) class Meta: model = Venda fields = ['search', 'status', 'colocador'] def search_filter(self, queryset, name, value): return Venda.objects.filter( Q(name__icontains=value) | Q(phone_number__icontains=value) | Q( cpf__icontains=value) | Q(rg__icontains=value), colocador__in=self.colocadores) def __init__(self, user, *args, **kwargs): super(VendaFilter, self).__init__(*args, **kwargs) self.colocadores = Colocador.objects.filter(work_for=user) self.filters['colocador'] = django_filters.ModelChoiceFilter( queryset=Colocador.objects.filter(work_for=user)) The dropdown is showing just the objects that are related to user, but when I submit the filter raise this error raise FieldError("Cannot resolve … -
Import Issue With django.views
everyone. I'm working with a small team to create a python project with Django and Vue implemented. We're having troubles with our import statements and having PyCharm recognize the file path. from django.views import views as vue_views This particular line of code is what's causing the problem. Pycharm keeps telling us "Cannot find reference 'views' in 'init.py' ". When we run the django server, the console will tell us "ImportError: cannot import name 'views' from 'django.views' (C:\Users\myusername\AppData\Roaming\Python\Python39\site-packages\django\views_init_.py)". The project will work fine on one of my coworkers machines but gives us these errors when any of us pull it from git. This leads us to believe it has something to do with our interpreter or something like that. Any help would be appreciated. Thanks in advance! -
How to list MultiChoiceField results one by one in Django?
I have multi choice model. I want to display it in the template one by one and not all at once. Like i want to list them in my template one by one in a good position. how do i separate multichoicefield display results ? views.py def car_detail(request, id): single_car = get_object_or_404(Car, pk=id) data = { 'single_car': single_car, } return render(request, 'cars/car_detail.html', data) models.py features_choices = ( ('Sürücü Hava Yastığı', 'Sürücü Hava Yastığı'), ('Eba (ani Fren Desteği )', 'Eba (ani Fren Desteği )'), ('Hırsızlığı Önleyici Alarm Sistemi', 'Hırsızlığı Önleyici Alarm Sistemi'), ('Sürücü Yan Hava Yastığı', 'Sürücü Yan Hava Yastığı'), ('Ön Yolcu Hava Yastığı', 'Ön Yolcu Hava Yastığı'), ('Arka Ses Ötesi Park Radar Sistemi', 'Arka Ses Ötesi Park Radar Sistemi'), ('İmmobilizer', 'İmmobilizer'), ('Dstc (dinamik Denge Ve Çekiş Kontrol Sistemi)', 'Dstc (dinamik Denge Ve Çekiş Kontrol Sistemi)'), ('Şerit Değiştirme Asistanı', 'Şerit Değiştirme Asistanı'), ('Kör Nokta Sensörü', 'Kör Nokta Sensörü'), ('Ön Yolcu Yan Hava Yastığı', 'Ön Yolcu Yan Hava Yastığı'), ('Ön Emniyet Kemerini Bağla Sinyali', 'Ön Emniyet Kemerini Bağla Sinyali'), ('Deri Kaplama El Freni', 'Deri Kaplama El Freni'), ('Yol Bilgisayarı', 'Yol Bilgisayarı'), ('Navigasyon Sistemi', 'Navigasyon Sistemi'), ('Uzun Far Asistanı', 'Uzun Far Asistanı'), ('Merkezi Kilit', 'Merkezi Kilit'), ('Yağmur Sensörü', 'Yağmur Sensörü'), ('Usb Bağlantısı', 'Usb … -
how to center a bootstrap div image vertically and horizontally
before you downvote and close the topic, hear me out please. I DID CHECK OUT every single stackoverflow question on this exact topic. I did try every single approach and yet nothing's working. It may take you a few seconds to help me solve this, but I am struggling for over 3 hours on this exact thing. Here's the problem. My web app runs on django and I'm currently working on the front-end. It looks like this at the moment. I'm trying to get the 3 pictures centered both horizontally and vertically into some reasonable size into the middle of the page. I want it to be responsive. This is a home page for a logged category of HOST, when logged as TENANT, he has only 2 pictures there, which I want to have centered as well relative to the window size. Here is my html with a bit of django logic: {% extends 'milk_app/base.html' %} {% load static %} <!DOCTYPE html> {% block title_block %} Homepage {% endblock %} {% block body_block %} <!-- Home page for Hosts --> {% if user.userprofile.account == "Host" %} <div class="container"> <div class="row"> <!-- Scroll other properties --> <div class="center-block col-4"> <a href="{% … -
Django model-form-view connection
I am trying to scrap datas from a website. Here is my models.py ` from django.db import models from .utils import get_link_data from .forms import AddLinkForm class Link(models.Model): name = models.CharField(max_length=500, blank=True) price = models.CharField(max_length=20, blank=True) image = models.CharField(max_length=1000, blank=True) def __str__(self): return str(self.name) def save(self, *args, **kwargs): name, price, image = get_link_data(AddLinkForm.url) self.name = name self.price = price self.image = image super().save(*args, **kwargs) And here is my forms.py from django import forms class AddLinkForm(forms.Form): url = forms.URLField() And my views.py: from django.shortcuts import render from .models import Link from django.views.generic import DetailView from .forms import AddLinkForm def home_view(request): form = AddLinkForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.save() form = AddLinkForm() qs = Link.objects.all() items_no = qs.count() context = { 'qs': qs, 'items_no': items_no, 'form': form, } return render(request, 'links/main.html', context) class ProductDetailView(DetailView): model = Link template_name = 'links/details.html' ` I have to change form.save() I guess, but how will I save the form after I change it and get the url from view? I dont want 'url' in my db so I didnt add it to my model. -
how to substitue models.permalink depracted code in Django?
I am reading the book Beginning Django E-Commerece that describes how to build a webshop using Django. In one of the code example that I am following the author is setting up a product model that looks as below. Here he used a decorator models.permalink followed by get_absolute_url. From the documentation, I learned models.permalink is depracted. How should I adapt the below code for my current Django 3.1.3 version? Also can somebody explain to me what models.permalink actually does? In particular what does @models.permalink def get_absolute_url(self): return ("catalog_product", (), {'product_slug' : self.slug}) intend to do? from django.db import models from django.db.models.fields.related import create_many_to_many_intermediary_model class Product(models.Model): name = models.CharField(max_length = 50, unique=True) description = models.TextField() allergic_note = models.CharField(max_length = 255) quantity = models.IntegerField(null = True, blank = True) #Used for campaign products to show how many items there is left price = models.DecimalField(max_digits=9, decimal_places=0, default=0.00) is_active = models.BooleanField(default = True) is_deliverable = models.BooleanField(default = True) image_path = models.CharField(max_length = 255) meta_keywords = models.CharField(max_length=255, help_text="comma delimited keywords text for SEO") meta_description = models.CharField(max_length=255, help_text="SEO description content") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=255, unique = True, help_text="Unique text for url created from name") is_featured = models.BooleanField(default = False) is_bestseller = …