Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migrate two databases, but one database in mysql was deleted?
There are two database setted in my Django project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'default_db', ... }, }, 'crm': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'crm_db', ... } } And I want to migrate my app ad_management's models into default_db: app structure: ├── ad_management ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tasks.py ├── tests.py ├── urls.py ├── utils models: from django.db import models class Name(models.Model): name = models.CharField(max_length=32) class Meta: managed = True Then I just run python manage.py makemigrations ad_management and python manage.py migrate ad_management, but the db crm_db was deleted as the default db django operating was my default_db. can anyone help me out of this confusion, thanks. -
what happens when we use on_delete=models.CASCADE in django
what happens when we use "on_delete=models.CASCADE" in django models class HospitalStay(models.Model): patient = models.ForeignKey(User, on_delete = models.CASCADE) -
Make deleting by url not possible. Only by direct button click
I have a model form editing template with Save and Delete buttons. I check in the view that the user who tries to delete a post is the owner of it. I use a pop up onlick confirmation. But if I just go to the url (.../post_delete/pk) it deletes the post right away. How do I make sure the deletion is only possible with a button click on the edit template? -
Error in superuser creation NOT NULL constraint failed
I have created a custom user model Student to modify the default signup page provided by Django. from django.db import models from django.contrib.auth.models import AbstractUser class Student(AbstractUser): email = models.EmailField(unique=True) roll = models.CharField(max_length=200, blank=False) contact_no = models.DecimalField( max_digits=10, decimal_places=0, blank=False) I then migrated the database by running: python manage.py makemigrations students python manage.py migrate Now when I try to create a superuser using the command python manage.py createsuperuser, it shows the following error: Traceback (most recent call last): File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 296, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: students_student.contact_no The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 184, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/contrib/auth/models.py", line 161, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/contrib/auth/models.py", line 144, in _create_user user.save(using=self._db) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 73, in save super().save(*args, **kwargs) … -
Different map pins using Mapbox-gl-js with Django
I'm trying to create a dynamic map of places for my travel blog with Django to be automatically updated based on new entries in database. So far it's going quite good (link: http://puchalatravel.com/map) What I'm having issues with is creating different colour pins based on status field in the database. I'd like to have 4 colors for 4 different status options. I don't know JavaScript well enough to know how to approach the issue. I've googled and tried JS for() loops but didn't manage to make it work.. Currently my code looks as follows: models.py class PlaceStatus(models.Model): status = models.CharField(max_length=32) class Meta: verbose_name_plural = "Place statuses" def __unicode__(self): return self.status def __str__(self): return self.status class Place(models.Model): name = models.CharField(max_length=32) coord_v = models.FloatField() coord_h = models.FloatField() status = models.ForeignKey(PlaceStatus, on_delete=models.CASCADE) trip = models.ManyToManyField(Trip, blank=True, null=True) images = models.ManyToManyField(Image, blank=True, null=True) def __unicode__(self): return self.name def __str__(self): return self.name views.py def map(request): places = Place.objects.all() return render(request, 'blog/map.html', {'places': places}) map.html {% extends 'blog/base.html' %} {% block header %} <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.js'></script> <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.css' rel='stylesheet'/> {% endblock %} {% block banner %} {% endblock %} {% block two_columns %} <div id='map'></div> <script> mapboxgl.accessToken = 'pk.eyJ1IjoibWljaGFscHVjaGFsYSIsImEiOiJjamxxeWk0ZTYwcWJyM3BwbGVzMWpobjFqIn0.sBxqcK2lDMxn9RvqaBfduw'; var map = new mapboxgl.Map({ container: 'map', style: … -
What is virtual environment in Django ? Is it really necessary for a Django project?
While watching any of the tutorials, there is a discussion about making a virtual environment using the command pip install virtualenv What is the use of this virtual environment in Django app development. Where is the formation of Django virtual environment takes place? What is the significance of this virtual environment? -
Django doesn't return request headers to axios
I'm trying to receive a session cookie with axios from a django rest framework backend. I'm using django sessions described here. When I make a post from the command line with httpie, I see several headers, including Set-Cookie with the session token: http post http://example.com:8000/api/ key1=val1 key2=val2 HTTP/1.1 201 Created Allow: POST, OPTIONS Content-Length: 83 Content-Type: application/json Date: Thu, 17 Jan 2019 08:47:16 GMT Server: WSGIServer/0.2 CPython/3.6.7 Set-Cookie: session=e30:1gk3KW:PVn6Pgj-gZQhQue6plWCAONePR4; Domain=*; expires=Thu, 31 Jan 2019 08:47:16 GMT; HttpOnly; Max- Age=1209600; Path=/; SameSite=Lax Vary: Accept, Cookie, Origin X-Frame-Options: SAMEORIGIN { <response params> } But when I do it from axios, the only response header is Content-Type: application/json. I went for the kitchen sink approach with the CORS settings: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_DOMAIN = '*' CSRF_COOKIE_DOMAIN = '*' CORS_ALLOW_HEADERS = default_headers + ( 'Set-Cookie', ) CORS_EXPOSE_HEADERS = ( 'Set-Cookie', ) but to no avail. The view doesn't do much: def post(self, request): request.session.create() request.session.save() return super().create(request) nor does the axios code: axios.post( URL, { key1: val1, key2: val2, } ) .then(response => {whatever(response)}) I'm trying to figure out how to receive the other headers in axios, or at least the reason they're not being received in the first place. I … -
Pass Post Data To Get() - Django
I haveJobListView in which im list the data as well displaying the form. Now when i am posting that i am directly redirected to same page. But now i want to filter out jobs query. So i need that posted data in get(). I am able to print status which is coming from JobSearchForm in post(). But not able to send that status in get(). The reason i want to do this is that i want to filter out jobs query so that only particular list should be displayed. If you have any better approach then please suggest me. class JobListView(LoginRequiredMixin, generic.TemplateView): template_name = 'admin/jobs/job.html' def get(self, request, *args, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) company_name = self.request.user.userprofile.user_company jobs = Jobs.objects.exclude(job_is_deleted = True).filter(job_company=self.request.user.userprofile.user_company) form = JobSearchForm() return render(request, self.template_name, {'form': form, 'jobs': jobs}) def post(self, request, *args, **kwargs): form = JobSearchForm(request.POST) if form.is_valid(): status = form.cleaned_data['status'] print (status) return HttpResponseRedirect('/useradmin/job/') -
Form Validation When Submitting Two Forms
After Submiting Form Before Submitting Form Form error comming for validations. When i remove form_hour from get and post function then form but when i put form_hour then the error of validations comes. Basically i am updating a form named form and creating form_hour. Views.py class ClockOutAddView(LoginRequiredMixin, generic.View): # model = TimesheetEntry template_name = 'admin/clock/clock_form.html' # form_class = ClockOutForm success_url = '/useradmin/timesheet/' def get(self, request, pk, *args, **kwargs): form = ClockOutForm(instance=TimesheetEntry.objects.get(id=pk)) form_hour = ClockOutHourForm() return render(request, self.template_name, {'form': form, 'form_hour':form_hour}) def post(self, request, pk, *args, **kwargs): form = ClockOutForm(request.POST, instance=TimesheetEntry.objects.get(id=pk)) form_hour = ClockOutHourForm(request.POST) print(form.error_class) print(form_hour.error_class) print('Outside Valid') if form.is_valid(): form.instance.timesheet_is_running =False print('Inside Valid') # form.save() # form.instance.timesheet_hour_created_by = self.request.user # form.instance.timesheet_hour_updated_by = self.request.user return HttpResponseRedirect(self.success_url) return render(request, self.template_name, {'form': form, 'form_hour':form_hour}) Form.py class ClockInForm(forms.ModelForm): class Meta: model = TimesheetEntry fields = ['timesheet_jobs', 'timesheet_clock_in_date', 'timesheet_clock_in_time'] class ClockOutForm(forms.ModelForm): class Meta: model = TimesheetEntry fields = ['timesheet_jobs', 'timesheet_clock_in_date', 'timesheet_clock_in_time', 'timesheet_clock_out_date', 'timesheet_clock_out_time', 'timesheet_note' ] Models.py class TimesheetEntry(models.Model): timesheet_users = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_users') timesheet_jobs = models.ForeignKey(Jobs, on_delete=models.CASCADE,related_name='timesheet_jobs') timesheet_clock_in_date = models.DateField() timesheet_clock_in_time = models.TimeField() timesheet_clock_on = models.DateTimeField(auto_now_add=True) timesheet_clock_in_by = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_user_clock_in_by') timesheet_clock_out_date = models.DateField(blank=True, null=True) timesheet_clock_out_time = models.TimeField(blank=True, null=True) timesheet_clock_out_on = models.DateTimeField(auto_now_add=True, blank=True, null=True) timesheet_clock_out_by = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_user_clock_out_by') timesheet_note = models.CharField(max_length=100) timesheet_is_edited = models.BooleanField(default=False) timesheet_is_out_edited = models.BooleanField(default=False) … -
Passing arguments as json object
I am trying to link my django web app to Azure ML API. I do have Django form with all the required inputs for my Azure API. def post(self,request): form = CommentForm(request.POST) url = 'https://ussouthcentral.services.azureml.net/workspaces/7061a4b24ea64942a19f74ed36e4b438/services/ae2c257d6e164dca8d433ad1a1f9feb4/execute?api-version=2.0&format=swagger' api_key = # Replace this with the API key for the web service headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)} if form.is_valid(): age = form.cleaned_data['age'] bmi = form.cleaned_data['bmi'] args = {"age":age,"bmi":bmi} json_data = str.encode(json.dumps(args)) print(type(json_data)) r= urllib.request.Request(url,json_data,headers) try: response = urllib.request.urlopen(r) result = response.read() print(result) except urllib.request.HTTPError as error: print("The request failed with status code: " + str(error.code)) print(json_data) # Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure print(error.info()) print(json.loads(error.read())) return render(request,self.template_name) When i try to submit the form i am getting type error - TypeError('POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.',) Getting status code - 400 and below error {'error': {'code': 'BadArgument', 'message': 'Invalid argument provided.', 'details': [{'code': 'RequestBodyInvalid', 'message': 'No request body provided or error in deserializing the request body.'}]}} Arguments are using print(json_data) - b'{"age": 0, "bmi": 22.0}' I need to pass arguments as json. Please help. -
Django is not hashing passwords for new users
I am trying to create a signup page with django. I used a normal html form and linked it to django's views and models. However for some reason it won't hash the passwords in the database, it is just storing them as plain text. Not only is this a security issue but it is also not allowing users to login. html form: <div id="signupboxelementscontainer"> <form action="" method="post"> {% csrf_token%} <div id="namerow" class="row"> <input name="firstname"id="firstname" class="formelements" placeholder="First name" type="text"> <input name="lastname" id="lastname" class="formelements" placeholder="Last name" type="text"> </div> <input name="email" id="email" class="formelements" placeholder="Email address" type="email"> <br> <input name="password" id="password" class="formelements" placeholder="Password" type="password"> <br> <input name="passwordagain" id="passwordagain" class="formelements" placeholder="Password again" type="password"> <br> <div class="row"> <input name="areacode" id="areacode" class="formelements" placeholder="+234" type="text"> <input name="number" id="number" class="formelements" placeholder="Mobile phone number" type="text"> </div> <button id="submitbutton" type="submit"> Submit</button> </div> <p>Already have an account? <a href="{% url 'login'%}">Sign in</a> </p> models: class CustomUser(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) email = models.EmailField(max_length=30) password = models.CharField(max_length=100) areacode = models.CharField(max_length=4) number = models.CharField(max_length=30) views: def signup(request): if request.method == "POST": firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') email = request.POST.get('email') password = request.POST.get('password') passwordagain = request.POST.get('passwordagain') areacode = request.POST.get('areacode') number = request.POST.get('number') userdetails = CustomUser(firstname=firstname,lastname=lastname,email=email,password=password, areacode=areacode, number=number) userdetails.save() return render(request, 'main/accountconfirmationpage.html') else: … -
How to specify dictionary parameter in dJango urls?
I am newbie to dJango and got the following error saying that Reverse for 'plot_graph' with keyword arguments '{'column': '["c4", "c5"]'}' not found. 2 pattern(s) tried: ['index/api/plot_graph/(?P<column>[0-9]+)$', 'index/api/plot_graph/(?P<column>[\\w-]+)/$'] My webpage shows me five distinct checkboxes which are c1,c2,c3,c4,c5 and when I click c4,c5 and then click submit button, I can see the above error. below are my codes. urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^form/$', views.Form), # url(r'^api/plot_graph/', views.plot_graph, name='plot_graph'), url(r'^api/plot_graph/(?P<column>[\w-]+)/$', views.plot_graph, name='plot_graph'), url(r'^api/plot_graph/(?P<column>[0-9]+)$', views.plot_graph, name='plot_graph'), views.py def plot_graph(request,column): print(column) data = Data.objects.all() \ .extra(select={'data': connections[Data.objects.db].ops.date_trunc_sql('data', column)}) \ .values(column) return JsonResponse(list(data),safe=False) def Form(request): if request.method == 'POST': if len(request.FILES) !=0: file = request.FILES['files'] column_name = upload_file_name(file) return render(request,"index/form.html",{"column_name":column_name}) else: columns = request.POST.getlist('columns') column_json = json.dumps(columns) return render(request,"index/form.html",{"column_json":column_json}) else: return render(request,"index/form.html",{}) form.html d3.json("{% url "plot_graph" column=column_json|safe %}", function(error, data) { data.forEach(function(d){ d.c5 = d.c5; }); In my case, how to change the urls so that it works? -
Django and DRF, ip limit for request
I need an advise I have some public endpoint created using DRF. Now I want to limit access to it: for example no more than 5 requests in a day. What library/module should I use? Or is there anything in DRF itself? -
Django model instance getattr in multiple database landscape
I have multiple database landscape with "default": {} in databases. I dont need any default db and made this for consistency as suggested in django docs. I also have some Model1 which has related Model2 by FK. Now i am struggling with strange behaviour: having instance of Model1 in one of the databases, i want to get it related instance from Model2, i use: inst1 = Model1.objects.using("mydb").get(...) # this sets inst1._state.db to "mydb related = getattr(inst1, "related_field") and get ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. So instead of respecting inst1._state.db underlying __get__ just init manager with "default" database which leads to this exception. My ugly workaround trying to make generic function for this is: from django.apps import apps related_model = apps.get_model(inst1._meta.app_label, inst1._meta.model_name) related_object = related_model.objects.using(inst1._state.db).get(...) Maybe i am missing something here? -
I can't add a separate image to each article
I can't add a separate image to each article {% for article in articles %} <li> <a href="{% url 'postDetail' id=article.id %}"><img src="{% static 'article.image.url' %}" alt="img" /> </a> <div class="title"><a href="{% url 'postDetail' id=article.id %}"> <h2>{{article.title | safe}}</h2> </a> </div> </li> {% endfor %} -
django-channels not working/not sendind any messages as web socket
by following one of those tutorials over youtube i have just wrote a websocket server using django-channels here is my code signal.py from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from asgiref.sync import async_to_sync from channels.layers import get_channel_layer @receiver(post_save, sender=User) def announce_new_user(sender, instance, created, **kwargs): if created: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( "gossip", {"type": "user.gossip", "event": "New User", "username": instance.username}) consumers.py from channels.generic.websocket import AsyncJsonWebsocketConsumer class NoseyConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.channel_layer.group_add("gossip", self.channel_name) print(f"Added {self.channel_name} channel to gossip") async def disconnect(self, close_code): await self.channel_layer.group_discard("gossip", self.channel_name) print(f"Removed {self.channel_name} channel to gossip") async def user_gossip(self, event): await self.send_json(event) print(f"Got message {event} at {self.channel_name}") apps.py from django.apps import AppConfig class NotifierConfig(AppConfig): name = 'notifier' def ready(self): from .import signals init.py default_app_config = 'notifier.apps.NotifierConfig' routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from notifier.consumers import NoseyConsumer application = ProtocolTypeRouter({ "websocket": URLRouter([ path("notifications/", NoseyConsumer), ]) }) and in channels_layers in settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost",16379)], }, }, } i dont know what the issue is when ever i create a new user using admin i cant see any kind of data that is being transmitted from django websockets over the console … -
Django: Run a script right after runserver
Context: I have a table on the database that uses values from an external database. This external database updates its values periodically. Problem: In order to update my database everytime i start the server, I want to run a script right after the runserver. Potential Solution: I have seen that it is possible to run a script from a certain app, which is something I'm interested in. This is achievable by using the django-extensions: https://django-extensions.readthedocs.io/en/latest/runscript.html However, this script only runs with the following command: python manage.py runscript your_script Is there any other way to run a script from an app and execute it right after the runserver command? I am open to suggestions! Thanks in advance -
Django Authentication Login returns nothing
I'm trying to log users in with django authenticate. It returns nothing even when the email and password are correct. It just reloads the page and doesn't do anything. I have checked and the email and password I used are stored in the database, so the account exist but login doesn't do anything. I am using django 2. Views: def signup(request): if request.method == "POST": firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') email = request.POST.get('email') password = request.POST.get('password') passwordagain = request.POST.get('passwordagain') areacode = request.POST.get('areacode') number = request.POST.get('number') userdetails = CustomUser(firstname=firstname,lastname=lastname,email=email,password=password, areacode=areacode, number=number) userdetails.save() return render(request, 'main/accountconfirmationpage.html') else: return render(request,'main/signup.html') def login(request): email=request.POST.get('email') password=request.POST.get('password') user = authenticate(request, email=email, password=password) if user is not None: if user.is_active: login(request, user) return render(request,'main/dashboard.html') else: return render(request, 'main/login.html') from django.db import models Models: # Create your models here. class CustomUser(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) email = models.EmailField(max_length=30) password = models.CharField(max_length=100) areacode = models.CharField(max_length=4) number = models.CharField(max_length=30) -
optimise django sql query
I'm using Django 2.x. I have two models class AmountGiven(models.Model): contact = models.ForeignKey(Contact, on_delete=models.PROTECT) amount = models.FloatField(help_text='Amount given to the contact') interest_rate = models.FloatField(blank=True, default=None, null=True) given_date = models.DateField(default=timezone.now) total_due = models.FloatField(blank=True, default=0.0, editable=False) class AmountReturned(models.Model): amount_given = models.ForeignKey(AmountGiven, on_delete=models.CASCADE, blank=True) amount = models.FloatField() return_date = models.DateField(default=date.today) Use case There can be multiple records of the amount given to a contact There can be multiple records of the returned amount for an amount given Now, I want to get total_due amount for a particular contact. This includes total_payable = total_given + interest total_due = total_payable - total_returned To calculate total_due and interest, I have defined few property methods in the AmountGiven model. @property def interest_to_pay(self): if self.interest_rate: simple_interest_amount = ... return simple_interest_amount return 0 @property def total_payable(self): return self.amount + self.interest_to_pay @property def amount_due(self): total_due = self.total_payable - self.total_returned self.total_due = total_due self.save() return total_due @property def total_returned(self): returned_amount = self.amountreturned_set.aggregate(total_returned=Sum('amount'))['total_returned'] if not returned_amount: returned_amount = 0 return returned_amount In Contact model, there is a property method to get the total due amount for the contact. @property def amount_due(self): total_due = 0 for due in self.amountgiven_set.all(): total_due += due.amount_due return total_due Query ContactSerializer class ContactMinSerializer(serializers.ModelSerializer): class Meta: model = Contact … -
django: ValueError: invalid literal for int() with base 10. for UpdateView ModelForm
I have a Django application containing a basic Profile model which extends the User model using the OneToOneField class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, ) And this is the url pattern for /updateProfile path('updateProfile/<pk>', views.UpdateProfileView.as_view(), name='update_profile'), which is being called from the navigation bar of the website as follows: <a href="{% url 'update_profile' request.user %}">UpdateProfile</a> I have utilised the ModelForm class in forms.py as follows: class update_profile_form(forms.ModelForm): class Meta: model = Profile fields = ('phone_number', 'profile_picture') And in Views.py the following UpdateView class-based view is invoked: @method_decorator(login_required, 'dispatch') class UpdateProfileView(UpdateView): model = Profile success_url = reverse_lazy('home') form_class = update_profile_form template_name = 'update_profile.html' # this is where the error occurs def get_queryset(self): return Profile.objects.filter(user=self.request.user) I am unable to determine what combination of user field to use above to render the form in the update_profile.html template. Please help! Thanks -
Django: How do I show images to select in forms?
I have a Car model and each car object has a photo. I want to create a form where the photos of every car are displayed. When user clicks on a photo and then clicks Submit, the id of the car associated with the photo gets transferred to a next form. How do I create such a form? Can I transfer the id from one form to a field on another form? -
Localization: django-admin compilemessages skip venv
I am using localization in Django 1.11 application. I can exclude the virtual environment folder and node_modules folder while adding the messages in message file using -i option like: django-admin makemessages -l 'no' -i venv django-admin makemessages -d djangojs --locale no -i venv -i node_modules After adding the translations I am compiling messages using: django-admin compilemessages It processes django.po files of all installed packages located in virtual environment folder. Thus it takes longer time to finish compiling translations. I did not find any argument parameter to skip a specific path from compilemessages command in documentation. Is there any option to skip the venv or specific path from compilemessages? -
How to show column name on admin site in django?
I'm extending my admin table on django default admin table. After adding a column, when I go to the admin site, I can only see the username column name on the user section. But when click it, it shows the column name and ready to put some fields. All I want is to show all the column name when visiting to the user table. Im just a newbie in Django Framework, I read some documents and ways to extend my admin table. All I want is to add column name on existing admin table. #models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): contact_number = models.CharField(max_length=250, blank=True) #views.py from django.shortcuts import render from .models import User from django.urls import reverse_lazy from django.views import generic from .forms import NewUserCreationForm from django.http import HttpResponseRedirect class SignUp(generic.CreateView): form_class = NewUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' def userView(request): users = User.objects.all() return render(request,'registration/view_users.html', {"all_users":users}) #admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User from .forms import NewUserCreationForm, NewUserChangeForm class NewUserAdmin(UserAdmin): add_form = NewUserCreationForm form = NewUserChangeForm model = User list_display = ['username','first_name','last_name','contact_number'] admin.site.register(User,NewUserAdmin) I want to show all the column on the admin site. -
Why css isn't loading in my Fastcomet Django website?
Static files don't load to the django website deployed on fastcomet, with cpanel The site is deployed and seemly works well in the other regards, loads from the database, redirects to pages but it doesn't not load any css, javascript or images, it's bare html, I have tried changing {% load static %} to {% load staticfiles %} in all pages, and vice-versa and setting direct directory to the staticfiles folder in the settings file, it works perfectly fine in my localhost, I don't know what could be the problem static and media files in settings.py file: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aida_ganaderia_luz_y_sombra.settings') application = get_wsgi_application() passenger_wsgi.py import os import sys sys.path.insert(0, os.path.dirname(__file__)) wsgi = imp.load_source('wsgi', 'aida_ganaderia_luz_y_sombra/wsgi.py') application = wsgi.application current state http://aidaganaderialuzysombra.tryfcomet.com/ bare html -
Customise django-activity-stream Action’s content
I’m using it for the first time and it just took a few minutes to set it up and running. However, I wanted to have below pattern for the final notification: [Date/time of comment][User Role][Username] commented on [Target]. However, I can only see this fixed syntax: action.send(User, verb='commented on', target=myObject) I can’t figure out how to customize it.