Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name normalize_password
hi can anyone tell me what is exact error and how to solve.i got error in open edx . error posted below. enter code hereile "/edx/app/edxapp/edx-platform/manage.py", line 118, in <module> edx.devstack.lms | startup.run() edx.devstack.lms | File "/edx/app/edxapp/edx-platform/lms/startup.py", line 19, in run edx.devstack.lms | django.setup() edx.devstack.lms | File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/init.py", line 27, in setup edx.devstack.lms | apps.populate(settings.INSTALLED_APPS) edx.devstack.lms | File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/apps/registry.py", line 116, in populate edx.devstack.lms | app_config.ready() edx.devstack.lms | File "/edx/app/edxapp/edx-platform/common/djangoapps/student/apps.py", line 20, in ready edx.devstack.lms | from .signals.receivers import update_last_login edx.devstack.lms | File "/edx/app/edxapp/edx-platform/common/djangoapps/student/signals/receivers.py", line 10, in edx.devstack.lms | from student.helpers import ( edx.devstack.lms | File "/edx/app/edxapp/edx-platform/common/djangoapps/student/helpers.py", line 51, in edx.devstack.lms | from util.password_policy_validators import normalize_password edx.devstack.lms | ImportError: cannot import name normalize_password -
Django rest framework timestamp to datetime
How do you change the timestamp format to datetime using the Django Rest Framework timestamp data is located in database (sqlite) -
Wagtail: change max_length of Page.title
I'm working on a website for a public administration. In this website some pages might have a title which is longer than 255 characters. Is it possible to change the default max_length of the Page title? Thanks for the help I'm using: Python 2.7; Django 1.11; Wagtail 1.13.4; -
Inserting related entity ids over rest
I am working with api built by another company. They created insert endpoint expecting POST payload like this: { name: 'a', surname: 'b', relatedBoards: [ { id: '123' }, { id: '34' }, ] } Where this feels way unneeded and I'd expect to make post with following payload: { name: 'a', surname: 'b', relatedBoards: ['123', '34'] } I don't know python or django rest myself, but this feels like a lot of needed mapping before making the request. Is this true that Django rest framework expects payload like this and it can't be changed? Is there a reason for this data structure? -
Trying to create a chat application using sockets in django
I am creating chat application using django to create a chat app , that will help to establish a chat between user and admin.I have a code written in python that will help to communicate through the terminal , but i am not able to find out the solution , how i attach to frontend eg html, css. server.py # server.py def do_some_stuffs_with_input(input_string): """ This is where all the processing happens. Let's just read the string backwards """ print("Processing that nasty input!") return input_string[::-1] def client_thread(conn, ip, port, MAX_BUFFER_SIZE = 4096): # the input is in bytes, so decode it input_from_client_bytes = conn.recv(MAX_BUFFER_SIZE) # MAX_BUFFER_SIZE is how big the message can be # this is test if it's sufficiently big import sys siz = sys.getsizeof(input_from_client_bytes) if siz >= MAX_BUFFER_SIZE: print("The length of input is probably too long: {}".format(siz)) # decode input and strip the end of line input_from_client = input_from_client_bytes.decode("utf8").rstrip() res = do_some_stuffs_with_input(input_from_client) print("Result of processing {} is: {}".format(input_from_client, res)) vysl = res.encode("utf8") # encode the result string conn.sendall(vysl) # send it to client conn.close() # close connection print('Connection ' + ip + ':' + port + " ended") import time, socket, sys print("\nWelcome to Chat Room\n") print("Initialising....\n") time.sleep(1) s … -
There is problem installing mysql using command prompt , for django
enter image description here This problem arises when after the command [pip install mysqlclient] and red warning arises saying [Failed building wheel for mysqlclient]. error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.12.25827\bin\HostX86\x86\cl.exe' failed with exit status 2 -
how to remove specific form field from validating (is_valid) django
There are four field in django form and i am using is_valid() function to validate, but instead of validating the whole form i want to exclude one field which should not be validate using is_valid() function -
How can I bundle up the input data by users and the numbers generated by my sudoku generator, and pass them to Django?
I've made the sudoku generator and the templates, but now I stuck in posting the whole array(9x9) to Django (i.e. sudoku_checker) for checking the duplicates and determine whether the user can go next game. Here is my template looks like in Django, and you'll see I've indexed/positioned every single table cell, thought it might help with later checking: <table> <caption>Sudoku of the day</caption> {% for row in numbers %} <tr> {% for col in row %} {% if col is 0 %} <td> <input class="d0" size="1" autocomplete="off" maxlength="1" name="{{ forloop.parentloop.counter0 }}{{ forloop.counter0 }}"> </td> {% else %} <td id="{{ forloop.parentloop.counter0 }}{{ forloop.counter0 }}">{{ col }}</td> {% endif %} {% endfor %} </tr> {% endfor %} </table> <button class="btn btn-primary" type="submit">Submit</button> but then what should I do next? Am I correct to use Form method to Post the data to Django? But how can i make sure all the data have been bundled up when passing through for checking, in terms of both the known numbers and unknown numbers(input by users)? any hints please? -
django export data as an csv file with dropdown options
I am working export the searched result in a .csv file Everything working good Issue is How can i display list options as an dropdown in csv file like below. here i am trying Groups as an dropdown options This is my resources.py file from import_export import resources from .models import Attendance, User import import_export from import_export.fields import Field class UserResource(resources.ModelResource): username = Field(attribute='username', column_name='Username') first_name = Field(attribute='first_name', column_name='Firstname') last_name = Field(attribute='last_name', column_name='Lastname') desiredintake = Field(attribute='desiredintake', column_name='Desiredintake') intakeyear = Field(attribute='intakeyear', column_name='Intakeyear') id = Field(attribute='id', column_name='StudentId') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'desiredintake', 'intakeyear', 'id') This is my Export view: def Export_studentscsv(request): if request.method == 'POST': form = ExportStudentscsv(request.POST) if form.is_valid(): data = form.cleaned_data #get course from dropdown value course = data.get('course') # find course id based on course title courseid = Course.objects.get(title=course) #find groups using course id groups = Groups.objects.filter(course=courseid) groupnames = [] for group in groups: groupnames.append(group.name) desiredintake = data.get('desiredintake') intakeyear = data.get('intakeyear') user_resource = UserResource() queryset = User.objects.filter(desiredintake=desiredintake, intakeyear=intakeyear, role=4) if not queryset: return page_not_found(request, "Bad Request") dataset = user_resource.export(queryset) dataset.insert_col(5, lambda row: course, header='Course') dataset.insert_col(6, lambda row: courseid.id, header='CourseId') dataset.insert_col(7, lambda row: groupnames, header='Groups') dataset.csv response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="students.csv"' … -
Show local time in html
I have the django project with the Model to save date_added information. Here's the Model code. class Outputting(models.Model): date_added = models.DateTimeField(auto_now_add=True) And I want to retrieve such date_added information and demonstrate it as the local time in the html. How could I make the transformation? Here's the view.py and html template, but it still show the UTC time. Thx! view.py def results(request): user = request.user data = Outputting.objects.filter(owner=user).order_by('id').values_list('id','date_added') return render(request, "xx.html", {"data": data}) Html: <tr> {% for i in data %} <td style="word-wrap:break-word;"><div class="panel-body" type="datetime-local"><small>{{ i.1|date:'M d Y H:i:s' }}</small></div></td> </tr class="something"> {% endfor %} -
Django error, constantly faced with the same server error even if I start an entirely new application and run it
OperationalError at / no such table: core_document Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.4 Exception Type: OperationalError Exception Value: no such table: core_document Exception Location: C:\Python37-32\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: C:\Python37-32\python.exe Python Version: 3.7.1 Python Path: ['E:\Django\Dec19\simple-file-upload-master', 'C:\Python37-32\python37.zip', 'C:\Python37-32\DLLs', 'C:\Python37-32\lib', 'C:\Python37-32', 'C:\Python37-32\lib\site-packages'] Server time: Wed, 19 Dec 2018 04:22:57 +0000 -
How do I get a list of the categories column, and then list of everything in a single view?
I want a navbar on top of my page with the categories in my model. And when I click on the link to a category, I want a table that lists the items in that category. For whatever reason I just can't get both things to work at the same time. This is my model from django.db import models # Create your models here. class menulist(models.Model): name = models.CharField(max_length=120) description = models.CharField(max_length=500) price = models.DecimalField(decimal_places=1, max_digits=10, default=100.00) category_choices = ( ('breads', 'Breads'), ('cakes', 'Cakes'), ('hotfood', 'Hot Food'), ('porkrolls', 'Pork Rolls'), ('drinks', 'Drinks'), ('MISC', 'Misc'), ) category = models.CharField(max_length=50, choices=category_choices, default='MISC',) dateadded = models.DateField(auto_now_add=True) dateupdated = models.DateField(auto_now=True) img = models.ImageField(upload_to='products/', default='products/blank.jpg') def __str__(self): return self.name This is the view: class ProductAdminView(ListView): template_name = 'menulistapp/product_admin.html' def get_queryset(self): slug = self.kwargs.get("slug") if slug: queryset = menulist.objects.filter(category__iexact=slug) else: queryset = menulist.objects.all() return queryset def get_context_data(self, *, object_list=None, **kwargs): context = super(ProductAdminView, self).get_context_data(**kwargs) categorylist = menulist._meta.get_field('category').choices context = { "category_list": categorylist, "cat": cat, } return context html template: {% extends 'base.html' %} {% block content %} <div class="container "> <ul class="nav nav-pills border-bottom border-top pt-2 pb-2"> {% for i in catname %} <li class="nav-item"> <a class="nav-link" href="/productadmin/{{ i }}">{{ i }}</a> </li> {% endfor %} … -
Foreign key to multiple other tables
I am working on a content management system where a user can create a course for a student to go through. So far my database has Course, Lesson, and Slide models and I want to connect my Slide model to Quiz, HTML, or Video: class Course(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) slug = models.SlugField(max_length=40, unique=True) name = models.CharField(max_length=100) desc = models.CharField(max_length=1000) date_created = models.DateTimeField(default=datetime.now, blank=True) last_updated = models.DateTimeField(default=datetime.now, blank=True) price = models.DecimalField(max_digits=8, decimal_places=2) is_visible = models.BooleanField(default=True) def __str__ (self): return self.name class Lesson(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) name = models.CharField(max_length=100) order = models.IntegerField() def __str__ (self): return self.name class Quiz(models.Model): points = models.IntegerField() # Link to quiz model class HTML(models.Model): content = models.TextField(blank=True) class Video(models.Model): media_path = models.CharField(max_length=150) class Slide(models.Model): lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE) title = models.CharField(max_length=100) slide_type = models.CharField(max_length=100, choices=[("video", "Video"),("image", "Image"), ("text", "Text"), ("quiz", "Quiz")]) notes = models.TextField(blank=True) last_updated = models.DateTimeField(default=datetime.now, blank=True) content = models.TextField(blank=True) reference = models.CharField(max_length=150, blank=True) def __str__ (self): return self.title class QuizQuestions(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question = models.TextField() points = models.IntegerField() Now my slide model could be 1 of 3 things: Text (raw HTML) Video Test How do I design my database slide model so it can either be a link to a Video, … -
"TypeError: unsupported operand types" only when using certain filter
When I use the filter of filter(user=user, product=product) it shows the error of unsupported operand type(s) for /: 'NoneType' and 'int' However, when I only use filter(product=product) it does not show any error. Any solutions? Here is the code snippet that I use in views.py for product in Product.objects.all(): product_total_value = Transaction.objects.filter(user=user, product=product).aggregate(Sum('value')) total = Transaction.objects.aggregate(Sum('value')) percentage = product_total_value['value__sum'] / total['value__sum'] * 100 -
Django creating foreign key references to the wrong tables on database creation
I wiped out the database on my Django app to start again. I did this by deleting existing migrations and then re-running makemigrations and migrate. I of course backed up the database first. I soon ran into an issue; upon submitting a form I was informed that "The table 'topics__old' does not exist". which I thought odd as I have named all my tables and that is not one of them. Here are the relevent models: class Topic(models.Model, FormatDateMixin): topic_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) comment = models.TextField(max_length=150) created_date = models.DateTimeField(default=timezone.now) class Meta: db_table = 'topics' class TopicUpdate(models.Model, FormatDateMixin): update_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) original_topic = models.ForeignKey(Topic, on_delete=models.CASCADE) submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) comment = models.TextField(max_length=150) update_date = models.DateTimeField(default=timezone.now) class Meta: db_table = 'topic_updates' I checked out the database files for the old working version and the current version and I found the following: Original Table: CREATE TABLE "topic_updates" ("update_id" char(32) NOT NULL PRIMARY KEY, ... "original_topic_id" char(32) NOT NULL REFERENCES "topics" ("topic_id") DEFERRABLE INITIALLY DEFERRED, ... New Table: CREATE TABLE "topic_updates" ("update_id" char(32) NOT NULL PRIMARY KEY, ... "original_topic_id" char(32) NOT NULL REFERENCES "topics__old" ("topic_id") DEFERRABLE INITIALLY DEFERRED, ... As you can see when creating the database … -
DJango filter_queryset
I am new to DJango and DRF and have been asked to manage some DJango/DRF related code. After a lot of search I am still unable to find a complete example on how filter_queryset works and how can it be used with different arguments. At some places I see it used like the following, self.filter_queryset(queryset) and at other places it is used with some arguments. It would be helpful if some one can explain the fundamentals like how and when to use it, what are the dependent variables (lookup_field, filter_backends etc...) and arguments and how to set them up. I have searched a lot and also gone through the docs. If i have missed any doc kindly let me know. -
Django queryset returning no data to template despite data existing in database
This is probably a very obvious error, but I've spent almost an hour trying to debug and figure it out, and can't identify why this is happening. My view: def list_animals(request, name=None): animaltypes = animals.objects.filter(animalname=name) template = loader.get_template('/animalpedia/main_page/templates/front_page/list-animal.html') context={'animaltypes': animaltypes, 'name': name} return HttpResponse(template.render(context)) and code in my template: {% for instance in animaltypes %} Animal Name: {{ instance.animalname}} <br /> Animal Category: {{ instance.anicat }} <br /> Animal Family: {{ instance.family }} {% endfor %} Absolutely nothing is returnedin HTML. I know there is data in the database for what is passed to name, without any doubt. What am I missing? -
Customizing django admin view of models
I've the following django model, class Country(Base): name = models.CharField(max_length=255, unique=True) flag = models.CharField(max_length=512, null=True, blank=True) I'm customizing the display on django admin in this way, @admin.register(Country) class CountryAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'flag') This throws up the following error, ValueError: At least one model must be passed to register. What am I doing wrong here? -
How do I get the List Filters similar to the ones in admin console in my list views?
I am writing my first django app and in one of my ListView there will be hundreds of records. I want the user to be able to filter the result. The filter widget in the admin console looks intuitive for any kind of user. But the problem is, I am not sure how I can get them in my List Views. I have briefly looked into the django-filters. But, I am not sure if it can help me achieve similar functionalities. -
Trouble passing variable to view through to template in django
I have a page listing different items, and when an item is selected I want the name of the item clicked on to load an item-detail page, with the item clicked on being the paramter to item-detail. For example, using colors. I have the following excerpt from my views.py: def selected_color(request, name): colors = color.objects.filter(colorname=name) template = loader.get_template('/color_webapp/color_site/colors/templates/colors/selected-color.html') return HttpResponse(template.render({}, request, colorname)) The following excerpt from my urls.py: url(r'^color-detail/(?P<colorname>[\w\-]+)$', views.selected_color, colorname='selected_color'), However, when I try to access my site with /color-detail?name=red, I get the error: missing 1 required positional argument: 'colorname' I have followed tutorials on this and had thought I've done everything correctly. What am I missing? -
Django URLconf not matching localhost root
I'm sure that there is a very simple answer to this question, but I have tried all the other solutions I have seen, and cannot get it to work. I am using an include in the project urls.py at the root to my app urls.py root, but am getting a 404 error. Any help is greatly appreciated. My project urls.py is: urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')) ] And my app urls.py is: urlpatterns = [ re_path(r'^$', views.login), re_path(r'^profile/$', views.profile), ] -
How to connect Django app on DigitalOcean to domain with insecure
I am making a small app that deals with processing files, making static data and allowing users to view and download the new static data. I have not learned how to do this with python manage.py runserver and I currently run this with python manage.py runserver --insecure (I am also not entirely sure who will hack my website or how is this insecure). I am using digitalocean to host the website and I have setup the DNS from Google domains already. However, I am stuck on what to do next. A few searches say that gunicorn and/or nginx, but how do I configure this so that the --insecure part remains? If this is not possible, is there a way I can maintain a tunnel forever? Ngrok seems to close after some time, but if there a tunnel that I can maintain forever, I can simply redirect this website to the tunnel's url. -
Add group to user
I have created 3 groups 1. Staff, 2. Admin, 3. Operational Manager and assigned permission. Now whenever I wanted to add new user I wanted to show the choice field of the group and able to select the group. As per the framework the User and Groups have many-to-many relations and I am trying to implement nested serializer. And as per documentation to add nested data I need to implement create or update method in the serializer but here I am not getting the choice field in group and the data is null. GroupSerializer: class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('name',) UserSerializers: class UserSerializers(serializers.ModelSerializer): groups = GroupSerializer(many=True) class Meta: model = User fields = ('first_name', 'last_name','address','contact', 'email', 'date_of_birth', 'branch', 'groups') def create(self, validated_data): groups_data = validated_data.pop('groups') user = User.objects.create(**validated_data) for group_data in groups_data: Group.objects.create(user=user, **group_data) return user when I wanted to make a post request I am getting : { "first_name": "", "last_name": "", "address": "", "contact": null, "email": "", "date_of_birth": null, "branch": null, "groups": [] } here groups fields are empty. If I try to make a post request it says { "groups": [ "This field is required." ] } -
UNIQUE constraint failed when trying to use ForeignKey
I have the following models.py: from django.db import models class Restaurant(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): return self.name class MenuSection(models.Model): restaurant = models.ForeignKey( Restaurant, on_delete=models.CASCADE, ) food_type = models.CharField(max_length=50) def __str__(self): return self.food_type + " - " + self.restaurant.name class MenuItem(models.Model): MenuSection = models.ForeignKey( MenuSection, on_delete=models.CASCADE, ) food_item = models.CharField(max_length=50) def __str__(self): return self.food_item + " - " + self.restaurant.name When I try to migrate these changes I get the error: " no such column: core_menuitem.id" at the command line and when I try and access /admin it says: "no such column: core_menuitem.id". Does anyone know what the issue is? Thanks in advance -
pdf file doesn't save in Django
I use Django 2.1.4 and use Django sample for create pdf report def some_view(request): # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() # FileResponse sets the Content-Disposition header so that browsers # present the option to save the file. return FileResponse(buffer, as_attachment=True, filename='hello.pdf') It started dowloaded but never finished. What is wrong? Old version works properly def some_view(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response