Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How/why do unit tests affect each other in a TestCase and how to prevent this behaviour?
I am writing tests for a webapp that is made in Python3.6/Django 2.0 and I have the following situation: class TestFoo(TestCase): def test_a(self): obj = Foo.objects.create(a = "bar") expectation = {"a" : "bar"} self.assertEquals(obj.method_x(), expectation) def test_b(self): obj = Foo.objects.create(a = "baz") expectation = {"a" : "baz"} self.assertEquals(obj.method_x(), expectation) def test_c(self): obj = Foo.objects.create(a = "bar") obj2 = Foo.objects.create(a = "baz") obj.b.add(obj2) expectation = {"a" : "bar", "b" : {"a": "baz"}} self.assertEquals(obj.method_x(), expectation) To my understanding every test is run in isolation, yet when I run test_c alongside test a or b, all tests fail. Basically this: test_a + test_b + test_c = ALL FAIL test_a + test_b = ALL PASS test_c = ALL PASS test_a + test_c = ALL FAIL test_b + test_c = ALL FAIL I have tried: Deleting all Foo objects in teardown (in case this didn't happen), this had no effect Using patch.object, but this was not the behavior I desired because I want to test the method works correctly Sticking test_c in a separate class, this had no effect Running the tests in a certain order (a, then b, then c and first c, then a/b, this resulted in different points of failure; if I … -
How show variable from different model as a field in Profile in DJANGO Admin
Sorry for the lack of knowledge,still learning Django I n my Django admin I have both reports and profiles models. Reports has variables Toxicity and Sportsmanship. https://ibb.co/bVBrsH I am trying to get the variables TOXICITY and SPORTSMANSHIP and display the total of them both as a field in my PROFILE view for admin(eg:total:25),but keep getting an error: ERRORS: : (admin.E108) The value of 'list_display[2]' refers to 'user_report', which is not a callable, an attribute of 'ProfileAdmin', or an attribute or method on 'api.Profile'. from django.contrib import admin from ..api.models import Profile,Report, Game_Api_Connection, Feedback class ReportAdmin(admin.ModelAdmin): def user_report(self): total = TOXICITY + SPORTSMANSHIP return self.user.total admin.site.register(Report,ReportAdmin) class ProfileAdmin(admin.ModelAdmin): list_display = ('birth_date', 'sessions_played', 'user_report') admin.site.register(Profile, ProfileAdmin) -
Check if record exists in Django Rest Framework API LIST/DATABASE
I want to create a viewset/apiview with a path like this: list/<slug:entry>/ that once I provide the entry it will check if that entry exists in the database. *Note: on list/ I have a path to a ViewSet. I wonder if I could change the id with the specific field that I want to check, so I could see if the entry exists or not, but I want to keep the id as it is, so I tried: class CheckCouponAPIView(APIView): def get(self, request, format=None, **kwargs): try: Coupon.objects.get(coupon=self.kwargs.get('coupon')) except Coupon.DoesNotExist: return Response(data={'message': False}) else: return Response(data={'message': True}) But I got an error: _init__() takes 1 positional argument but 2 were given. Is there any good practice that I could apply in my situation? -
Django admin queryset limited to 100 items
Here's the situation: I have a model called Profile. There are currently more than 200 Profile items in my DB. I have another model called Item. These two models have a one-to-one relationship. In the Profile list page I can see all Profile items I have in the DB. Good. In the Item edit page I have a dropdown field (called "profile") that should list all the Profile items in my DB (more than 200). The problem is that it only lists the first 100 items. Also, the same field displays "---------" when the related Profile item is above the 100th in the DB. It's like there's some setting that limit the queryset to 100 in the Django admin. Am I missing something? -
Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got about). Pass the callable instead
from django.conf.urls import url urlpatterns = [ 'chat.views', url(r'^$', 'about'), url(r'^new/$', 'new_room'), url(r'^(?P<label>[\w-]{,50})/$', 'chat_room'), ] can any one please help me -
How to make URL point to next successive element in Django?
I am developing a polling application using Django , it has bunch of questions with multiple options below it .. polling Question and its choices When i click the next button , the question has to change I have question id and i wanted to increment the question id so that when i click the button it points to the next question. I tried doing this <form action="{% url 'polls:detail' question.id+1%}"> <input type="submit" value="Next" name="Next" class="button button5" /></form> But the question.id+1 isn't working ! Can someone please tell me the approach to solve this! -
unauthorized error on view django-rest-framework-social-oauth2
after successful social login i am getting redirected to the SOCIAL_AUTH_LOGIN_REDIRECT_URL = "/users/ldata/" but it's giving the unauthorized error HTTP 401 Unauthorized Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Bearer realm="api" { "detail": "Authentication credentials were not provided." } my settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework_social_oauth2.authentication.SocialAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } AUTHENTICATION_BACKENDS = ( # for Google authentication 'social_core.backends.open_id.OpenIdAuth', 'social_core.backends.google.GoogleOpenId', 'social_core.backends.google.GoogleOAuth2', #linkedin 'social_core.backends.linkedin.LinkedinOAuth', # django-rest-framework-social-oauth2 'rest_framework_social_oauth2.backends.DjangoOAuth2', # Django 'django.contrib.auth.backends.ModelBackend', ) middleware: 'social_django.middleware.SocialAuthExceptionMiddleware', conbtext_processor: 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', installed apps: 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', 'rest_framework', 'users', -
Django one-to-many reverse relationship
I don't understand it's my logic error or something else related to django template condition or django model reverse relationship. you can see result in image marked red 1 and 2 (i want to get result like one) i don't get it how can both condition true at same time in mark 2 here is my model class Contract(models.Model): """ using one to many relation for contract 1. user_a > my_id 2. user_b < friend_id 3. status 0 for pending 1 for accepted 2 for not know """ user_a = models.ForeignKey(User, on_delete=models.CASCADE, related_name='me') user_b = models.ForeignKey(User, on_delete=models.CASCADE, related_name='friend') status = models.IntegerField(default=2) def __str__(self): return self.user_b.username here is my template, what i actually doing here first i checked if result is user self then i don't want to show anything you can see first result (motailab don't show anything it's working fine). (ahsan result also working fine) but problem in tarik result (here both condition true at same time if and else how can i resolve this problem). i have database table created like this table row 1 user_a = motailab user_b = tarik status = 0 table row 2 user_a = motailab user_b = ahsan status = 0 table row … -
How to install django-channels in ubuntu?
I have tried to install django channels using this command. pip install -U channels Getting this error.Anybody can help me out. Downloading/unpacking channels Downloading channels-2.0.2-py2.py3-none-any.whl Cleaning up... Exception: Traceback (most recent call last): File "/home/praneet/pral/myvenv/lib/python-wheels/setuptools-3.3-py2.py3-none-any.whl/pkg_resources.py", line 2482, in _dep_map return self.dep_map File "/home/praneet/pral/myvenv/lib/python-wheels/setuptools-3.3-py2.py3-none-any.whl/pkg_resources.py", line 2344, in __getattr raise AttributeError(attr) AttributeError: _DistInfoDistribution__dep_map During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/praneet/pral/myvenv/lib/python3.4/site-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/home/praneet/pral/myvenv/lib/python3.4/site-packages/pip/commands/install.py", line 278, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "/home/praneet/pral/myvenv/lib/python3.4/site-packages/pip/req.py", line 1266, in prepare_files req_to_install.extras): File "/home/praneet/pral/myvenv/lib/python-wheels/setuptools-3.3-py2.py3-none-any.whl/pkg_resources.py", line 2291, in requires dm = self._dep_map File "/home/praneet/pral/myvenv/lib/python-wheels/setuptools-3.3-py2.py3-none-any.whl/pkg_resources.py", line 2484, in _dep_map self.__dep_map = self._compute_dependencies() File "/home/praneet/pral/myvenv/lib/python-wheels/setuptools-3.3-py2.py3-none-any.whl/pkg_resources.py", line 2508, in _compute_dependencies parsed = next(parse_requirements(distvers)) File "/home/praneet/pral/myvenv/lib/python-wheels/setuptools-3.3-py2.py3-none-any.whl/pkg_resources.py", line 2605, in parse_requirements line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec") File "/home/praneet/pral/myvenv/lib/python-wheels/setuptools-3.3-py2.py3-none-any.whl/pkg_resources.py", line 2573, in scan_list raise ValueError("Expected "+item_name+" in",line,"at",line[p:]) ValueError: ('Expected version spec in', 'asgiref ~=2.1', 'at', ' ~=2.1') Storing debug log for failure in /home/praneet/.pip/pip.log -
Django 1.11 - Profile model with 1-1 link to User model
I tried to create a Profile model (a 1-1 link to User model) by following the instruction in this blog post. But something weird happened: as I create a new user, the Profile model (via the signal) generate the corresponding profiles for the user. However, it generates TWO profiles for a given user_id (which is the Django assigned id in User model). These two profiles are exactly the same except one being a well-defined integer id and one being None (please see the image below). I googled around, but still can't figure out how come this happened. Any help is highly appreciated! -
'User' object has no attribute 'ValidationError'
I'm trying to create a registration form. Everything works fine until I try to raise a validation error in case email already exists. It says, 'User' object has no attribute 'ValidationError' Here's what I did, def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): new_form = form.save(commit=False) mail = form.cleaned_data['email'] if User.objects.filter(email=mail).exists(): raise new_form.ValidationError('Looks like email already exists') else: new_form.save() username = request.POST.get('username') password = request.POST.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect(reverse('accounts:profile')) else: form = RegistrationForm() How can we fix that? -
Prewarming several images in same model with django-versatileimage
I'm successfully using VersatileImage for my django project to prewarm images (i.e. save images at various sizes postsave), but I've come up against a situation where I want my model to have several image fields and I'm not sure how to prewarm them as the code I'm using only seems to allow a reference to a single image field. models.py class Testimonial(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) image = VersatileImageField('image_testimonial', upload_to=upload_location, validators=[file_size], null=True, blank=True) image2 = VersatileImageField('image_testimonial', upload_to=upload_location, validators=[file_size], null=True, blank=True) message = models.TextField(default='', null=True, blank=True) def __str__(self): return self.author.username @receiver(models.signals.post_save, sender=Testimonial) def warm_testimonial_images(sender, instance, **kwargs): testimonial_img_warmer = VersatileImageFieldWarmer( instance_or_queryset=instance, rendition_key_set='image_testimonial', image_attr='image' ) num_created, failed_to_create = testimonial_img_warmer.warm() @receiver(models.signals.post_delete, sender=Testimonial) def delete_testimonial_images(sender, instance, **kwargs): instance.image.delete_all_created_images() instance.image.delete(save=False) This code will only prewarm images that are uploaded to the 'image' file on the model on account of this line: image_attr='image' I'm not sure how to adapt this code to handle image2 as well. Thanks -
Alphabetical names in Django list
I want to to Display my List name as alphabetical order {{ name }} Philip Bosson Alivio and i want to make it like Alivio Bosson Philip can anyone help me i'll appreciate it -
Python use args and kwargs to validate data inside a serializer
Well I am building this django rest api where my users can send some data and I save them into the db. There I need to validate the data send by them prior to saving them to the db. I have already added validators like, def validate(self, value): UnitOfMeasureName = ["Each", "Grams", "Ounces", "Pounds", "Kilograms", "Metric Tons"] if value in UnitOfMeasureName: return True else: return ValidationError('Invalid') inside the serializers but there are several such validations to be achieved for each serializer. So I am searching for a way where I can use one function for all those validations. I am thinking of using of args and kwargs but have no idea how to proceed. Any ideas please. Thanks in advance. -
django development server restarts itself while performing long script
I'm using Django 1.8.1 with MSSQL Server connection. I'm testing this one big function in which I iterate through 250 records and insert each into the SQL server. My problem is that at the middle of the script, the Django server just restarts itself every single time. In the log, there's no error message. it's just a message that I always get when I do "python manage.py runserver". See pasted below. For further info, my function logic is basically: 1. Trigger data pull 2. Get data from an external data warehouse (about 250 records) into a DataFrame 3. For each row in the DataFrame, perform a simple logic and then insert data into Table 1 at SQL Server 4. After step 3, open table 1 at SQL server and perform another logic and update the record on table 1. 5. Return to home page with success / failure message. Can anyone help me troubleshoot this? I don't even see any error message to know where to start. Also if you have any recommendation on how to improve the workflow above (aka may be better way to process large number of record?) please let me know. Thank you all. [08/Apr/2018 23:34:47]"GET … -
Django on Google Cloud Platform
I'm new to programming.I tried a django project.Now i need to put that on google cloud platform,but I'm not sure how to proceed ,i didn't find any clear link or tutorial.Please someone help me.I find the app.yaml and requirements.text file are needed but didn't get what all needed? and how and where to create it. -
Use @StaticMethods in serializer Django Rest Framework
I have a basic question hope your guys help me clear it. I have two serializers which use a same function. I want to define it as a static method and reuse it. Serializer for Article class ArticleDetailSerializer(ModelSerializer): liked = SerializerMethodField() class Meta: model = Article fields = [ 'id', 'self_liked', 'title' ] def get_liked(self, obj): request = self.context.get('request') self_like_obj = Reaction.objects.filter(user=request.user.id, content_type=ContentType.objects.get(model='article'), object_id=obj.id) if self_like_obj.exists(): self_like = Reaction.objects.get(user=request.user.id, content_type=ContentType.objects.get(model='article'), object_id=obj.id).react_type else: self_like = False return self_like Serializer for comment class CommentSerializer(ModelSerializer): liked = SerializerMethodField() class Meta: model = Comment fields = [ 'id', 'self_liked', 'content' ] def get_liked(self, obj): request = self.context.get('request') self_like_obj = Reaction.objects.filter(user=request.user.id, content_type=ContentType.objects.get(model='comment'), object_id=obj.id) if self_like_obj.exists(): self_like = Reaction.objects.get(user=request.user.id, content_type=ContentType.objects.get(model='comment'), object_id=obj.id).react_type else: self_like = False return self_like As you see, two serializer use a general function: get_liked How can I define it as a static methods for reuse? Thanks in advance! -
How to find deadlock threads in python
Does anyone know how to find deadlock threads in python (Django) program? I know how to do in Java as follows (but don't know in Python): ThreadMXBean bean = ManagementFactory.getThreadMXBean(); long[] threadIds = bean.findDeadlockedThreads(); if (threadIds != null) { ThreadInfo[] infos = bean.getThreadInfo(threadIds); ... -
Django issue with passing in arguents to url pattern
I've been following this nifty chat creating tutorial (git for the nifty tutorial) and was able to get it to work perfectly. However, when I tried implementing it to my project I converted the url in the main project to what I have above and the effects are trickling downward. I cant' seem to pass in an argument to a url pattern in a .html page. Here's what I got My main project url.py url(r'^chat/', include("chat.urls",namespace='chat')), My app 'chat's url.py urlpatterns = [ url(r'^$', chat_view, name='chats'), url(r'^<int:sender>/<int:receiver>/$', message_view, name='chat'), ] The app chat's view def chat_view(request): if not request.user.is_authenticated: return redirect('chat:chats') if request.method == "GET": return render(request, 'chat/chat.html', {'users': User.objects.exclude(email=request.user.email)}) HTML page: chat.html {% for user in users %} <p>{{ user }}</p> <a href="{% url 'chat:chat' 1 2 %}" id="user{{ user.id }}" class="collection-item row"> {% endfor %} Error message: Reverse for 'chat' with arguments '(1, 2)' not found. 1 pattern(s) tried: ['chat/<int:sender>/<int:receiver>/$'] Error occurs when I go to http://127.0.0.1:8000/chat/ . When I remove the arguments the page pops up. Anyone have any thoughts on why this is? I tried to take out 'chat' from -
django admin ordering not working
in this as you can saw we change order 1, and order 0 while running it still the same you can saw using the shell title at top and Whats the deal with strings? while this has to be reverse according to the order` Courses/model.py from django.db import models # Create your models here. class Course(models.Model): created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=255) description = models.TextField() def __str__(self): return self.title class Step(models.Model): title = models.CharField(max_length=255) description = models.TextField() order = models.IntegerField(default=0) course = models.ForeignKey(Course) class Meta: ordering = ['order', ] -
Host Dockerized Django project on AWS
I have a Django project which is working fine on my local machine. I want to host the same on AWS, but confused on what service to use and what is the best practice to so. Do I use EC2, create a ubuntu instance on it and install Docker or use ECS ? What is the best practice to transfer my django project to AWS. Do I create a repository on Docker hub ? Please help me explain the best workflow on this. My docker-compose file looks like this: version: '3' services: db: image: mysql:latest restart: always environment: - MYSQL_DATABASE=tg_db - MYSQL_ROOT_PASSWORD=password volumes: - ./dbdata:/var/lib/mysql web: build: . command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db Thanks! -
Django add to ManyToMany on create
so basically I want to mimic the admin page behavior when adding objects to a m2m field, and i must admit... I'm way too lost... at the moment each model has it's own view, but if I add a button to the create objects for the Album model, how do I return the Photo models to the Album view so I can save them? My models.py: class Photos(models.Model): title = models.CharField(max_length=255, blank=True) file = models.FileField( upload_to="Resources/" ) class Album(models.Model): title = models.CharField(max_length=255, blank=True) files = models.ManyToManyField( Photos ) -
Pointing Template Engine to Project Templates Directory
I'd like to store templates that all app templates will extend from. Current layout of project mysite/ -(virtualenv folders...) - wesdrew/ # project root - static/ - templates/ - base.html # simple templates to test loading - wesdrew/ # 'home page' app In wesdrew/settings.py: PROJECT_TEMPLATES='../templates' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [PROJECT_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', ], }, }, ] Is there a way to override the template engine looking for '/templates/wesdrew' -
Django Simple Input --> Python Script --> Output
So I'm new to learning Django and having a hard time. Generally speaking, how would you let the website user input a numerical value, run it through a script which tells you if it is an odd or even number? I know this can be done through HTML but I have more complex calculations in the future and i want to run it through a python script. {% extends "personal/header.html" %} {% block content %} <form action= '' method="post"> {% csrf_token %} {{ form }} <input id='num1' type="submit" value="Submit" onclick="alert("After running the script, we determined your number was...)" /> </form> {% endblock %} This is what {{form}} gives for those wondering Also another question, when do we use models.py or views.py, in some tutorials i've seen them use either or. For this one i used views.py is this wrong? -
NoReverseMatch using through model
This code in my views.py works fine when it was still not in template format def detail(request, entity_group_id): entity_group = get_object_or_404(EntityGroup, pk=entity_group_id) # noqa entity_list = entity_group.members.order_by('name') context = { 'entity_group': entity_group, 'entity_list': entity_list, } return render(request, 'core/detail.html', context) When I changed it into a Generic View a NoReverseMatch comes up... class DetailView(generic.DetailView): model = EntityGroup template_name = 'core/detail.html' def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) context['entity_group'] = EntityGroup context['entity_list'] = EntityGroup.members return context Here is my models.py class Entity(models.Model): name = models.CharField(max_length=30) class EntityGroup(models.Model): name = models.CharField(max_length=20) members = models.ManyToManyField(Entity, through='Membership') class Membership(models.Model): entity_group = models.ForeignKey(EntityGroup, on_delete=models.PROTECT, null=False) entity = models.ForeignKey(Entity, on_delete=models.PROTECT, null=False) How do I set a reverse on the Generic view?