Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - POST after Get won't work in the view
I'm trying to write a view which will do two things: first it will show an empty form, if the request.method is Get. then it should submit the form into the database, if the method is POST. the problem is, that when the form is submitted and it should POST stuff, the same view won't run, instead it runs the root url of the project. here is the log: (add is the url I've set for this view) [14/Sep/2017 18:27:07] "GET /add HTTP/1.1" 200 1815 [14/Sep/2017 18:27:12] "POST / HTTP/1.1" 200 1683 (add is the url I've set for this view) and the code looks like this: def add_link(request): if request.method == 'POST': form = Form(request.POST) ... else: form = Form() return render(request, 'mytemp.html', {'form': form }) -
Django serializer with the same field, use different request and response
I'm using CreateAPIView with serializer below: class CategorySerializer(ModelSerializer): class Meta: model = Category fields = [ 'id', 'name', 'hexColor' ] class TransactionCreateSerializer(ModelSerializer): categoryz = CategorySerializer(read_only=True, source='category' ) class Meta: model = Transaction fields = [ 'id', 'category', 'categoryz' ] extra_kwargs = {"user": {"read_only": True}} As you can see I have a category and categoryz, I want this category field use id as a request (write_only) and use the CategorySerializer as the response. How can I do that? This code will work but I want to get a 'category' response rather than categoryz This is the response I get now: { "id": 12, "amount": 28.0, "date": "2017-09-14", "attachment": "", "category": 1, "categoryz": { "id": 1, "name": "White", "hexColor": "#FFFFFF" } } I want to change it to : { "id": 12, "amount": 28.0, "date": "2017-09-14", "attachment": "", "category": { "id": 1, "name": "White", "hexColor": "#FFFFFF" } } -
Django: Query to find total based on type
I have employees and types of leaves applied by each person like Casual,sick,vacation,maternity,paternity...I want a table for each employee containing number of leaves approved in different leave_types excluding sat,sun in the current year 2017 Eg: person 1 applied sick leave from 11th sept,Mon 2017 to 13 sept,Wed 2017--3 days person 1 applied Casual leave from 14th ,Thu 2017 to 15 sept,Fri 2017--2 days person 1 applied Vacation leave from 18th ,Mon 2017 to 26 sept,Tue 2017--7 days excluding sat,sun Then I need a table in the form of | leave type|count| | vacation | 7 | | casual | 2 | | sick | 3 | This is for single employee...I need it even for each and every employee models.py class employees(models.Model): emp_name = models.CharField(max_length = 100) emp_loc = models.CharField(max_length = 100) manager_id=models.IntegerField(null=True) class leave(models.Model): employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1') start_date = models.DateField() end_date = models.DateField() l_type=models.CharField(max_length=1) -
Can I use GitHub project in production?
I create project with Django backend and Angular frontend. I wonder whether it is legal to use someone's code from GitHub in my own project which will be deployed and will be profitable in the future? -
Am getting errors in trying to migrate using Django
"I get this error when am trying to start a project on Django. am a new user. kindly help me out. Thanks" (awd) C:\Users\Abdul-Waris\Desktop\awd>django-admin.py startproject muyipicky (awd) C:\Users\Abdul-Waris\Desktop\awd>python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Abdul-Waris\Desktop\awd\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\Abdul-Waris\Desktop\awd\lib\site-packages\django\core\management\__init__.py", line 307, in execute settings.INSTALLED_APPS File "C:\Users\Abdul-Waris\Desktop\awd\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\Abdul-Waris\Desktop\awd\lib\site-packages\django\conf\__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Abdul-Waris\Desktop\awd\lib\site-packages\django\conf\__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Abdul-Waris\Desktop\awd\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 936, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'muyipicky' -
Get newly added forms from django formset
I have a formset as follows: TableAddFormSet = modelformset_factory(Table, form=TableAddForm) The model looks like this: class Table(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) amount_of_people = models.IntegerField() category = models.CharField(max_length=10) reserved = models.BooleanField(default=False) Now the model required the attribute 'restaurant', which I will set on form-submission. Until now I've done the following: for form in formset: form.instance.restaurant = request.user.restaurant which means that even forms that already existed get looped through and updated. Is there a more efficient way to add this attribute to the newly added forms, something like: for form in formset.new_forms(): or is my implementation the most suitable way for solving this problem? -
How can I handle both pk and url values HyperlinkedModelSerializer in Django Rest Framework
Unsure if there is a good way to do this. If I have a ForeignKey relation - something like this: class ModelA(models.Model): modelb = models.ForeignKey(ModelB) class ModelASerializer(serializers.HyperlinkedModelSerializer): pass I am able to properly set modelb if I POST with this as part of the request "modelb": "http://localhost:8000/rest/modelb/1/" Whats the best way to continue to allow for this behavior, but also allow for directly using the pk? "modelb": 1 I've seen a few things reference using something like this, but I'm unable to determine how to properly set this up "modelb_id": 1 -
Docker + Django + Postgres Add-on + Heroku
So I'm running through the following: Created a Dockerfile and a docker-compose.yml to develop a django app locally, nothing to do here, everything works just fine. Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ All it does is fetches python3 image, copies the code from my source folder to the docker image Then I'm trying to deploy this to heroku, so I added postgres add-on on heroku apps, and configured it using dj_database_url, with the following command on my settings.py file : DATABASES = {} DATABASES['default'] = dj_database_url.config() After that I pushed my application to heroku using heroku container:push web and it got pushed to my app no problem at all... The final piece is when I open my application using heroku open it says I got an error: Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. This is what get printed on the heroku website Now, when I log using heroku logs -t, it says that exited with code 0, then it crashes What am I missing? … -
djangotables2 shows bullets near pagenumbers
I am new to django-tables2 and was trying out few things. I followed the django-tables2 tutorial of using data from model directly without creating tables with another dataset. However bullets appear near the page numbers area. How do I remove the bullet points? Screenshot of the bottom of page -
Canonical Urls with django wagtail puput
I made my first blog with puput and wagtail. I´m using the following tag for canonical_urls: <link rel="canonical" href="{% block canonical %}{% canonical_url %}{% endblock canonical %}"/> If I open my website with http, it renders http://www.example.com as canonical. If I open my website with https, it renders https://www.example.com as canonical. If I´m not wrong, google will treat http and https as differents pages. Is it possible to set all canonical urls as https only or it doesn´t matter? -
How to solve the error: "No module named psycopg2" (postgreSQL and Django)?
I am quite new to Django, and this is my first time setting up a Databse. I followed tutorials, and created a virtual environment. In this virtual environment, the package psycopg2 is installed (as you can see in the image below). However, when I use the command "python manage.py migrate", the following error appears: "No module named psycopg2". This is strange, because it seems like psycopg2 is installed, and the right virtual environment is linked with PyCharm. Any guidance would be truly appreciated! -
Django view, using passed argument to dynamically set field to update
New to django and trying to pass an argument as the field to update however I get the error "keywords cant be an expression" Is there a proper method of dynamically setting the field? class UpdateUser(AtomicMixin, CreateModelMixin, GenericAPIView): serializer_class = UserSerializer authentication_classes = () def post(self, request): """User registration view.""" User.objects.filter(id=request.data['userID']).update(request.data['fieldToUpdate']=request.data['value']) return Response("Saved", status=status.HTTP_200_OK) -
New versions of html files not being served
I'm using a combination of nginx, gunicorn and django. All works fine except that new versions of html pages are not being served. The old pages continue to be served. I've tried restarting gunicorn and nginx and rebooting the server. Suggestions? -
Django merge Many-To-Many data
I am building IMDB clone in order to learn Django. I'm facing problem when I'm using Many-To-Many relationship with intermediate table. Here are my models: class Role(models.Model): role = models.CharField(max_length=40) description = models.TextField(null=True, blank=True) class Person(models.Model): first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) birth_date = models.DateField() brief = models.TextField() roles = models.ManyToManyField(Role, through='CrewMembership') class Media(models.Model): name = models.CharField(max_length=255) genres = models.ManyToManyField(Genre) poster = models.ImageField(upload_to='posters/%Y/%m/%d', default='posters/Placeholder.png') cast = models.ManyToManyField(Person, through='CrewMembership') ... class CrewMembership(models.Model): media = models.ForeignKey(Media) member = models.ForeignKey(Person) role = models.ForeignKey(Role) character = models.CharField(max_length=255, null=True, blank=True) And here's my view: def person_detail(request, person_id): person = get_object_or_404(Person, pk=person_id) media_list = CrewMembership.objects.filter(member_id=person_id) return render(request, 'main/person_detail.html', {'person': person, 'media_list': media_list}) I really don't know if the database design is good or not but it seems to work. At the moment I'm building the person detail page and I'm having trouble if one person worked as for example director and writer on the movie. I get 2 different rows because the roles are different. How can I merge the data and show for example Christopher Nolan worked as both director and writer? I have attached my current result -
Django templates folder
I want to create a "templates" folder in my project's root folder When I do this: {% extends "base.html "%} I get a "TemplateDoesNotExist" error. Here is my project structure: Here is the template configuration from settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] The logs: (Using Django 2.0.dev20170914122638) -
Resize a drop-down menu
I am very new in Django/Python, and I want to create a drop-down menu. It works well, but the size, the appearance are so strange, but I don't know how to fix it View class StatisticsIndexView(StaffRestrictedMixin, TemplateView): template_name = 'loanwolf/statistics/index.html' def get_context_data(self, **kwargs): context = super(StatisticsIndexView, self).get_context_data(**kwargs) context.update({ 'statistics': Statistics(), 'form': StatisticsBaseForm(), }) return context Model class Statistics(TimeStampedModel): type_choice = models.SmallIntegerField(_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, default=0) def count_nb_loans_per_period(self): pass Form class StatisticsBaseForm(ModelForm): def __init__(self, *args, **kwargs): super(StatisticsBaseForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) class Meta: model = Statistics fields = '__all__' I think I could fix my problem with from crispy_forms_materialize.layout import ( Layout, Div, Field, Row, Column, HTML, Submit ) but it is unclear. Are there anyone here who could help me with that? Here is a picture of what it looks like Drop-Down menu -
redirect does not redirecting properly in django
I am using django 1.10. This is my sample code. The problem is after calling redirection, the address bar populated with the follow addresses. It should directly redirected to google news. But it does not. How can I solve it? def redirect_url_view(request, *args, **kwargs): // done something url = "www.news.google.com/news" return redirect(url) http://localhost:8000/www.news.google.com.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/news And in the console contains following: "GET /www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/news HTTP/1.1" 302 0 Can anybody tell what is the problem!!! -
Use Django Backward Relation to Show Only n Objects
I am currently using Django backward relationships to determine what organizations the logged in user belongs to, and then display leads that belong to this organization. This is how I am accomplishing this in my html template: {% for organization in organization %} <h3>{{ organization.name }}</h3> {% for lead in organization.lead_set.all %} {{ lead.first_name }} {% endfor %} {% endfor %} This however displays all the leads that belong to an organization, is there anyway I can limit the number of leads that show up to say the last 5? Thanks -
Dynamically detecting the text in image and tracing over them
Using Python's Open CV it is possible to detect text and it is also possible to draw lines over Images . So I have task to do like i have to create an application where if a user uploads an image my python code has to detect the text in it and trace them with multiple lines like to create a circuit over it . Please share ideas. Thanks in advance -
Grab only latest object from Q in Django/DRF
queryset = queryset.prefetch_related( Prefetch('drivernote_set', queryset=DriverNote.objects.filter(driver_id__in=queryset).order_by('-date_created') .select_related('owner'), to_attr='notes'), Prefetch('rental_set', queryset=Rental.objects.filter( # Active and reserved rentals Q(state_in=['active', 'reserved'], driver_id_in=queryset) | # Latest returned rental?? Q(state='returned', driver_id_in=queryset)) .select_related('vehicle').select_related('driver'), to_attr='rentals'), ) return queryset Is there any way to grab just the latest object via Q in Django? Let's say I'm trying to pull in all active and reserved rentals, but I only want to pull one rental with state returned (latest)? How would I go about accomplishing that via Q object? Or do I call two queries chain the querysets together? I tried latest() but it does not work. -
Extract field form django model
I have defined the following model: class User(models.Model): userid = models.CharField(max_length=26,unique=True) status = models.CharField(max_length=5) Now I would like to extract the value of my status field for a specific userid that I have saved in my database. I am doing it currently in this way: field = User.objects.filter(userid=id).values('status') Which gives me a Query Set, e.g.: <QuerySet [{'status': 'some status'}]>. However, I am not looking for the Query Set but for the Field string. So I am currently doing a workaround to get the field value: field1 = str(field) field2 = field1.replace("<QuerySet [{'status': '","") field3 = field3.replace("'}]>","") Which returns me: "some status". That is obviously super messy. So what would be the correct way to get the field string "some status" for this example? -
Django to show status of running os command
I am using django to create an app which will take the targets from the text file and then will launch the Nmap scan against the hosts specified. Everything is working fine with the only problem being showing status of the running command on browser's screen.Since I am running the command with os.system(command), I can get the output at terminal from where I have launched the runserver command. But, I am just wondering if there is any way to redirect the output to the web browsers screen. -
ImportError: No module named weather_Core_Engine.weather_DB_Handler
I'm trying to build a project on python using Django on pythinanywhere. I'm not familiar at all with Django so any hints it's more than welcome. I created a Django app called profiles and there i created some db models. so far so good. I'm using sqlite3 and I managed to migrate the db and to correctly start my project. now I have modified the file models.py but while running the migration using the command: "python ./manage.py makemigrations" I have the following issue: "16:11 ~/Mico_Weather_BackTrace $ python ./manage.py makemigrations Traceback (most recent call last): File "./manage.py", line 22, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 353, in execute self.check() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 310, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res … -
django is adding characters to my URL
When people visit my website, django is sometimes randomly adding characters to my URL. (It happens intermittently) name_of_url.com gets re-routed to something like name_of_url.com/KiRkZ/ name_of_url.com/section gets re-routed to something like name_of_url.com/KiRkZ/section Is there a way to remove these characters? It is causing a 404 error for the visitors it happens to. -
Display latest "commentator" username in forum app [Django]
I am creating a forum app, and want to display latest commentator's username(as seen in screenshot): But I have some gaps in information, here is my code so far: Models class Forum(models.Model): """ Forum Model """ forum_author = models.ForeignKey( Profile, related_name='user_forums', null=True, blank=True, on_delete=models.CASCADE ) forum_title = models.CharField( max_length=225, verbose_name=u'Thread Title', blank=False, null=False ) forum_category = models.ForeignKey( 'Category', verbose_name=u'Thread Category', ) forum_content = MarkdownxField() class Comment(models.Model): """ Comment Model """ forum = models.ForeignKey( 'Forum', related_name='forum_comments' ) comment_author = models.ForeignKey( Profile, related_name='user_comments', null=True, blank=True, on_delete=models.CASCADE ) comment_content = MarkdownxField() created_date = models.DateTimeField( default=datetime.datetime.now, ) Forum list views - display all threads ... from app_forum.models import Forum, Comment def forum_list_view(request): forum_list = Forum.objects.all().order_by("-misc_created") return render(request, 'app_forum/forum_list.html' {'forum_list': forum_list}) My single thread views : def forum_single_view(request, pk): forum = get_object_or_404(Forum, pk=pk) forum_comments = Comment.objects.filter(forum=forum.id) paginator = Paginator(forum_comments, 10) page = request.GET.get('page', 1) try: forum_comments = paginator.page(page) except PageNotAnInteger: forum_comments = paginator.page(1) except EmptyPage: forum_comments = paginator.page(paginator.num_pages) return render(request, 'app_forum/forum_single.html', {'forum': forum, 'forum_comments': forum_comments})