Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django: TypeError: join() argument must be str, bytes, or os.PathLike object, not 'dict'
Based on the following question and answer (How do I display the console output to HTML in Django?), I'm trying to get the console to display in a HTML window. However, I'm running into the error: "TypeError: join() argument must be str, bytes, or os.PathLike object, not 'dict'" This is the problematic code: import subprocess import os from django.shortcuts import render def Deploy(home, staging_folder): output = "" os.chdir(staging_folder) script = home + '/webscripts/terraformdeploy.py' try: output = subprocess.check_output(['python', script], shell=True) except subprocess.CalledProcessError: exit_code, error_msg = output.returncode, output.output os.chdir(home) return render('projectprogress.html', locals()) I thought "locals()" was the offending part. I then tried: return render('projectprogress.html', output) But that also gave the same error message, so it seems to be a problem with the output subprocess variable. According to the other question, this solution worked, so I'm not entirely sure why it's not working in this instance. Any help would be greatly appreciated! -
Selecting name of the excel sheet while loading an excel file with tablib
I have an excel file to load with 4 sheets. I want to load a specific sheet from. How can I choose the name of the sheet? This doesn't help. I can't choose a specific sheet. imported_data= dataset.load(file.read( ), format= 'xlsx') -
How to convert decimal numbers stored as JSON into decimal with Django?
I store Decimal numbers in JSONField with Django in order to have flexible amount of digits but then I'm unable to use them. This is how my model looks like. from decimal import Decimal # from django.core.serializers.json import DjangoJSONEncoder import simplejson class Order(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) size = JSONField(null=True) Following the recommendation from this answer https://stackoverflow.com/a/3148376/3423825 and store the value like this: import simplejson as json self.size = json.dumps(Decimal('1'), use_decimal=True) Now when I try to convert it to decimal I get an error. size = Decimal(self.size) Object of type 'Decimal' is not JSON serializable I must say I'm a bit lost because type(self.size) returns <class string> so I should be able to convert it to Decimal, or am'I missing something? Thank you -
django - CreateView - how to insert default values with ForeignKey Field
I'm trying to have a model with a Foreign Key to have default dynamic values when I enter the CreateView. Let me explain: With the following models: class EquipmentType(models.Model): type = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=250, default='') date_posted = models.DateTimeField(auto_now_add=True) image =models.ImageField(default='default.jpeg', upload_to='equipment/equipment_type') active =models.BooleanField(default=True) objects=EquipmentTypeManager() def __str__(self): return self.type def get_absolute_url(self): return reverse('equipmentType-home') def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) ###################################### class EquipmentItem(models.Model): type =models.ForeignKey(EquipmentType, on_delete=models.SET_NULL, null=True) brand =models.CharField(max_length=100, help_text='bho some help text') model_type =models.CharField(max_length=100) matricola =models.CharField(max_length=100) image =models.ImageField(default='default.jpeg', upload_to='equipment/equipment_item') libretto_uso_e_manutenzione = models.FileField(null= True, default= '', blank=True, upload_to='equipment/equipment_item/libretti_uso_e_man') elimina =models.BooleanField(default=False) def __str__(self): return str(self.id) + '. '+ self.type.type + ' - '+ self.brand + ' - ' +self.model_type def get_absolute_url(self): return reverse('equipmentItem-list', kwargs={'type': self.type.type}) First, on the front-end, I list all the different types (chaisaws, welders etc), then by clicking on the specific type, I enter the Item-list-view: class EquipmentItem_ListView(LoginRequiredMixin, ListView): model = EquipmentItem template_name = 'equipment/equipmentItem_list.html' context_object_name = 'obj_list' ordering = ['brand'] def get_queryset(self): type = get_object_or_404(EquipmentType, type=self.kwargs.get('type')) return EquipmentItem.objects.filter(type = type, elimina=False).order_by('brand') Then with the following create view: class EquipmentItem_CreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = EquipmentItem template_name='equipment/equipmentItem_form.html' fields = ['type', 'brand', 'model_type', … -
the static files and media doesn't show in production but it works in development environments
the project was working fine in development but when i push it to heroku app the media doesn't show and this my code settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, "media"), ] MEDIA_URL = '/media/' STATIC_URL = '/static/' MEDIA_ROOT = ( os.path.join(BASE_DIR, 'media/') ) STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') urls.py from django.contrib import admin from django.urls import path from rashed import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="index"), path('form', views.Createview.as_view(), name="form") ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Sending out notifications like "n users liked your post" in django
I have created a Django application where users are able to post, comment, and like each other's activity. I am now implementing sending out notifications when one user comments on another user's post, and I am able to do that using django-notifications. Although it is not as modular as I would like it to be, it gets the job done. Example of notification (views.py): from notifications.signals import notify ... notify.send(sender=request.user, recipient=post.user, verb='commented on your post', target=post) I would like to send out notifications like "n users liked your post" (similar to Facebook notifications) and don't know how to do that. However, I found that django-notifications is rather outdated and I am considering whether I should switch to pinax-notifications if that package could help me out with this issue (tracking the change in the number of likes since recipient's last log in). How can I solve this? -
Queryset from two models for a single table
I have a list of parts (model 1) with prices (model 2). I want to display them in a django-tables2 table to get the historic prices of a part in a table: models.py: class Parts(models.Model): name = models.CharField('Name', max_length=120, unique=True) class Prices(models.Model): price = models.DecimalField("Price", decimal_places=2, max_digits=8) date = models.DateTimeField(default=timezone.now) part = models.ForeignKey(Parts, on_delete=models.CASCADE) tables.py: class PriceHistoryTable(django_tables2.Table): price = django_tables2.Column(accessor="prices_list", verbose_name="Price",) date = django_tables2.Column(accessor="dates_list", verbose_name="Date",) class Meta: model = Parts sequence = ("date", "price",) I tried to create the tables from two lists as I thought the docs would suggest here (list of dicts) using these methods in the models: def dates_list(self): return [{"date": d.date} for d in Prices.objects.filter(part_id = self.id)] def prices_list(self): return [{"price": p.price} for p in Prices.objects.filter(part_id = self.id)] But then I end up with a table in django-tables2 that contains the complete list of dates and prices in just one row. How would a method look that creates a queryset for the prices and one for the dates, so I can use it for django-tables2? -
How do I modify the url that generate by submit
I am using python 3.6 and django 3.0X The problem I have is: I want the flow is that when user select a brand and submit. The url path will generate as http://127.0.0.1:8000/show/car:Ford and link to url.py to pass to show.html However when submit, the url path generated as http://127.0.0.1:8000/show?car=Ford How can I get the correct url path that meet url.py. That is why there are a '?' and '=' in url path? Or how do I modify the url.py to meet the url path that generated by search.html? Below are my codes: search.html enter image description here show.html enter image description here url.py enter image description here Views.py enter image description here -
React JS actions not reflected in Django Backend
So, i'm planning to start my Masters Data Science in Winter Semester 2020. Heard that extra skills are appreciated in the field. So, i started Web App Development using Django & React JS. The steps followed by me: a.) Made backend Django CRUD views and urls. b.) Setup front-end React JS. I made a Web app which included a form in which people would input certain information about themselves which i would later use on for Predictive Analysis. So, this web app involve simple tasks like Listing all the inputted data, Creating new Data, Editing saved Data, Deleting saved data and so on. While working on the creation of new data, the code works perfectly fine but the changes are not reflected in Django Admin. handleChange listens to the changes made in input form. activeRecord takes in the current active form values. handleChange(e){ var value = e.target.value; this.setState({ activeRecord:{ ...this.state.activeRecord, [e.target.name]:value } }) } To deal with the submit button and saving the data to Django backend, i made handleSubmit: handleSubmit(e){ e.preventDefault() console.log('Item',this.state.activeRecord) var csrftoken = this.getCookie('csrftoken') var url = 'http://127.0.0.1:8080/DataCollection/create/' } fetch(url,{ method:'POST', headers: { 'Content-type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify(this.state.activeRecord) }) .then((response)=>{ this.fetchTasks() this.setState({ activeRecord:{ id: "", full_name:"", age:"", … -
Filter model with serializer.validated_data
I am setting up a Django REST application where peopple can review restaurants. So far I have those models: class RestaurantId(models.Model): maps_id = models.CharField(max_length=140, unique=True) adress = models.CharField(max_length=240) name = models.CharField(max_length=140) class RestaurantReview(models.Model): review_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantId, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class StarterPics(models.Model): restaurant_review_id = models.OneToOneField(RestaurantReview, on_delete=models.CASCADE) pics_author = models.ForeignKey(User, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantId, on_delete=models.CASCADE) name_1 = models.CharField(max_length=40) picture_1 = models.ImageField() My serializers: class RestaurantIdSerializer(serializers.ModelSerializer): class Meta: model = RestaurantId field = fields = '__all__' class RestaurantReviewSerializer(serializers.ModelSerializer): class Meta: model = RestaurantReview field = fields = '__all__' class StarterPicsSerializer(serializers.ModelSerializer): class Meta: model = StarterPics fields = '__all__' My views: class RestaurantIdViewset(viewsets.ModelViewSet): queryset = models.RestaurantId.objects.all() serializer_class = serializers.RestaurantIdSerializer class RestaurantReviewViewset(viewsets.ModelViewSet): queryset = models.RestaurantReview.objects.all() serializer_class = serializers.RestaurantReviewSerializer permission_classes = [IsAuthenticatedOrReadOnly,IsAuthorOrReadOnly] def perform_create(self, serializer): serializer.save(review_author=self.request.user) class StarterPicsViewset(viewsets.ModelViewSet): queryset = models.StarterPics.objects.all() serializer_class = serializers.StarterPicsSerializer permission_classes = [IsAuthenticatedOrReadOnly] def perform_create(self, serializer): if models.RestaurantReview.objects.filter(id=serializer.validated_data["restaurant_review_id"], review_author=self.request.user).exists(): serializer.save(pics_author=self.request.user) I have set up permissions as well so only the review_author can update his reviews and pics_author can update his pictures. My permissions: class IsOwnReviewOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.pics_author == request.user class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return … -
JavaScript Uncaught Syntax Error Missing ) after argument list, While Sending html data
I am trying to show my data with onclick function. My data in firebase cloudfirestore database and ı am using django. So in the views.py ı send tutorial data and unit_name data. which is ı can get data with; {{tutorial_data.to_dict.data | safe}} and {{unit_name.to_dict.data}} Here is my data it's look like; <pre><code class="language-python"> from bs4 import BeautifulSoup <br> import requests <br> url ="http://canilgu.com/" <br> request = requests.get(url) <br> soup = BeautifulSoup(request.text,` html.parser') <br> print(soup.title)</pre>/code> So I am trying to show this data in my web browser with using onclick function.. But ı am gettin error.. Here is my basic function; <script> function show(content){ document.getElementById("content").innerHTML=content; } </script> Here is html side; <div class="card background-color p-5" style="color:rgb(235,235,235);"><div id="content"> {{tutorial_data.to_dict.data | safe}} </div> <div class="unititem" onclick='show("{{unit_name.to_dict.data}}")'> But when ı want to show data which is look like this ı am not getting any erros; <h4>Beatiful Soup 4</h4> In today's world, we have tons of freely selected unstructured data / here (some web data). Sometimes it is freely available, sometimes easy to read. So, when data includes <pre> <code> </code> </pre> ı am getting Uncaught Syntax Error Missing ) after argument list.. Where is my mistake? or how can ı solve this issue? Thanks … -
Session cookies overwrite each other if multiple respondents answer a Django survey at the same time. Why?
I am doing a Django-based survey and everything runs fine. However, if multiple people answer it at the same time, the input data of one respondent overwrites the data of another before it is stored in the database. I use request.session[''] to store the data. def home(request): # Create an individual session to save the data for later use global user_id user_id = random.randint(0,10000) request.session['user_id%d' % (user_id)] = user_id # Not 100% sure if initial is right initial={user_id:request.session.get(user_id, user_id)} # This is my Survey(respondents type in their data here) form = SurveyForm(request.POST or None, initial=initial) if request.method == 'POST': # Save input data in session if form.is_valid(): request.session['age%d' % (user_id)] = form.cleaned_data['age'] request.session['gender%d' % (user_id)] = form.cleaned_data['gender'] ... ... I am using MIDDLEWARE to store the data. Why can one respondent influence the data of another respondent? Do they share a session? I thought sessions are created for every respondent individually on every browser. At the very end then, I save the data with survey.objects.create() and save(). -
Error: 'str' object has no attribute 'model' while creating user in Django Abstract User class
I created the Abstract User model in my Django project. I'm able to create a superuser but facing error in create_user cmd. Following is my piece of code. Thank you in advance. My Views.py FIle: def index(request): user=AccountManager.create_user("alb@alb.com","albas","12345") user.username="alba" user.save() return HttpResponse(f"User created {user.username} - {user.email}") My Models.py file: class AccountManager(BaseUserManager): def create_user(self,email,username,password=None): if not email: raise ValueError("User Must have an e mail address.") if not username: raise ValueError("User Must have a Username.") user=self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password): user=self.create_user( email, password=password, username=username, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self.db) return user Error Am Receiving: Internal Server Error: / Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python38-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\user\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Python\projects\Practise\Django User class\trialcode\trialcode\views.py", line 12, in index user=AccountManager.create_user("alb@alb.com","albas","12345") File "C:\Users\Python\projects\Practise\Django User class\trialcode\Userclass\models.py", line 17, in create_user user=self.model( AttributeError: 'str' object has no attribute 'model' [22/Jul/2020 13:32:30] "GET / HTTP/1.1" 500 71321 -
I'm trying to create a login form in django with both username and password to be my phone number provided while registration
Here is my models.py, im using these details for registration after registration i want the user to login with phone_number as his username and password. I tried custom ModelBackend but couldn't come with up solution models.py class userModel(models.Model): Full_Name = models.CharField(max_length = 50) Date_of_Birth = models.DateField() Phone_Number = models.CharField(max_length = 10,unique=True,null=False,blank=False) Email_ID = models.EmailField() Passport_Number = models.CharField(max_length = 10) photo = models.ImageField(upload_to='images/',max_length=255,blank=True,null=True) def __str__(self): return self.Full_Name views.py def register(request): registered = False if request.method == 'POST': user_form = userForm(request.POST, request.FILES) if user_form.is_valid(): user = user_form.save() user.save() registered = True else: print(user_form.errors) else: user_form = userForm() return render(request,'dezzexapp/registration.html',{'user_form':user_form,'registered':registered}) -
Please help me with Django Todo project
I have a Django project about To do list and I have a problem. I want to delete an element in the home page when user click it and then add it in another page. My models.py: class Todo(models.Model): text = models.CharField(max_length=300) date = models.DateTimeField(auto_now=True) def __str__(self): return self.text class Meta: verbose_name = "Todo" verbose_name_plural = "Todos" class CompletedTodo(Todo): pass My index.html template: <div class="icons__tick"><a href="{% url 'completed_tasks'%}"><img src="{% static 'main/images/icons/tick.svg'%}" alt="Completed Task" class="icons__thumb"></a> </div> <form action="{% url 'complete_todo' todo.id%}" method="post"> {% csrf_token%} <button class="complete_button" type="submit" >Completed</button> My urls.py: path('completed_tasks', views.Comp.completed_tasks, name='completed_tasks'), path('complete_todo/<int:todo_id>', views.Comp.complete_todo, name='complete_todo') My views.py: class Comp: completed_todo = Todo.objects.get(id=task_id) def completed_tasks(self): return render(self, 'main/completed_tasks.html') def complete_todo(self, todo_id): global task_id task_id = todo_id completed_todo = Todo.objects.get(id=todo_id) return HttpResponseRedirect('/') I got error: File "D:\Edgar\IT\Programming\django\projects\Todo App\todo\main\views.py", line 33, in Comp completed_todo = Todo.objects.get(id=task_id) NameError: name 'task_id' is not defined So when the user clicks on the "Completed" button I want to from home page delete the element that was clicked and then add it to another page. Hope you'll find some time for my problem, thank you in advance. -
Django Admin Password field displays plain text
I extended the AbstractUser class, and then added a password2 field for password validation. However, in my admin page, my password2 field displays as plain text, instead of a hashed value just like the AbstractUser password field. I'd want my password2 value to be hashed as well. How can that be done, please. User Model: class UserProfile(AbstractUser): profile_image = models.FileField(upload_to="profile_img") password2 = models.CharField(max_length=350, default="") SignUp serializer: class SignUpSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = UserProfile fields = ('username', 'password', 'password2', 'email',) `` -
Perform math in Django and databases
I am building an inventory system using Django, right now I am adding the functionality to place an order. What I want to do is to subtract the quantity ordered from the quantity in the database. For example if someone ordered 10boxes of chips and I have 11 in my stock once I place the order on web I want the web to subtract 10 boxes from the stock. I am not really sure how to do that. Any help is appreciated! -
Django DjangoRestFramework Appending Item to ListField
I faced this problem while appending a CharField item to ListField: the result list is split into individual characters instead of one string. The files: # serializers.py class TodoSerializer(serializers.ModelSerializer): key = serializers.IntegerField(source='id') levels = serializers.ListField(source='level') # (a) class Meta: model = Todo fields = ['key', 'title', 'desc', 'level', 'levels', 'created'] (a): # models.py level = models.CharField(_('level'), max_length=20) What I want the ListField to behave is, say the level is normal, I want the ListField to come out as ["normal"]. However, it came out as individual characters, as shown in this image: In one sentence, I want to append level into levels but the format is not satisfactory. Can anyone please help? Thanks in advance. -
Static files are not loading in Django. Get 404 error. Static directry defination in settings.py looks proper
I get following error; GET http://127.0.0.1:8000/static/bootstrap/css/bootstrap.min.css net::ERR_ABORTED 404 (Not Found) GET http://127.0.0.1:8000/static/bootstrap/css/bootstrap-grid.min.css net::ERR_ABORTED 404 (Not Found) GET http://127.0.0.1:8000/static/bootstrap/css/bootstrap-reboot.min.css net::ERR_ABORTED 404 (Not Found) . . . so on... URL setting in settings.py is as follows; STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') I have entered the static file urls in the template(home.html); {%load static%} <!DOCTYPE html> <html > <head> <!-- meta data --> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1"> <link rel="shortcut icon" href="{% static 'images/logo4.png' %}" type="image/x-icon"> <meta name="description" content="Website Builder Description"> <title>home.html</title> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap-grid.min.css' %}"> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap-reboot.min.css' %}"> <link rel="stylesheet" href="{% static 'tether/tether.min.css' %}"> <link rel="stylesheet" href="{% static 'dropdown/css/style.css' %}"> <link rel="stylesheet" href="{% static 'animatecss/animate.min.css' %}"> <link rel="stylesheet" href="{% static 'theme/css/style.css' %}"> My foder structure as follows: enter image description here Can some on ehelp me to resolve the isseu? -
Probem with saving data to model.Error: save() prohibited to prevent data loss due to unsaved related object
Im trying to create web gpx track archive displayed on map. Unfortunately I have problem with saving parsed data from uploaded file to model. When I try to Run parsing/saveing func error occurs: save() prohibited to prevent data loss due to unsaved related object (gpx_file) My code: views.py from django.shortcuts import render, redirect from .forms import UploadGpxForm, Up from .models import GPXPoint, GPXTrack, gpxFile, gpxdata from django.http import HttpResponseRedirect from django.contrib.gis.geos import Point, LineString, MultiLineString from django.conf import settings from django.core.files.storage import FileSystemStorage import gpxpy import gpxpy.gpx def home(request): #context = { #'notes': Note.objects.all() #} return render(request, 'gpsarchive/home.html') # function for parsing and saving data from gpx file to our database #function is called after the gpx_file is uploaded def SaveGPXtoPostGIS(f, file_instance): gpx_file = open(settings.MEDIA_ROOT+ '/gpxstorage'+'/' + f.name) gpx = gpxpy.parse(gpx_file) if gpx.waypoints: for waypoint in gpx.waypoints: new_waypoint = GPXPoint() if waypoint.name: new_waypoint.name = waypoint.name else: new_waypoint.name = 'unknown' new_waypoint.point = Point(waypoint.longitude, waypoint.latitude) new_waypoint.gpx_file = file_instance new_waypoint.save() if gpx.tracks: for track in gpx.tracks: print("track name:" +str(track.name)) new_track = GPXTrack() for segment in track.segments: track_list_of_points = [] for point in segment.points: point_in_segment = Point(point.longitude, point.latitude) track_list_of_points.append(point_in_segment.coords) new_track_segment = LineString(track_list_of_points) new_track.track = MultiLineString(new_track_segment) new_track.gpx_file = file_instance new_track.save() def upload_success(request): return render(request, 'gpsarchive/success.html') … -
FormView subclasses calling Post twice
@method_decorator(registration_required, name = 'dispatch') @method_decorator(require_http_methods(["GET", "POST"]), name = 'dispatch') class ProfileCreateView(StudentContextMixin, FormView): form_class = ProfileForm template_name = 'profiles/create_profile.html' success_url = '/profiles/home' def form_valid(self, form): print('called out') with transaction.atomic(): profile = Profile(**form.cleaned_data) profile.student = self.student print('called in') profile.save() assign_perm(self.student.user, "profiles.view_profile", profile.pk) assign_perm(self.student.user, "profiles.delete_profile", profile.pk) assign_perm(self.student.user, "profiles.change_profile", profile.pk) return redirect(self.success_url) My form is hitting the post method and thus the form_valid method twice (I checked by overriding the post method the same way). All these views extended from FormView are submitting twice and redundant profiles are being created. 127.0.0.1 - - [22/Jul/2020 12:18:19] "GET /profiles/create_profile HTTP/1.1" 200 - called out called in called out called in 127.0.0.1 - - [22/Jul/2020 12:18:25] "POST /profiles/create_profile HTTP/1.1" 302 - 127.0.0.1 - - [22/Jul/2020 12:18:25] "GET /profiles/home HTTP/1.1" 200 - What is going wrong and how to change it? -
Changing CSS of Labels in Django Admin
[View this image for reference][1] I want to change css of User name and Mobile no. as that of others. what should I change in admin.py ? class orderAdmin(admin.ModelAdmin): list_display= ('id','total_amount','status','user_name','notes','user_mobile') def user_name(self, obj): return obj.user_id.full_name def user_mobile(self,obj): return obj.user_id.mobile_number user_name.description = 'User Name' admin.site.register(order,orderAdmin) [1]: https://i.stack.imgur.com/RIVLl.png -
Multiselect django ['] no es una de las opciones disponibles
I have a Multiselect in django that resolve this error: <ul class="errorlist"><li>months_recurrence<ul class="errorlist"><li>Choose a valid option. [&#39;3&#39;, &#39;4&#39;, &#39;5&#39;] is not a valid option.</li> </ul></li></ul> form.py class Formwhatever(forms.ModelForm): Enero = 1 Febrero = 2 Marzo = 3 ... months_recurrence_options = ( (Enero, "Enero"), (Febrero, "Febrero"), (Marzo, "Marzo"), (Abril, "Abril"), (Mayo, "Mayo"), (Junio, "Junio"), (Julio, "Julio"), (Agosto, "Agosto"), (Septiembre, "Septiembre"), (Octubre, "Octubre"), (Noviembre, "Noviembre"), (Diciembre, "Diciembre") ) months_recurrence = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=months_recurrence_options) class Meta: model = Whatever fields = [... 'months_recurrence',...] model.py Enero = 1 Febrero = 2 Marzo = 3 Abril = 4 Mayo = 5 Junio = 6 Julio = 7 Agosto = 8 Septiembre = 9 Octubre = 10 Noviembre = 11 Diciembre = 12 months_recurrence_options = ( (Enero, "Enero"), (Febrero, "Febrero"), (Marzo, "Marzo"), (Abril, "Abril"), (Mayo, "Mayo"), (Junio, "Junio"), (Julio, "Julio"), (Agosto, "Agosto"), (Septiembre, "Septiembre"), (Octubre, "Octubre"), (Noviembre, "Noviembre"), (Diciembre, "Diciembre") ) months_recurrence=models.CharField(max_length=100,choices=months_recurrence_options, blank=True,null=True) view.py obj = get_object_or_404(whatever,id=id) form = CompanyFormAdmin(request.POST or None, request.FILES or None, instance=obj) if request.method == 'POST': if form.is_valid(): form.save() return redirect('others.html') print(form.errors) return render(request,'template.html', {'form': form) And html --> {{ form.months_recurrence }} What is the correct sintax in my model or in my form? Thanks. -
Django - How to make a notification?f when User Register It will send notification to Email of Admin
class SignupForm(forms.Form): username = forms.CharField(max_length=10, widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'Username', }) ) email = forms.EmailField( max_length=200, widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'Email' }) ) password = forms.CharField( min_length=6, max_length=10, widget=forms.PasswordInput({ 'class': 'form-control', 'placeholder': 'Password' }) ) repeat_password = forms.CharField( min_length=6, max_length=10, widget=forms.PasswordInput({ 'class': 'form-control', 'placeholder': 'Repeat password' }) ) Here is my form.py, how to make an email notification to the email of server ? That will notify the admin that there is a new User register to his application. -
Django reset password link gives 404
I have implemented django_reset_password functionality. Everything is running perfectly on localhost but when I am running the same thing on server, the link that i get in the email says 404 on server. path('password_reset/', password_reset, name='auth_password_reset'), path('password_reset/done/', password_reset_done, name='auth_password_reset_done'), path('reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,23})/', password_reset_confirm, name='auth_password_reset_confirm'), path('reset/done/', password_reset_complete, name='auth_password_reset_complete'), "auth_password_reset_confirm" is the function in which I am getting 404 on server. http://testing.xyz.com/auth/reset/(%3FPNg%5B0-9A-Za-z_%5C-%5D+)/(%3FP5id-91751fc793227bd46093%5B0-9A-Za-z%5D%7B1,13%7D-%5B0-9A-Za-z%5D%7B1,20%7D)/ Above link gives 404 http://127.0.0.1:8000/auth/reset/(%3FPNg%5B0-9A-Za-z_%5C-%5D+)/(%3FP5id-91751fc793227bd46093%5B0-9A-Za-z%5D%7B1,13%7D-%5B0-9A-Za-z%5D%7B1,20%7D)/ But this same url works in localhost. Please tell me what am I doing wrong.