Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery doesn't talk to django database
I am using Celery for very first time in a project. I have to insert a lot of records in database asynchronously. When I try to do SomeModel.objects.create() in celery task, it shows error django.db.utils.OperationalError: FATAL: role "<DEFAULT_USERNAME>" does not exist It looks like celery is ignoring database settings for connection in settings.py and using default settings. Can anyone tell me please what I am missing here? -
How to pass attributes to 3rd party FormView in Django?
I am trying to use django-password-reset, and this is my first attempt with class-based forms, especially 3rd party. In the documentation I see a bunch of attributes I can use. But how exactly (where in my code) do I set for example case_sensitive? All I have so far is a bunch of templates and this line in urls.py: url(r'^password/', include('password_reset.urls')), -
Difference between NestedStackedInline and NestedTabularInline
I using a nested model in a Django project. The following snippet code is model.py: from django.db import models from django.db.models.deletion import CASCADE class Model_(models.Model): name = models.CharField(max_length=50, default="This is a model") frequently = models.FloatField(default=1.0) def __str__(self): return self.name class SubModel(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=8, default='0x') model_ = models.ForeignKey(Model_, on_delete=CASCADE) def __str__(self): return self.name class Metadata(models.Model): key = models.CharField(max_length=100) value = models.CharField(max_length=100) sub_model = models.ForeignKey(SubModel, on_delete=CASCADE) This is my admin.py script: from django.contrib import admin from nested_inline.admin import NestedTabularInline, NestedStackedInline,\ NestedModelAdmin from <my model app>.models import Model_, SubModel, Metadata class MetadataAdmin(NestedTabularInline): model = Metadata extra = 1 class SubModelAdmin(NestedStackedInline): model = SubModel inlines = [MetadataAdmin] extra = 1 class Model_Admin(NestedModelAdmin): model = Model_ inlines = [SubModelAdmin] list_display = ['name'] admin.site.register(Model_, Model_Admin) Question: What is the difference between NestedStackedInline and NestedTabularInline in admin.py script? [NOTE]: Versions: Python 2.7 and Django 1.11 -
Lines before form.save() are not saving the right values
I have a view with model form, the ModelForm doesn't really contain all fields in the model. other fields I've used the methods of form.field = value before form.save(), but all of this fields being saved as default. none take the value am trying to give. here are the code : def PostAd(request): ad_post_form = AdPostForm() if request.user.is_authenticated: obj = Account.objects.get(user=request.user) if request.method == "POST": ad_post_form = AdPostForm(request.POST, request.FILES) if ad_post_form.is_valid(): ad_post_form.created_by = request.user if obj.role == 'admin': ad_post_form.is_active = True ad_post_form.save() return redirect('home') else: ad_post_form = AdPostForm(request.POST, request.FILES) else: if request.method == "POST": ad_post_form = AdPostForm(request.POST, request.FILES) if ad_post_form.is_valid(): otp_number = random.randint(100000, 999999) ad_post_form.otp = otp_number ad_post_form.is_activated = False ad_post_form.save() current_id = ad_post_form.id current_contact_email = request.POST.get('contact_email') email_url_active = str(settings.URL_LOCAL) + 'new_ad/adidnumberis' + str( current_id) + '/needactivate/activate/' + str(otp_number) + '/' email_msg = "Please Confirm adding the Ad to Jehlum. Click link " + email_url_active email = EmailMessage('Active Email', email_msg, to=[current_contact_email]) email.send() return redirect('home') else: ad_post_form = AdPostForm() context = { 'ad_post_form': ad_post_form, } return render(request, 'pages/post-ad.html', context) the problem is ad_post_form.is_active = True is being saved as False(default) also ad_post_form.otp = otp_number is being saved as 0 (default) and i need to give the spicific values i assigned here … -
how do i add data to django model according to choices
suppose i have a model : class DataA(models.Model): created = models.DateTimeField(auto_now=True) name = models.CharField(max_length=60) TYPE = ( ('N', 'Select Type'), ('S', 'Student'), ('P', 'Professional'), ) data_type = models.CharField(max_length=1, choices=TYPE, default='N', validators=[type_val]) student = models.CharField(max_length=60, default=None) professional = models.CharField(max_length=60, default=None) and view : class DataACreateView(CreateView): model = DataA fields = '__all__' template_name = 'api/view.html' def form_valid(self, form): # here want to save data according to data_type in the model if it a S only student value must save if it is P only professional value must save return HttpResponseRedirect(reverse('create')) I tried it says values are immutable and I understand it but how to fix this -
How to have two type of users with different logins using Django?
I have two type of Users Artist and Customer. so far I have this in models.py class User(AbstractBaseUser, PermissionsMixin): Email = models.EmailField(unique=True) USERNAME_FIELD = 'Email' objects = MyUserManager() class Customers(models.Model): User = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) CustomerID = models.AutoField(primary_key=True) class Artists(models.Model): User = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ArtistID = models.AutoField(primary_key=True) I use Email as authentication, and it is good until an Artist wants to be Customer too. and he/she can't have two accounts one as Customer and another as Artist with the same Email. here my questions: 1. Is this way of implementation correct? if not, how to do that? 2. what is the best way to have a user be Artist and Customer at the same time? Is this have security issues? -
It is not possible to install the chanels in conjunction with docker
I ran into a very interesting mistake I began to consider the django-chanels and can not start the chanels on docker-compose + gunicorn + nginx. My application is working fine, but the channels are started when the server starts. For example: I added "channels" to INSTALLED_APPS and start my containers. When starting the server, I should get an error, because there is no this string: ASGI_APPLICATION = 'my-app.routing.application'. But there is no error. If I run a server without dockers, only with the command: python manage.py runnserver, then I get this error. I'm thinking about nginx or gunicorn.conf, but I do not understand how they can influence this. If necessary, this command starts my server: gunicorn --config app/gunicorn_config.py myapp.wsgi:application. Any idea? -
Django template within a for loop
I have a for loop that looks like this: <ul> {% for post in latest_post_list %} <li>{{ post }}</li> </ul> {% empty %} <p>No posts are available.</p> {% endfor %} But it looks super ugly. I want to wrap each post object in a template, so for example: {% for post in latest_post_list %} {% include jobposttemplate.html %} {% empty %} {% include noposts.html %} {% endfor %} jobposttemplate.html will then include all the various information held within the JobPost model. I tried: {% for jobposttemplate.html in latest_post_list %} {{ jobposttemplate.html }} {% empty %} {% include noposts.html %} {% endfor %} But, predictably, it didn't work. Basically I'm just trying to avoid having to having to write the html out each time, e.g.: {% for post in latest_post_list %} <div style="blah">{{ post.deadline }} </div> <div style="schmah">{{ post.created_at }} </div> {% empty %} <p>No posts are available.</p> {% endfor %} -
Curious, why can't I retrieve attribute of my own Django Form class?
In a Django project shell(Python 3.5 + Django 1.11), I tried the following statements: from django import forms class ContactForm(forms.Form): subject = forms.CharField() email = forms.EmailField(required=False) message = forms.CharField() print( ContactForm.subject ) But I can not fetch my ContactForm.subject attribute. I got error message: AttributeError: type object 'ContactForm' has no attribute 'subject' Why is it so? Is it caused by some hidden Python language trick? -
Django pagination show me all objects beginning with second page
I made pagination in the standard way, but from the second page on the page all the objects are visible. All subsequent pages contain the same data. If I return to page one from any other page, then I can see all existing objects on it views.py def viewtrainers(request, slug): trainers_list = Profile.objects.filter(city__slug = slug) page = request.GET.get('page') paginator = Paginator(trainers_list, 10) try: trainers = paginator.page(page) except PageNotAnInteger: trainers = paginator.page(1) except EmptyPage: trainers = paginator.page(paginator.num_pages) return render(request, "trainers.html", {'trainers':trainers}) template.html {% if trainers.has_other_pages %} <ul class="pagination justify-content-center" style="margin:20px 0"> {% if trainers.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ trainers.previous_page_number }}">&laquo;</a></li> {% else %} <li class="page-item disabled"><span class="page-link" >&laquo;</span></li> {% endif %} {% for i in trainers.paginator.page_range %} {% if trainers.number == i %} <li class="page-item active"><span class="page-link">{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if trainers.has_next %} <li class="page-item"><a class="page-link" href="?page={{ trainers.next_page_number }}">&raquo;</a></li> {% else %} <li class="page-item disabled"><span class="page-link" >&raquo;</span></li> {% endif %} </ul> {% endif %} -
local variable '' referenced before assignment - using modelforms in view
I'm trying to using the form in my views, but checking either if the user is logged on or not to change some fields depending on it. here are my views.py def PostAd(request): if request.user.is_authenticated: obj = Account.objects.get(user=request.user) if request.method == "POST": ad_post_form = AdPostForm(request.POST, request.FILES) if ad_post_form.is_valid(): ad_post_form.created_by = request.user if obj.role == 'admin': ad_post_form.is_active = True ad_post_form.save() return redirect('home') else: ad_post_form = AdPostForm(request.POST, request.FILES) else: if request.method == "POST": ad_post_form = AdPostForm(request.POST, request.FILES) if ad_post_form.is_valid(): ad_post_form.created_by = 'guest' otp_number = random.randint(100000, 999999) ad_post_form.otp = otp_number ad_post_form.save() return redirect('home') else: ad_post_form = AdPostForm() context = { 'ad_post_form': ad_post_form, } return render(request, 'pages/post-ad.html', context) for some reason. the variable ad_post_form goes out of scope in a specific step that I can't find out. so it gives me the error local variable 'ad_post_form' referenced before assignment. -
Sessions and access 'previous page' in template
In some cases I need to know the previous page. For example: the user LogOut and I want to keep the user on the same page. The user is on the Delete page, and hit cancel and I want to return him, back on the previous page. So, I'm thinking that I can add the page to the session as a variable, and when the user go to the next page, to access this variable. I need: 1) to use it global 2) to overwrite the variable value used for previous page, but not before I retrieve it, if I need it 3) access it in template -
How do I run docker image on my local machine and use postgres service same way I do in gitlab-ci?
I have setup GitLab-CI to run selenium tests for Django. On my local machine selenium tests run without any issue. On my local machine approach is very strightforward I lunch a dev server with python manage.py runserver in one console, and start selenium tests by passing SERVER_URL as "http://localhost:8000". Simple. It works. Inside docker image, I try to do same sort of thing, I start a server on "http://localhost:8000" and then run selenium tests, however tests in this case fail. From error reports I guess that there is a problem with lunching django server, but I am not sure. My GitLab-CI: image: <docker image on my private repository> stages: - test - deploy services: - postgres:9.3 variables: POSTGRES_DB: <my db> POSTGRES_USER: <my user> POSTGRES_PASSWORD: <my password> uTests: stage: test script: - ./run_utest.sh tTests: stage: test script: - mv settings.ini.ttest settings.ini - ./run_ttest.sh iTests: image: <docker image for selenium tests> stage: test before_script: - . ~/vml/bin/activate - mv settings.ini.itest settings.ini - ./manage.sh migrate_schemas --shared script: - ./manage.sh runserver & - ./run_itest.sh -e :3 artifacts: when: always paths: - logs/ The "./run_itest.sh -e :3" is a bash script which starts runs python tests, -e options means "start Xvfb on screen 3". So, … -
How to access a ForeignKey Object's attribute on a dynamic basis
I'm currently trying to access the ForeignKey to attribute in a for loop as I require it to be dynamic. Neither django's docs nor online search delivered any helpful results. Here's what I'm using: Django 1.11 with Django CMS 3.5.2 and Django Countries package. The error message is: AttributeError: 'ForeignKey' object has no attribute 'to However, accessing the field's name or verbose_name or even choices attribute (for charFields or IntegerFields) works. models.py company = models.ForeignKey(verbose_name=_('Company'), blank=False, null=False, to='accounts.CompanyName', on_delete=models.CASCADE) views.py def generate_view(instance): model = apps.get_model(app_label='travelling', model_name=str(instance.model)) data = dict() field_list = eval(instance.fields) fields = model._meta.get_fields() output_list = list() for field in fields: for list_field in field_list: if field.name == list_field: options = list() if field.__class__.__name__ == 'ForeignKey': print(field.to) # Here's the error elif field.__class__.__name__ == 'CountryField': for k, v in COUNTRIES.items(): options.append((k, v)) # Works properly elif field.__class__.__name__ == 'ManyToManyField': pass # Yields the same issues as with foreign keys output_list.append({ 'name': field.name, 'verbose': field.verbose_name, 'options': options, 'type': field.__class__.__name__ }) return data -
Facebook signup / linking in django rest with custom manual login
What is the end-to-end architecture to implement Facebook signup/linking in Django rest when using custom manual login which has mobile number as the primary key ? Also what is the best and most efficient way to do this. ? -
Convert Postgres raw query to Django Orm Query
I have a userpoints table with ( user_id, total_points and total_time ) fields. If i want to get a rank list based on total_points and total_time i can do this like SELECT *, dense_rank() OVER ( ORDER BY total_points DESC, total_time ASC ) AS rank from userpoints And using django orm this can be done as UserPoints.objects.annotate( rank=Window( expression=DenseRank(), order_by=[F('total_points').desc(), F('total_time').asc()])) If i want to get a specific user_id from this i can do this by SELECT *, from ( SELECT *, dense_rank() OVER ( ORDER BY total_points DESC, userpoints.total_time ASC ) AS rank from userpoints ) as u INNER JOIN userpoints on u.user_id = userpoints.user_id where userpoints.user_id='users_uuid' How to do this second query with django orm ? -
django template with pandas
below is code in the views.py def detail(request): ...... v_context={ "data":df.to_dict('records'), } return render(request,'detail.html',context=v_context) in the template {% for i in data%} <table style="width:100%"> <tr> <th>date</th> <th>close</th> </tr> <tr> <td>{{i.date}}</td> <td>{{i.close}}</td> </tr> </table> {%endfor %} ================ end code=== Just wonder why in template, not using i['data'] or i['close']. Thanks -
How to render datetime.datetime with timezone to the HTML template in Django?
views.py def myVideo(request, id): myVideo = MyVideo.objects.filter(id=id) serializerClassVideo = MyVideoSerializer(myVideo,many=True) print(type(myVideo[0].upload_time)) print(myVideo[0].upload_time) myDate = datetime.now() print(type(myDate)) print(myDate) return render(request, 'video.html', { 'myDate': myDate, 'videos': serializerClassVideo.data, } ) in the console, output like this: <class 'datetime.datetime'> 2018-05-30 19:52:20+00:00 # video.upload_time <class 'datetime.datetime'> 2018-08-05 13:47:57.653627 # datetime.now() video.html {{ myDate|date:"Y-m-d" }} {{ v.upload_time|date:"Y-m-d" }} On the html page, the first line above shows: 2018-08-05 which is great, and the second one, that I need, shows nothing. I thought the issue should be related to the timezone in the "upload_time" field, what should I do if I don't wanna change anything of this field (which means keep the timezone of "upload_time")? -
StringRelatedField not working as expected
I have models, class Reporter(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Article(models.Model): title = models.CharField(max_length=100) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.title and serializer, class ReporterSerializer(serializers.ModelSerializer): article = serializers.StringRelatedField(source='article_set') class Meta: model = Reporter fields = '__all__' and views class ReporterAPI(viewsets.ModelViewSet): queryset = Reporter.objects.all() serializer_class = ReporterSerializer Everything seems fine, but, my response showing something weird response Here is the RESPONSE IMAGE The response article is showing wrong output -
Django 2 Login Registration
I'm Prety new in Django. After a few google search, I find full CRUD and I know how to handle that. But in User registration, I fell some problem all over the online every one uses Form.py to handle registration form but I don't want to use Form.py I like to customize it. So When I create a password I use make_password((request.POST.get('password')) but the problem is when I use auth for login then Django auth says it's a wrong password I use auth.authenticate(email=email,password=password) for login check Is anyone please explain custom login registration without using Form.py with some example. -
How can you run an extra thread with a tornado server?
I've got a tornado server serving a django app that is working. I've got a mattermosrdriver that connects to a mattermost server that is working. I'm trying to get both working together but starting one blocks the other. I tried threading one process and got "RuntimeError: There is no current event loop in thread 'Thread-1'" def main(): wsgi_app = tornado.wsgi.WSGIContainer( django.core.handlers.wsgi.WSGIHandler()) tornado_app = tornado.web.Application( [ (r'/static/(.*)', NoCacheStaticHandler, {'path': 'static'}), ('/hello-tornado', HelloHandler), ('/websocket', WebSocketHandler), ('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app)), ]) server = tornado.httpserver.HTTPServer(tornado_app) server.listen(options.port) instance = tornado.ioloop.IOLoop.instance() p = threading.Thread(target=mattermost_chat,args=(instance,)) p.start() instance.start() def mattermost_chat(parameter): print(parameter) chat = Chat() chat.login() chat.connect() if __name__ == '__main__': #mattermost_chat() main() Example run. (env-bd2l-csmu-int-app01-python-3) csmu@int-app01:~/bd2l-django$ ./tornado-server.py Loading environment /home/csmu/bd2l-django/api/settings.py /home/csmu/bd2l-django/api/.env <tornado.platform.asyncio.AsyncIOMainLoop object at 0x7f5fb9631080> {'scheme': 'http', 'url': 'localhost', 'token': '8ttjc63cdbr58y6jr7huj75q3a', 'port': 8065} {'last_name': 'Processor', 'timezone': {'useAutomaticTimezone': 'true', 'manualTimezone': '', 'automaticTimezone': ''}, 'position': '', 'username': 'bd2l-processor', 'create_at': 1533167906430, 'notify_props': {'push_status': 'away', 'mention_keys': 'bd2l-processor,@bd2l-processor', 'desktop_sound': 'true', 'desktop': 'mention', 'email': 'true', 'comments': 'never', 'channel': 'true', 'first_name': 'false', 'push': 'mention'}, 'roles': 'system_user system_user_access_token', 'update_at': 1533169925778, 'auth_service': '', 'last_password_update': 1533167906430, 'id': 'duicxyoipbg7tkegjh1sro6ndo', 'nickname': '', 'delete_at': 0, 'email': 'bd2l-processor@bd2l.com.au', 'locale': 'en', 'first_name': 'Mipgen', 'auth_data': ''} Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line … -
Creating custom user model when a new user is created with Django-rest-auth
I'm building a DRF app with Django-rest-auth implemented for social login. The problem I'm having now is that I want to extend my User Model, but I'm afraid if I change the User Auth Model migrations will complete destroy my project due to the rest-auth link. So my option is to create a UserData field and hook it to User through a one to one field. However, I'm not sure how to instantiate a new UserData object and link it to the User every time a new user is sign up or created through Django-rest-auth api. Any help and advice for this would be appreciated. -
How to update update image file without any exception in django?
I just wanna update image like if no image is selected then the previous stored image path will be stored and if any image selected then selected value will be replaced with previous value. But it giving me exceptions, please some body help me. enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here -
python - Understanding ModuleNotFoundError: No module named '__main__.xxx' (Relative Imports)
For example I have this package: └── package │ __init__.py │ first.py │ second.py and in my first.py #first.py def foo(): pass in second.py #second.py from .first import foo if __name__=='__main__': foo() Now if i try to execute the second.py as: $ cd package $ python3 second.py I got this error: ModuleNotFoundError: No module named '__main__.first'; '__main__' is not a package why does this happen? -
Failed building wheel for mysqlclient and myslq-python
I am trying to install mysqlclient for django but I keep getting an error saying Failed building wheel for mysqlclient So then I tried installing MySql-python but got the same error