Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ManyToMany does not save to db Django
I have a ManytoMany field and the results of the CheckboxSelectMultiple don't get saved in the db and i don't understand why. It must be really simple but... Here's the code: models.py class Person(models.Model): last_name = models.CharField(max_length = 50) first_name = models.CharField(max_length = 50) def __str__(self): return self.last_name +" "+self.first_name class Event(models.Model): owner = models.ForeignKey(User, on_delete=models.SET_NULL, null = True) person = models.ManyToManyField(Person) forms.py class EventForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.get('user',None) #self.user = kwargs.pop('user',None) super(EventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' #self.helper.form_action = reverse_lazy('simpleuser') self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success')) class Meta: model = Event fields = ['person'] widgets ={ 'person': forms.CheckboxSelectMultiple, } views.py def uploadevent(request): if request.method == "POST": form =EventForm(request.POST) if form.is_valid(): event = form.save(commit=False) event.owner = request.user event.save() else: form = EventForm() return render... -
Automatic creation of database view from Django
Maybe this question also is similar to something like "automatic execution of raw SQL code just before creating exact one special model in models.py with managed=False". For example, I have 3 models in models.py (default User, UserTypes and relation between them): from django.contrib.auth.models import User class UserTypes(models.Model): type = models.TextField(unique=True) class Meta: db_table = 'user_types' class UsersHaveTypes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) type = models.ForeignKey(UserTypes, on_delete=models.CASCADE) class Meta: db_table = 'users_have_types' unique_together = (("user", "type"), ) I have few types of users one of which is clients. Now I want to create endpoints "/clients", which will work as a usual model (CRUD). Right now, I just add this in models.py: class Clients(models.Model): first_name = models.TextField(blank=True, null=True) last_name = models.TextField(blank=True, null=True) # all another fields from User model, which duplicated in the database view class Meta: managed = False db_table = 'clients' and then I make this by hand in my database backend: Create database view Create a function to make Insert, Update and Delete Create a trigger to trigger this functions. It's a bunch of code and there is nothing special, all worked fine. This all is to make working CRUD on "/clients" endpoint, so, for example, on "Creation", it will … -
Error with migrate of django-firebird
Running the migrate command with django-firebird will result in the following error: It's a problem associated with automatically generated user tables, so it's hard to fix it. I would appreciate any help on how to resolve it. Operations to perform: Apply all migrations: admin, auth, contenttypes, mdlservice, sessions Running migrations: Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length...Traceback (most recent call last): File "C:\Users\emptyspear\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\emptyspear\AppData\Local\Programs\Python\Python35-32\lib\site-packages\firebird\base.py", line 236, in execute return self.cursor.execute(q, params) File "C:\Users\emptyspear\AppData\Local\Programs\Python\Python35-32\lib\site-packages\fdb\fbcore.py", line 3627, in execute self._ps._execute(parameters) File "C:\Users\emptyspear\AppData\Local\Programs\Python\Python35-32\lib\site-packages\fdb\fbcore.py", line 3333, in _execute "Error while executing SQL statement:") fdb.fbcore.DatabaseError: ('Error while executing SQL statement:\n- SQLCODE: -607\n- unsuccessful metadata update\n- MODIFY RDB$RELATION_FIELDS failed\n- action cancelled by trigger (1) to preserve data integrity\n- Cannot update index segment used by an Integrity Constraint', -607, 335544351) The development environment is as follows os : windows10 python : 3.5.4 django : 1.10.8 fdb : 2.0.0 firebird : 2.5(32bit) django-firebird : https://github.com/maxirobaina/django-firebird -
Django: allow language prefix and root url
I have a Django application with multiple languaje, in this moment I have the language prefix activated in this way: urlpatterns += i18n_patterns( ..., prefix_default_language=True, ) And when I load the website in the home url: mysite.com/ it redirects to mysite.com/en/ (the default language) but I need to load mysite.com/ as home without the redirection and mysite.com/en/ also as home (just when the user load that exact url) -
pydev using debug got error ,how to resolve?
pydev debugger: starting (pid: 21100) Traceback (most recent call last): File "D:\python tools\eclipse-java-oxygen-3a-win32-x86_64\eclipse\dropins\plugins\org.python.pydev.core_6.3.2.201803171248\pysrc\pydevd.py", line 1621, in main() File "D:\python tools\eclipse-java-oxygen-3a-win32-x86_64\eclipse\dropins\plugins\org.python.pydev.core_6.3.2.201803171248\pysrc\pydevd.py", line 1615, in main globals = debugger.run(setup['file'], None, None, is_module) File "D:\python tools\eclipse-java-oxygen-3a-win32-x86_64\eclipse\dropins\plugins\org.python.pydev.core_6.3.2.201803171248\pysrc\pydevd.py", line 1022, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Users\Kevin\Desktop\python\django\webapp\app01\views.py", line 12, in from app01.models import FristModel File "C:\Users\Kevin\Desktop\python\django\webapp\app01\models.py", line 8, in class FristModel (models.Model): File "C:\Python27\lib\site-packages\django-1.11.13-py2.7.egg\django\db\models\base.py", line 110, in new app_config = apps.get_containing_app_config(module) File "C:\Python27\lib\site-packages\django-1.11.13-py2.7.egg\django\apps\registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "C:\Python27\lib\site-packages\django-1.11.13-py2.7.egg\django\apps\registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
django datetimefield migration validation error
I haven't been able to figure out how to do what I want (not have to set datetime upon creation of object) and get around this error. Problem occurs when I run python manage.py migrate File "C:\Dev\Python36\lib\site-packages\django\db\models\fields \__init__.py", line 1423, in to_python params={'value': value}, django.core.exceptions.ValidationError: ["Value '' has a invalid date format. Must be in the formatformatet YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]."] My models.py timeToServe = models.DateTimeField(default=None, null=True, blank=True, auto_now=False, auto_now_add=False, verbose_name=get_lang(None, 'time_to_serve')) My migration (0021_auto_xxxx.py) operations = [ migrations.AlterField( model_name='booking', name='time', field=models.DateTimeField( default=None, blank=True, null=True, verbose_name='time'), ), -
i am passing a argument in URL view creating an error
its my view page i am getting an argument from url as offset[and this is my urls page]1 this is the eror page please help -
django modelserializer merge
Using django2.0.2 ptyhon3.4 MySerializer.py class post(serializers.ModelSerializer) class Meta: model = post fields = ("postuid","useruid","content") class reply(serializers.ModelSerializer) class Meta: model = reply fields = ("replyuid","postuid","useruid","content") class postview(serializers.ModelSerializer) reply = reply() post = post() fields = ('reply','post')??? i want like this form {"postview":{"post":{postfield},"reply":[{replyfield}]} how to this postview is not modelserializer? -
Count of likes not showing in django
I am new to django and trying to implement like button in my post_list page. It is howing the option to like, but when I click on it, the page just refreshes. It is not showing the total likes and also I want the page to redirect to post_detail. Can someone please help me regarding this ? Thank you. html <!DOCTYPE html> {% extends 'home.html' %} {% load staticfiles %} {% block content %} <div class="centerstage"> {% for post in post_list %} <div class="post"> <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1> <div class="date"> <p>Published on: {{ post.published_date|date:"D M Y"}}</p> </div> <p><a class='like-btn' data-href='{{ obj.get_api_like_url }}' data-likes='{{ obj.likes.count }}' href='{{ obj.get_like_url }}'> {{ obj.likes.count }} Agree</a></p> <form method = "post"> {% csrf_token %} </form> <a href="{% url 'post_detail' pk=post.pk %}">Comments: {{ post.approve_comments.count }}</a> </div> {% endfor %} </div> {% endblock %} models.py class Post(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(unique=True, blank=True, default=uuid.uuid1) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) likes = models.ManyToManyField(User, related_name='post_likes', blank = True) def get_like_url(self): return reverse("posts:like-toggle", kwargs={"slug": self.slug}) def get_api_like_url(self): return reverse("posts:like-api-toggle", kwargs={"slug": self.slug}) def publish(self): self.published_date = timezone.now() self.save() views.py class PostLikeToggle(RedirectView): def get_redirect_url(self, *args, **kwargs): … -
Django password-reset email shows wrong domain
I've set up a Django project on a Linode server. When I go to /password_reset, fill out the form with an email and hit "submit," the address I enter gets a message with a password reset link. But the subject says "Password reset on Default". The body has the following message: Hello, You received this email because a request was made to reset the password. If you requested this, go to the following page and choose a new password: https://127.0.0.1:8000/reset/MQ/4w9-86d9ad84d3320ddcc5a6/ Your username: my.personal@gmail.com Thank you. How do I set my site's domain or name in the subject? How do I set the correct domain name in the email body? -
Django vs Vue.js/Angular/React
I was hoping someone could explain the difference between Django, to which I think is a web framework vs Vue/Angular/React which are Javascript frameworks. What is the difference between a web framework and a Javascript framework? -
Formatting JSON in Serializer - Django REST
I am new to Django and Django-REST and I was tasked to create a serializer. The output of my serializer looks like this: { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "name": "a", "description": "a", "price": "1.00", "images": [ { "image_addr": "http://127.0.0.1:8000/media/products/Screenshot_from_2018-05-16_15-07-34.png", "product": 1 }, { "image_addr": "http://127.0.0.1:8000/media/products/Screenshot_from_2018-05-16_16-42-55.png", "product": 1 } ] } ] } How can i tweak my serializer in a way that my output would look like this: { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "name": "a", "description": "a", "price": "1.00", "images": [ "http://127.0.0.1:8000/media/products/Screenshot_from_2018-05-16_15-07-34.png", "http://127.0.0.1:8000/media/products/Screenshot_from_2018-05-16_16-42-55.png" ] } ] } The serializers that I am using are: class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = ('image_addr', 'product') and class ProductSerializer(serializers.ModelSerializer): images = ProductImageSerializer(many=True, read_only=True) class Meta: model = Product fields = ('id', 'name', 'description', 'price','images') -
prefetch_related does not work for SerializerMethodField in django REST framework serializer
I have a serializer that has a nested serializer field. I had set up eager loading and everything was working great. However, I had do add some custom filtering to the nested field, which required a SerializerMethodField. After that change, the prefetch_related eager loading is no longer working. How can I optimize a serializer with SerializerMethodField? Here was my initial, working setup: # views.py class MyView(generics.ListAPIView): serializer_class = WorkingSerializer def get_queryset(self): queryset = MyModel.objects.all() queryset = self.get_serializer_class().setup_eager_loading(queryset) return queryset # serializers.py class WorkingSerializer(serializers.ModelSerializer): related_field_name = CustomSerializer(many=True) @staticmethod def setup_eager_loading(queryset): queryset = queryset.prefetch_related('related_field_name') return queryset And here is my changed serializer that doesn't work: # serializers.py class NotWorkingSerializer(serializers.ModelSerializer): related_field_name = serializers.SerializerMethodField('get_related_field') def get_related_field(self, instance): queryset = instance.related_field_name.objects.all() # some filtering done here return queryset @staticmethod def setup_eager_loading(queryset): queryset = queryset.prefetch_related('related_field_name') return queryset -
The view account.views.register didn't return an HttpResponse object
Good day everyone, i'm new to django, i'm working on a project were users can create accounts, i'm using the django registration model. Here's the problem,during registration, if the username the guest wants to use is taken or the passwords entered don't match, it gives this error 'The view account.views.register didn't return an HttpResponse object. It returned None instead.' instead of informing the guest about the errors. views.py def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) # # Set the chosen password new_user.set_password( user_form.cleaned_data['password']) # Save the User object new_user.save() profile = Profile.objects.create(user=new_user) return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form}) -
how to test facebook login with localhost
i'm using django, and want to make facebook login with django-allauth. I made facebook login with few time, and tested it with localhost. But I found out that FB login require https after 2018 march, so when I login fb in local runserver, it gives error like Insecure Login Blocked: You can't get an access token or log in to this app from an insecure page. Try re-loading the page as https://. Is there any way to test fb login in localhost?? -
synchronize the local database with deployed project in Heroku
When I logged in the project deployed on Heroku with a registered account, Learning Log, it starts freshly without any data I have entered in the local project. I'm aware that Heroku employed Postgres while my local database is python's contributed sqlite. Additionally, I ignored the *.sqlite3 in git repository following the tutorial.(When undo the ignore, it not works) I prefer to work locally, push local data to remote and fetch remote to local. How could I synchronize remote with local? -
Building Resilient Spiders Against Inconsistent HTML markup
I want to get player and referee content from this site and store it in a db. At first, when I looked through it, all the players and the referees were in response.css("div.prelims p.indent::text"), and I could use regex to parse the ones with players from the ones with referees. No problem. Then I took a harder look at the rest of the site, only to see that they DO NOT follow this structure consistently. Here is an example: <div class="prelims"> <p class="indent">Text about players.</p> </div> <div class="num" id="p1"> <span class="num">1</span> <p class="indent">Text about players.</p> </div> <div class="num" id="p2"> <span class="num">2</span> <p class="indent">Text about players.</p> </div> <div class="num" id="p3"> <span class="num">3</span> <p class="indent">Text about players.</p> </div> <div class="num" id="p4"> <span class="num">4</span> <p class="indent">Text about players.</p> </div> <div class="num" id="p5"> <span class="num">5</span> <p class="indent">Text about referee.</p> </div> <div class="num" id="p6"> Not only does this page have this 'num' and 'span' that the other page didn't, but my regex, which worked fine on the test page, breaks on the first p class=indent here. What are some general principles of spider design that can make my spider more resilient against all this variability, and still be able to get the results into the … -
writing CLI based on a webpage WUI
I have a web page with no access to its API, I need to write a Command Line Interface based on the Web User Interface in Python. my question is how to start my project. -
ERROR: Pidfile (celerybeat.pid) already exists
I am getting this issue while re-build and re-start cookiecutter-django docker-compose in production. I am able to solve this by either removing all stopped docker containers or by adding rm -f './celerybeat.pid' in /compose/production/django/celery/beat/start.sh similar to /compose/local/django/celery/beat/start.sh. Is there any reason for not including this specific code in production version of compose file? -
django queryset foreignkey model property
Is it possible to create a django queryset using a combination of model fields and @property from a foreignkey model? I have the following models: class Person(models.Model): firstname = models.CharField(max_length=255) prefname = models.CharField(max_length=255,null=True,blank=True) surname = models.CharField(max_length=255,null=True,blank=True) def __str__(self): return str(self.person_name) if self.person_name else '' @property def person_name(self): if not self.surname: if not self.prefname: return self.firstname return self.prefname if not self.prefname: return ''.join([self.firstname,' ', self.surname]) return ''.join([self.prefname,' ', self.surname]) class Task(models.Model): person = models.ForeignKey(Person) status = models.CharField(max_length=255,choices=(('OPEN','Open'),('CLOSED','Closed')) I am trying to create a queryset with: qs = Task.objects.all().values_list('person__person_name','status') I am getting an error on 'person__person_name' that it is not an available field, I guess because person_name is @property and not an actual model field from the foreignkey model. Is there a way around this? Any help much appreciated! -
What's the most sensible and scalable way of retrieving multiple datasets from the same table in Django?
I'm using Django Rest Framework with a Postgresql database to create a REST API to be accessed by mobile app clients. One of my objects represents a user-submitted Post which has various attributes, including date_created and score, which represents a sum of upvotes/downvotes submitted by other users (similar to what's used on StackOverflow), and votes which is the total number of votes that have been cast on the Post. I want the mobile apps to be able to retrieve, say, 50 Post objects at a time and I would like them to be some mix of the newest posts, the most popular (highest score) posts of the past 24 hours, the Posts from any time which are still at 0 votes. I would also like to be able to paginate the results somehow, so that I can fetch another 50 posts once the user has voted on the first 50. Furthermore, I would like to do this in an efficient way such that my implementation will not be so poor as to create a bottleneck if there are a lot of requests being made to the API. The client apps do NOT need to be aware of why a given … -
Pytest use django_db with rest framework
I am trying to get a simple test to work against the real django_db not the test database using the django rest framework. Basic test setup: import pytest from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient @pytest.mark.django_db def test_airport_list_real(): client = APIClient() response = client.get(reverse('query_flight:airports-list')) assert response.status_code == 200 assert len(response.json()) > 0 Running this test I get: ___________________________ test_airport_list_real ____________________________ @pytest.mark.django_db def test_airport_list_real(): client = APIClient() response = client.get(reverse('query_flight:airports-list')) assert response.status_code == 200 > assert len(response.json()) > 0 E assert 0 > 0 E + where 0 = len([]) E + where [] = functools.partial(<bound method Client._parse_json of <rest_framework.test.APIClient object at 0x000001A0AB793908>>, <Response status_code=200, "application/json">)() E + where functools.partial(<bound method Client._parse_json of <rest_framework.test.APIClient object at 0x000001A0AB793908>>, <Response status_code=200, "application/json">) = <Response status_code=200, "application/json">.json query_flight\tests\query_flight\test_api.py:60: AssertionError When just running in the shell using pipenv run python manage.py shell I get the expected results: In [1]: from django.urls import reverse In [2]: from rest_framework.test import APIClient In [3]: client = APIClient() In [4]: response = client.get(reverse('query_flight:airports-list')) In [5]: len(response.json()) Out[5]: 100 Using the following packages: pytest-django==3.2.1 pytest [required: >=2.9, installed: 3.5.1] djangorestframework==3.8.2 django [required: >=1.8, installed: 2.0.5] Is there anyway to get pytest to access the real … -
Type error:View must be a callable or a list/tuple in the case of include() in django 2.0
i have python 3.6 and django 2.0 installed. i keep having this same error...Type error:View must be a callable or a list/tuple in the case of include() in django 2.0 my app urls the app's name is catalog from django.urls import path from django import views urlpatterns = [ path('index/', views.catalog_home, name='catalog_home'), path('category/<category_slug>/', views.show_category, name='show_category'), path('product/<product_slug>/', views.show_product, name='show_product') ] my project urls this is the projects urls from django.contrib import admin from django.urls import path, include from django.views import static urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls'),), path('static/', static, { 'document_root': 'C:/Users/USER1/PycharmProjects/untitled13/static' }), ] my views from django.shortcuts import get_object_or_404, render_to_response from catalog.models import Category, Product from django.template import RequestContext def index(request, template_name='catalog/index.html'): page_title = 'online shop for all items' return render_to_response(template_name, locals(), context_instance=RequestContext(request)) def show_category(request, category_slug, template_name='catalog/category.html'): c = get_object_or_404(Category, slug=category_slug) products = c.product_set.all() page_title = c.name meta_keywords = c.meta_keywords meta_description = c.meta_description return render_to_response(template_name, locals(), context_instance=RequestContext(request)) def show_product(request, product_slug, template_name='catalog/product.html'): p = get_object_or_404(Product, slug=product_slug) categories = p.categories.filter(is_active=True) page_title = p.name meta_keywords = p.meta_keywords meta_description = p.meta_description return render_to_response(template_name, locals(), context_instance=RequestContext(request)) -
Have a ForeignKey with multiple values? Proper solution?
I've decided to embark on the task of creating my own LMS in Django for a final project in my Advanced Python course, unfortunately, I have reached a wall in terms of progress. I have two models. Course model, consists of multiple members (ManyToMany field) Profile model, consists of several courses (ForeignKey field) My question is, how can I have the Profile model linked to multiple courses? Here is my code so far: class Course(models.Model): name = models.CharField(max_length=20) members = models.ManyToManyField(User, related_name=("Members")) def __str__(self): return str(self.name) class Profile(models.Model): role = models.CharField(max_length=1, choices=roles) user = models.OneToOneField(User, on_delete=models.CASCADE) courses = models.ForeignKey(Course) USERNAME_FIELD = 'user' REQUIRED_FIELDS = ['user', 'password', 'role'] def __str__(self): return str(self.user) @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save -
How to use django rq in CBV listview?
i cant figure out how to use django rq in sample queryset class PartnerCatalogueView(generic.ListView): """ Browse all products in the catalogue """ template_name = 'catalogue/partner.html' paginate_by = 9 model = Product context_object_name = 'prod' def get_queryset(self, **kwargs): queryset = super(PartnerCatalogueView, self).get_queryset() queryset = queryset.filter(stockrecords__partner__id=self.kwargs['pk']) return queryset