Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: access list of models belong of admin from admin console
I am sure this question has been asked before but I have not found anything regarding admin console. The database relationship is as follows: Host can have multiple students but a student has only one host (one-to-many or many-to-one depends on how we look at the problem). Below is my model setup: from django.db import models # Create your models here. class Student(models.Model): host = models.ForeignKey("Host", blank=True, null=True) fullname = models.CharField(max_length=255, blank=True, null=True) major = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, null=True) interests = models.CharField(max_length=255, blank=True, null=True) date = models.CharField(max_length=255, blank=True, null=True) attendance = models.IntegerField(blank=True, null=True) university = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = True db_table = 'student' class Host(models.Model): host_id = models.AutoField(primary_key=True) fullname = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) max_guests = models.IntegerField(default=5, blank=True, null=True) preference = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = True db_table = 'person' I can access host of a student by using .host (e.g. Student.objects.first().host) and also from a dropdown in django admin console. I can also access a list of students of a particular host like this: list_of_students_of_first_host = … -
list tables names of postgresql database in django
I use Cassandra Nosql DB as my backend in django application, but i want to connect to postgresql database only to list tables name for this database, i configure it successfully but can't show tables name from database scheme. this is my code in view.py: def postgresConf(request): conn_string = "host='localhost' dbname='demo' user='postgres' password='postgres'" conn = psycopg2.connect(conn_string) corsor = conn.cursor() corsor.execute("SELECT * FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema';") latest_question_list=corsor.fetchall() template = loader.get_template('postgresConf.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) -
ImportError at /accounts/register/ No module named 'honeygen'
i have no idea how to get rid of this error . i did read about change the sys.path but i dont understand how to do it because its not working at all . can someone help me to fix this error ? why i still cannot get rid of this error . its already 4 hours since i try to fix this error ImportError at /accounts/register/ No module named 'honeygen' Traceback: File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adila\Documents\tryFOUR\src\register\views.py" in register 13. user = form.save(commit=False) File "C:\Users\Adila\Documents\tryFOUR\src\custom_user\forms.py" in save 50. user.set_password(self.cleaned_data["password1"]) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\contrib\auth\base_user.py" in set_password 105. self.password = make_password(raw_password) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\contrib\auth\hashers.py" in make_password 79. hasher = get_hasher(hasher) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\contrib\auth\hashers.py" in get_hasher 124. return get_hashers()[0] File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\contrib\auth\hashers.py" in get_hashers 91. hasher_cls = import_string(hasher_path) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\utils\module_loading.py" in import_string 20. module = import_module(module_path) File "C:\Users\Adila\Envs\tryFOUR\lib\importlib\__init__.py" in import_module 126. return _bootstrap._gcd_import(name[level:], package, level) File "C:\Users\Adila\Documents\tryFOUR\src\honeywordHasher\hashers.py" in <module> 11. from honeygen import (generate_word, generate_tough_nut, TOUGH_NUT_PROBABILITY, Exception Type: ImportError at /accounts/register/ Exception Value: No module named 'honeygen' i cannot submit my registration form because i stil have this error . i dont know what … -
How to properly check whitelist in django-registration-redux custom RegistrationView
I'm getting in the code world, starting with python and web, and for my first project I decided to make a system for my college (I believe it's simple). Until now I was solving the problems that came up by looking for tutorials and forums (like stackoverflow). But I'm close to finishing the first part of the project (user authentication), and one of the problems already cost me long hours. I'm using Django 1.11 Bootstrap 4.0 Django registration redux 1.8 Python 3.5.2 This project requires a user creation white-list. Only user with an authorized R.A (nine numbers) and email can register on the site. I did the page to check up (like this one: check up) where the user types their R.A and email, then the system checks if he is able to register (it works very well) After the check-up, the user is redirected to the registration page which is a django-registration-redux page customized, that prepopulate the R.A and email fields with which they were checked (like this: register). The values are passed from allow_registration() to custom_registration using django.sessions. To to this, I've changed the registration URLconfig webapp/urls.py: # ... Imports app_name = 'webapp' urlpatterns = [ # Check … -
Django url giving error
Hey I am getting this error when I try to run my Django server "django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (urls.E004) Your URL pattern [, , , , , , , , , , , , , , , , , , , , , , , , , , , , , ] is invalid. Ensure that urlpatterns is a list of url() instances. events.SystemLog.text: (fields.E121) 'max_length' must be a positive integer. events.SystemLog.type: (fields.E121) 'max_length' must be a positive integer. " I do not know what is wrong. -
How to constantly run a python script on a Webserver
I have just coded a trading algorithm and some analytics software for the stock market which in itself works fine. Since my computer is not always running or internetconnection is not running perfectly I would like to source the script out and put it on a Webserver for example, where it would run all day and night. Do you guys now I could do that? I would also like to build a user interface using django to monitor live performance. Does anybody know what would be necessary to implement these steps? Thanks in advance and kind regards Marcel Kresse -
unresolved error of AbstractBaseUser from the Django example
When I read the Django document: customize user the example did not give the import AbstractBaseUser: class MyUser(AbstractBaseUser): identifier = models.CharField(max_length=40, unique=True) ... USERNAME_FIELD = 'identifier' I don't know how to import it, so there is unresolved error in my project. -
Which web framework is better to start for a good Python 3 programmer, Django or Flask?
I came across a very interesting and widely debated question during an info session on full stack. I was asked to explain why should I choose one of them to start learning and give good reasons for that. One possible answer I provided was choice of Django because of its huge community of developers, but at the same time, I was unaware of flask and its usability. I am more in Data Science and want to know which framework will suit the best to learn for people on same boat. Also not to forget compatibility of Python3 with them, just in case, issues varies with version as well. Please clarify my confusion on selection with your valuable reasoning. -
Django won't change url on redirect
Upon registration I check the user_type and move the user to one of three web pages. It is showing the correct page layout but the url stays the same as the registration page. EG: url says "http://127.0.0.1:8000/users/register/" Page shows: "user type 1 information" I thought using redirect should change the url but it doesn't seem to be working. views.py: def register(request): if request.method == 'POST': form = RegisterForm(data=request.POST) if form.is_valid(): # profile = form.save(commit=False) # profile.user = request.user # profile.save() user = form.save() profile = user.userprofile user_group = form.cleaned_data.get('user_type') profile.user_type = user_group profile.save() # form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user_group = form.cleaned_data.get('user_type') user = authenticate(username = username, password = password) login(request, user) print(user_group) print(type(user_group)) if user_group == '1': return HttpResponseRedirect("/users/business/") # return # HttpResponseRedirect('http://127.0.0.1:8000/users/business/') # return HttpResponseRedirect(reverse('users:business')) # return redirect(request, 'users/business.html') elif user_group == '2': return redirect(request, 'users/student.html') elif user_group == '3': return redirect(request, 'users/tourist.html') # else: # return redirect('main:index') else: print(RegisterForm.errors) else: form = RegisterForm() def business_view(request): # return redirect(request, 'users/business.html') # return HttpResponseRedirect('users/business.html') # return redirect('/users/business/') return redirect('users/business') def student_view(request): return redirect(request, 'users/student.html') def tourist_view(request): return redirect(request, 'users/tourist.html') urls.py urlpatterns = [ # Login page #url(r'^login/$', login, {'template_name': 'users/login.html'}, name='login'), url(r'^login/$', login, {'template_name': 'users/login.html'}, name='login'), #url(r'^login/$', … -
How do I make sure markdown doesn't appear when listing posts in a blog?
I'm building a blog using Django and I just integrated markdown. How do I make sure that the truncated part of the body of a post (which is telling a little of what you'll see when that particular post is opened) doesn't display markdown? I created a template filter markdown: from django.utils.safestring import mark_safe from django import template import markdown register = template.Library() @register.filter(name='markdown') def markdown_format(text): return mark_safe(markdown.markdown(text)) Here's the usage in the post_list.html template {% extends "base.html" %} {% load blog_tags static disqus_tags %} {% disqus_dev %} {% block content %} <div class="jumbotron"> <h1 class="heading-font">Shelter At Your Crossroads</h1> <p class="lead">...some random ass text that could serve as motto or something</p> </div> <div class="container"> <div class="row"> <div class="col-lg-8"> {% if tag %} <h2 class="mb-4">Posts tagged with "{{ tag.name }}"</h2> {% endif %} {% for post in posts %} <div class="card mb-5"> <img class="card-img-top img-fluid" src="{{ post.image.url }}" alt="{{ post.title }}"> <div class="card-body"> <h2 class="card-title"><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2> <p class="card-text">{{ post.body|markdown|truncatewords_html:50 }}</p> <a href="{{ post.get_absolute_url }}" class="btn btn-primary"><i class="fa fa-book" aria-hidden="true"></i>&nbsp;Read More </a> <a href="{% url 'post_share' post.id %}" class="btn btn-outline-secondary"><i class="fa fa-share-alt" aria-hidden="true"></i>&nbsp;Share Post</a> <div class="float-right"> <i class="fa fa-tags"></i> {% for tag in post.tags.all %} <a href="{% url … -
Django form doesn't show available values
I'm quite new to Django... So, I have a model. Notice the two foreign key fields (DeviceProfile model actually has data, but MISMStateSnapshot does not): class MISMWorkflow(models.Model): createdAt = models.DateTimeField(default=timezone.now) currentSnapshot = models.ForeignKey('MISMStateSnapshot', null=True, blank=True, on_delete=models.SET_NULL) device = models.ForeignKey(DeviceProfile, null=True, blank=True, on_delete=models.SET_NULL, related_name='workflows') def get_absolute_url(self): return reverse('{}:workflow_detail'.format(VIEW_NAMESPACE), args=(self.pk,)) And a CreateView: class WorkflowCreateView(generic.CreateView): model = MISMWorkflow fields = '__all__' template_name = 'mism_web/workflow_create_form.html' def form_valid(self, form): form.instance.device = DeviceProfile.objects.get(pk=self.kwargs.get('device_id')) form.instance.createdAt = timezone.now() return super(WorkflowCreateView, self).form_valid(form) And the template: {% extends 'mism_web/base.html' %} {% load material_form %} {% block content %} <form action="" method="POST">{% csrf_token %} <!--{{ form.as_p }}--> {% form form=form %}{% endform %} <input type="submit" name="_submit" class="btn" value="Save" /> </form> {% endblock %} urls: url(r'^workflow/workflow_create/$', workflow.WorkflowCreateView.as_view(), name='workflow_create_new'), This is what I see when I go to create page: There are couple of things wrong with this: I don't see the calendar/clock widget for the DateTimeField (createdAt) that I expected to see here. There's no selection input for either currentSnapshot or device fields (Even though there are devices in the DB) This is not because I am using the django-material plugin. I tested without it and I still get the same "empty" form. What's the cause of this and how to … -
Django how to define kwargs in a url pattern
url(r'^employee/create/(?P<employee_type>[\w-]+)$', staff_member_required(EmployeeCreateView.as_view()), name='employee-create'), I am using the above url config for following url <a href="{% url "myapp_app:employee-create" employee_type=product_eng %}" class="button is-light is-outlined">Create Product Engineer</a> <a href="{% url "myapp_app:employee-create" employee_type=product_dev %}" class="button is-light is-outlined">Create Product Developer</a> But this gives me an error saying matching reverse url is not found. How may I fix this issue -
Django, execute bash command dont work when running with Gunicorn
Im try to execute a bash command to manipulate files and directory, when run with django server execute good, but when running with gunicorn dont execute command, dont show any errors only dont execute. subprocess.call("mkdir testsuper", shell=True) also im try: os.system("command") -
django how to replace the logo title of 'django administrator'
my purpose is remove the the title of "Django administration" with yellow color in every admin page like following screen, please help. thanks. -
Requests parameters with non alphanumeric characters never match on lookup
I'm trying to retrieve a user based on their e-mail address using rest-frameworks ModelViewSet. Things work fine when there are only alphanumeric characters present in the request, however, it fails when characters such as @, . and _ are included. The response returned: { "detail": "Not found." } Where the e-mail address in the request exactly matches that in the database. Here is my current view: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'email' -
Java HTTP Request with Token Authentication
I am trying to make a GET request to a local server I have running. I am having trouble returning the correct data, I am seeing an 'Unauthorized' response. Can anyone spot any glaring issues with this given that the String 'token' is correct. protected Object doInBackground(Void... params) { try { String url = "http://192.168.0.59:8000/events/"; URL object = new URL(url); HttpURLConnection con = (HttpURLConnection) object.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("GET"); con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Authorization:", "Token " + token); //Display what the GET request returns StringBuilder sb = new StringBuilder(); int HttpResult = con.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader( new InputStreamReader(con.getInputStream(), "utf-8")); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); } else { System.out.println(con.getResponseMessage()); } } catch (Exception e) { Log.d("Uh Oh","Check your network."); return false; } return false; }* I was able to get a curl request working from the command line: curl -H "Authorization: Token token" http://0.0.0.0:8000/events/ -
Django: UpdateView for FormSet returns error when delete one or more
First of all, my models simply has a User model and Phone model which is a one-to-many relationship, where each user has many phones. I used the formset feature of django to create a user with many phones in one form with validating duplicates using the class below "CustomBaseInlineFormSet". It is working well, but my problem is in updating the user phones. In the UpdateView: I am getting the phones in the get request, then when adding or updating any field of the phone numbers, even when deleting one of them using the "x" button, it is working well. But, when just clear one of the phone number fields using the keyboard, the formset failed in validation step and returns error (This field is required), although if I added any new empty field, it ignores it. Finally, I want it to regard it as valid if any field is empty and save just the fields that have values. I searched a lot but I am stuck with it. Here is my code: forms.py: class PhoneForm(forms.ModelForm): class Meta: model = Phone fields = ("number",) from django.forms.models import BaseInlineFormSet class CustomBaseInlineFormSet(BaseInlineFormSet): def clean(self): values = set() for form in self.forms: value = … -
Django User Profile Model not saving
I have successfully created a profile model linked with the default Django user model, but I am having some trouble to save the profile with data. When I try to create a user, the default user is created with the data from the requests, but the profile model remains blank. The only field populated is the ID and the FK poiting to the user. HELP! The model: class StudentProfile(models.Model): user = models.OneToOneField(User, unique=True) address = models.CharField(max_length=100, null=True, blank=True) classroom = models.ForeignKey(Class, null=True, blank=True, related_name='classes', on_delete=models.CASCADE) birth = models.CharField(max_length=10, null=True, blank=True) isStudent = models.BooleanField(default=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: StudentProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() The creation method: user, created = User.objects.create_user(username=request.POST['username'], email=None, password=request.POST['password'], is_staff=True) StudentProfile.objects.create(user=user) student = StudentProfile.objects.last() user = User.objects.last() user.profile.address = 'aeaeaeae' student.birth = request.POST['birth'] student.classroom = request.POST['class'] user.save() -
`-p` is for what in creating virtual environment command of Django
Django creates virtual environment alternatively applies command: virtualenv -p python3 . I have typed over 30 times of the commands. The meaning of -p is a ghost for me.To search it several times,I failed to get its explanation. I wonder it might be out of the scope of my concepts and vocabulary. -
Connect Django to existing Docker Postgres container
I have a situation where I need to connect my Django to existing Docker Postgres container. In simple words, when i execute "python manage.py dbshell", django should connect to existing Docker Postgres container. Currently my django is connected to sqlite3 db. Below is my settings.py snippet for connecting to db. DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': 'etag_auth', # 'USER': 'etag_master', # 'PASSWORD': 'thisismypass', # 'HOST': 'cybercom_postgres', # 'PORT': '5432' 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } # 'etag': { # 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': 'etag', # 'USER': 'etag_master', # 'PASSWORD': 'thisismypass', # 'HOST': 'cybercom_postgres', # 'PORT': '5432', # } } I also tried with docker-compose, but i am not able to make docker-compose to connect to existing container. Below is my docker-compose.yml code snippet postgres: external: name: etag_postgres image: postgres ports: - "5432:5432" volumes: - /data/db Kindly help to solve the issue. -
DJango giving me an error when I use user.isAuthenticated
I am working on getting my Clubs website back up and running after our previous coder left. He left nothing behind so now hen I run it Django gives me the error File "/home/serverad/django14_project/my_django15_project/tsa/events/views.py", line 112, in custom500 return render_template('errors/500.mako', request, parent='../base.mako' if request.user.is_authenticated() else '../layout.mako') AttributeError: 'WSGIRequest' object has no attribute 'user' I have no idea what is wrong seeing as though our last programmer left no notes behind. -
import a python file ; custom hashing generator into hashers.py
hye again . how to import my custom password hasher generator ? i have been trying to do it for days now . it still give an error . my project name : tryFOUR my custom password hasher app name: honeywordHasher my custom password hasher generator file name : honey_gen.py i tried : from honeywordHasher.honey_gen import honey_gen it give an error . im confused because the honey_gen.py dont have a class . error : ImportError at /accounts/register/ cannot import name 'honey_gen' Traceback: File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adila\Documents\tryFOUR\src\register\views.py" in register 13. user = form.save(commit=False) File "C:\Users\Adila\Documents\tryFOUR\src\custom_user\forms.py" in save 50. user.set_password(self.cleaned_data["password1"]) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\base_user.py" in set_password 105. self.password = make_password(raw_password) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\hashers.py" in make_password 79. hasher = get_hasher(hasher) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\hashers.py" in get_hasher 124. return get_hashers()[0] File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\hashers.py" in get_hashers 91. hasher_cls = import_string(hasher_path) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\utils\module_loading.py" in import_string 20. module = import_module(module_path) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py" in import_module 126. return _bootstrap._gcd_import(name[level:], package, level) File "C:\Users\Adila\Documents\tryFOUR\src\honeywordHasher\hashers.py" in <module> 4. from honeywordHasher.honey_gen import honey_gen Exception Type: ImportError at /accounts/register/ Exception Value: cannot import name 'honey_gen' -
connection to postgres database fails infrequently
I am connecting to a Postgres database on windows using Django/Pycharm. I have done this plenty of times on other computers and am pretty confident I configured the connection correctly. Every once in a while the database connection fails and returns an error. It happens both in my Django app as well as using the pycharm UI. It is odd because it works at least every 9/10 times I interact with the database, but I've noticed that maybe it usually happens when I try to interact with the db multiple times in quick bursts, but this is not always the case. In the pycharm database connection UI, when I test the connection it usually works, but sometimes fails. I am using the default 'postgres' user, and I suspect that may be the issue. The following is the db configuration in my Django app, though I'm pretty positive this problem is unrelated to my code: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'contract_directory_site', 'USER': 'postgres', 'PASSWORD': 'my_password', } } Everything except the password is exactly how it looks in my code and in my PyCharm database connection properties. -
Django admin Inline Forms not working on production
I have a django admin inline form that works locally but doesn't work on production. Locally: And on Heroku: I don't have a clue why this could be. Any ideas? Any advice will help. This is the code: class OrderAdmin(admin.ModelAdmin): inlines = [OrderItemInline, TiptiItemInline, MessageInline] search_fields = ['client', 'shopper', 'state'] list_display = ['date', 'client', 'state', 'address', 'payment_method'] readonly_fields = ['client', 'address', 'billing_info', 'payment_methods', 'history', 'rate'] -
Django Restful Framework Update Object
I am a Beginner in Django Restful Framework. I want to create a BookAPI, here is my model: models.py book_id = models.AutoField(primary_key=True) book_name = models.CharField(max_length=64, null=False) order = models.IntegerField(null=True) Now I can get the list of books by GET http://localhost:8000/api/books/. And I want to modify the order of books and let every book has a unique order by PUT http://localhost:8000/api/books/orders "Response": [ { "book_id": 1, "order": 1 }, { "book_id": 2, "order": 2 } ] And Here is my serializer.py class OrderSerializer(ModelSerializer): class Meta: model = Book fields=['book_id','order'] so what should I do for update function in serializer.py