Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ACCESS_REFUSED - Login was refused using authentication mechanism AMQPLAIN. For details see the broker logfile
I'm getting this error when I try to perform celery -A draft1 beat in my terminal. Traceback (most recent call last): File "/home/james/postr/env/lib/python3.5/site-packages/celery/apps/beat.py", line 107, in start_scheduler service.start() File "/home/james/postr/env/lib/python3.5/site-packages/celery/beat.py", line 558, in start interval = self.scheduler.tick() File "/home/james/postr/env/lib/python3.5/site-packages/celery/beat.py", line 279, in tick self.apply_entry(entry, producer=self.producer) File "/home/james/postr/env/lib/python3.5/site-packages/kombu/utils/objects.py", line 44, in __get__ value = obj.__dict__[self.__name__] = self.__get(obj) File "/home/james/postr/env/lib/python3.5/site-packages/celery/beat.py", line 411, in producer return self.Producer(self._ensure_connected(), auto_declare=False) File "/home/james/postr/env/lib/python3.5/site-packages/celery/beat.py", line 395, in _ensure_connected _error_handler, self.app.conf.broker_connection_max_retries File "/home/james/postr/env/lib/python3.5/site-packages/kombu/connection.py", line 405, in ensure_connection callback) File "/home/james/postr/env/lib/python3.5/site-packages/kombu/utils/functional.py", line 333, in retry_over_time return fun(*args, **kwargs) File "/home/james/postr/env/lib/python3.5/site-packages/kombu/connection.py", line 261, in connect return self.connection File "/home/james/postr/env/lib/python3.5/site-packages/kombu/connection.py", line 802, in connection self._connection = self._establish_connection() File "/home/james/postr/env/lib/python3.5/site-packages/kombu/connection.py", line 757, in _establish_connection conn = self.transport.establish_connection() File "/home/james/postr/env/lib/python3.5/site-packages/kombu/transport/pyamqp.py", line 130, in establish_connection conn.connect() File "/home/james/postr/env/lib/python3.5/site-packages/amqp/connection.py", line 288, in connect self.drain_events(timeout=self.connect_timeout) File "/home/james/postr/env/lib/python3.5/site-packages/amqp/connection.py", line 471, in drain_events while not self.blocking_read(timeout): File "/home/james/postr/env/lib/python3.5/site-packages/amqp/connection.py", line 477, in blocking_read return self.on_inbound_frame(frame) File "/home/james/postr/env/lib/python3.5/site-packages/amqp/method_framing.py", line 55, in on_frame callback(channel, method_sig, buf, None) File "/home/james/postr/env/lib/python3.5/site-packages/amqp/connection.py", line 481, in on_inbound_method method_sig, payload, content, File "/home/james/postr/env/lib/python3.5/site-packages/amqp/abstract_channel.py", line 128, in dispatch_method listener(*args) File "/home/james/postr/env/lib/python3.5/site-packages/amqp/connection.py", line 603, in _on_close (class_id, method_id), ConnectionError) amqp.exceptions.AccessRefused: (0, 0): (403) ACCESS_REFUSED - Login was refused using authentication mechanism AMQPLAIN. For details see the broker logfile. … -
Django with Cloud SQL on GAE Flexible
My Django app working on GAE with Cloud SQL(MySQL). App requests to www.googleapi.com by New Relic Monitoring. I don't know that requests. (app connecting with cloud proxy) -
Dockerfile run python command not working
I have a dockerfile like this: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ ADD reports /code/ RUN pip install -r requirements.txt ADD . /code/ RUN ls -l /code/reports/report/manage.py # gives expected result RUN ls -l /code/reports/build_static/ # gives expected result RUN python /code/reports/report/manage.py build full_report.views.RenderView # does not work Everything works fine except for the last command which runs a python package (django-bakery) through manage.py build. I don't get any errors. This command should output some files inside build_static directory in the container. If I ssh into the container and run the command manually then it is working. I inserted the full path with /code/ to make sure that they match and created all necessary directories beforehand. This is how I build the container: docker-compose run django /bin/bash This is my docker-compose: version: '3' services: django: build: . volumes: - .:/code ports: - "8000:8000" I wonder how come it is working when I ssh in and run the command manually, but not working with the command in the dockerfile. Thanks! -
Deploying Django app on CentOS 7 with Cpanel/WHM
I am at my wits end. I currently am running CentOS 7 with cPanel and WHM, with python version 2.7.5. I cannot yum install mod_wsgi because I get this error: Error: Package: mod_wsgi-3.4-12.el7_0.x86_64 (base) Requires: httpd-mmn = 20120211x8664 All I am trying to do, is deploy a django app under a specific user, inside of a virtual environment. I have read somewhere, but cannot seem to find it again, about recompiling apache with mod_wsgi. If this is the case, I wouldn't mind recompiling every time apache is updated through easyapache4. I just need to get this app up and running asap. -
Only Want a user to 'like' a comment once. My code is not working
I have Post model, that has a field likes_total on it. I only want a user to be able to like a post once, but the code for this in the view is not working. here is the code: views.py def like(request, post_id, group_id): group = get_object_or_404(Group, pk= group_id) post = get_object_or_404(Post, pk= post_id) likers = [] if request.method == 'POST': if request.user in likers: return render(request, 'groups/detail.html', {'group':group, 'error': "you have already liked this post"} ) else: post.likes_total += 1 post.save() likers.append(request.user) return redirect('/groups/' + str(group_id) ) # post.save() else: return render(request, 'groups/detail.html', {'group':group}) this code seems right to me, cant tell what the problem is.. any help would be really appreciated! -
django series of events containing single and recurring dates
I'm looking for a django app or python package providing a calendar functionality or a well-formed models scheme. It should contain single events and series of events. These series may consist of repeated dates and "irregular" single dates which have some deviant values (e.g. start-time, room). The popular packages like django-schedule ect. don't map my needs. Mostly they only model single dates and/or "simple" recurring dates. If I'm right, the ical standard reflects "my" needs? But is there any package/lib for this kind of "dates/events"? Thanks in advance. -
Django rest insert order
I am doing a small project in Django with the rest framework and I reached a point where I don't really know how to continue. In the application, my customers can order food or drinks, which are then added to the order. I have the following models: Orders order_id = models.AutoField(primary_key = True) customer = models.ForeignKey(Customers, on_delete = None) date = models.DateTimeField(auto_now_add=True) The model Customers is just a OneToOneField from the User model. Food Orders fake_id = models.AutoField(primary_key = True) order_id = models.ForeignKey(Orders, on_delete = models.CASCADE) food_id = models.ForeignKey(Food, on_delete = models.CASCADE) quantity = models.IntegerField() Drink Orders fake_id = models.AutoField(primary_key = True) order_id = models.ForeignKey(Orders, on_delete = models.CASCADE) drink_id = models.ForeignKey(Drink, on_delete = models.CASCADE) quantity = models.IntegerField() So with my models in mind, first I need to create an order, and then create a food order or drink order for each item in the order. The problem I am having is I can't even create the order. I created a serializer and a view, pass the data with postman and nothing, I always get an error. My serializer: class OrdersSerializer(serializers.Serializer): customer = UserSerializer() date = serializers.DateTimeField() class Meta: model = Orders def create(self, validated_data): order = Orders.objects.create(**validated_data) order.save() return order … -
How to order friend by events in commun with Django and DRF?
My models : Profile : class Profile(models.Model): owner = models.OneToOneField('auth.User', on_delete=models.CASCADE, unique=True) def __str__(self): return self.owner.username class FriendShip(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) creator = models.ForeignKey(Profile, related_name="friendship_creator_set", on_delete=models.CASCADE) friend = models.ForeignKey(Profile, related_name="friend_set", on_delete=models.CASCADE) def __str__(self): return self.creator.pseudo + ' - ' + self.friend.pseudo Event : class Event(models.Model): owners = models.ManyToManyField(Profile, related_name='myevents') members = models.ManyToManyField(Profile, related_name='events') location = models.PointField(max_length=40, null=True) title = models.CharField(max_length=200) description = models.TextField(max_length=500) timeStart = models.DateTimeField('start_date', default=now) timeEnd = models.DateTimeField('end_date', default=now) seats = models.IntegerField(default=1) def __str__(self): return self.title class Meta: ordering = ('timeStart',) Now my serializers : class FriendshipSerializer(serializers.ModelSerializer): friend = serializers.HyperlinkedRelatedField(many=False, view_name='profile-detail', queryset=Profile.objects.all()) class Meta: model = FriendShip fields = ('friend',) class ProfileSerializer(FriendlyErrorMessagesMixin, serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') myevents = serializers.HyperlinkedRelatedField(many=True, view_name='event-detail', queryset=Event.objects.all()) events = serializers.HyperlinkedRelatedField(many=True, view_name='event-detail', queryset=Event.objects.all()) friends = serializers.SerializerMethodField() class Meta: model = Profile fields = "__all__" def get_friends(self, obj): serializer = FriendshipSerializer(FriendShip.objects.filter(creator=obj), many=True, context=self.context) return serializer.data When I GET a profile, how can I order his friends by events in common ? How can I count the number of relation in a manytomanyfield in common between two objects ? Thanks -
How to remove ForeignKey constraint in Django?
I have a django application with two tables order and user. Table order has a column user_id which is foreign key to user table. Now i want to migrate user table into a separate microservice. In order to do that i need to break foreign key constraint of user_id column in order table and keep it as a simple integer column. How can this be achieved through Django migrations without dropping the existing column? (Both tables have live data in production system) -
Add extra fields to a ModelAdmin form
So, I have a ModelAdmin that I need to add extra fields to. These fields do not exist on the model, but will be dynamically added to a custom ModelForm through the init method, and logic inside clean will handle the returned data on save. I can't seem to find any solid information related to adding custom non-model fields to a ModelAdmin form. The closest I have come is by overriding get_fields on the ModelAdmin class and updating self.form.declared_fields with the new fields I'd like to add. This just doesn't feel very clean to me and I was curious if there was a better way to add new fields to a ModelAdmin dynamically? -
How to send linux commands on another machine connected via WIFI?
I have a Django project on my laptop. It works perfectly fine. Now, this Django app detects a number plate, matches it with the database, if a match is found, then it must run a motor. To run a motor, I used a Raspberry Pi. So here comes my problem, I must transfer my whole project on Pi, then execute my Django server from there and Pi will be able to control the motor. What I am thinking: What if I run the Django app from my laptop, detects the number plate, if a match is found then somehow I must send a command to my raspberry pi to run the motor. In short, I want the web application to run on machine1 and motor program to run on machine2, and they both are connected via WIFI. I have seen many ways to send a command via ssh but my Pi always ask for a password, so those methods don't work for me. Is there any option I can do that. -
notifications handling angular 4 with djnago backend
i am using following django app for generating notifications https://github.com/django-notifications/django-notifications. It gives usage instructions for simple html and javascript, but angular won't understand those tags out of box. How can i achieve this with angular 4? -
Django: How to iterate over two one-two-many table relationships?
I am trying to build a simple web page that queries three tables. There is a Company table that has a one-to-many relationship with a Position table, as well as a one-to-many relationship with a Project table. The goal is to have the page display a given company once, along with all positions and and projects associated with said company. Then, move on to display the next company, any positions held there and projects completed. Below is the closest I've come to getting this right. But, the obvious problem is that if there is more than one project associated with a given company, you'll see that company listed more than once. I'm new to Django, so in the interest of learning, I wanted to beat my own head sufficiently hard before asking for help; but I could really use some fresh ideas at this point. Models: from django.db import models class Company(models.Model): company_id = models.AutoField(primary_key=True) company_name = models.CharField(max_length=20) company_logo = models.ImageField(upload_to='images/') def __str__(self): return self.company_name class Position(models.Model): position_id = models.AutoField(primary_key=True) position_title = models.CharField(max_length=55) company_id = models.ForeignKey('professional.Company', on_delete=models.CASCADE, blank=True, null=True) begin_date = models.DateField() end_date = models.DateField() def __str__(self): return self.position_title class Project(models.Model): project_id = models.AutoField(primary_key=True) project_name = models.CharField(max_length=55) company_id = models.ForeignKey('professional.Company', … -
Where in a Django class-based view should I check user identity?
I have several views that I need to limit access, in which case I would check that the user requesting a page is the owner of that page (owner is just a ForeignKey for that model). I know the way to do this is to check if request.user == MyModel.owner. However, from a security standpoint I want to know where it makes sense to put this check. For example see one of the views below: class RiskView(LoginRequiredMixin, UpdateView): login_url = '/accounts/login/' model = MyModel #option 1:put it here --> request.user == MyModel.owner fields = ['risk1', 'risk2', 'risk3', 'risk4', 'risk5'] template_name = 'project/risk_form.html' form = ProjectRiskForm #option 2:put it here --> request.user == MyModel.owner def get_success_url(self): return reverse('project:summary',kwargs={'pk': self.kwargs['pk']}) #option 3:put it here --> request.user == MyModel.owner def form_valid(self, form): form.save() return super(ProjectRiskView, self).form_valid(form) So, given the 3 options in the code above, where is the most recommended place to put the check? I assume that option 1 makes the most sense because nothing is exposed before that point? Regardless of where I put it I assume everything that follows needs to be inside that if request.user==MyModel.owner statement? -
Django 1.8 import issue
This is the first time I need to run my app deeper in the directory structure, I have obviously messed up my app structure while setting this up and can't get it right anymore. Could somebody help me out here? In my start.sh file I define following env vars: export PYTHONPATH=${PYTHONPATH}:'/home/ubuntu/workspace/skw/3rd_apps/' export PYTHONPATH=${PYTHONPATH}:'/home/ubuntu/workspace/skw/cskw/' And my dir structure looks like this: /home/ubuntu/workspace/skw/start.sh (also manage.py and gulpfile) /home/ubuntu/workspace/skw/3rd_apps/ (django is here) /home/ubuntu/workspace/skw/cskw/ (contains __init__.py) /home/ubuntu/workspace/skw/cskw/apps/ (contains __init__.py) /home/ubuntu/workspace/skw/cskw/core_app/ (settings.py is here and __init__.py) I cycle between two errors here: 1. When trying to setup a custom signup form: ACCOUNT_SIGNUP_FORM_CLASS = 'core_app.forms.SignupForm' The form is in place but i get this error: django.core.exceptions.ImproperlyConfigured: Module "core_app.forms" does not define a "SignupForm" class And if I fix this I can not import anything from apps, it expects them to be in core_app and does not see the app module at the same level as core_app. manage.py points to "core_app.settings", so do the variables in settings.py. -
react + django: accessing django admin
I have react app on port 3000 and django server on 9000. I can access django admin page like this: localhost:9000/api/admin/, but when I try localhost:3000/api/admin/ I get redirected back to localhost:3000 (or nothing happens if redirect is commented out). Djnago won't be exposed in production, so admin and other pages won't be accessible. Requests from front-end work fine. -
Update a Model Field when DetailView encounter. [Django]
I have a DetailView something like in views.py: views.py class CustomView(DetailView): context_object_name = 'content' model = models.AppModel template_name = 'dynamictemplate.html' def get_context_data(self, **kwargs): data = super(CustomView, self).get_context_data(**kwargs) <...snipped...> return data How could I update the model field, an IntegerField when the request from urls.py transfers to views.py. Let's suppose the name of IntegerField is clicks and when a user visits a particular link or passively, a model object from database, then how could I increment the clicks field of that object by 1. -
user.has_perm is false even though I can see it both in admin page and user.user_permissions
I am trying to test a permission. The code for permission is this in "customAuth.permissions.py" content_type = ContentType.objects.get_for_model(Soru) can_see_soru_list = Permission.objects.create( codename="can_see_soru_list", name="Can See The List", content_type=content_type, ) I have a customUser model that is almost same as normal User object. class customUser(AbstractUser): name = models.CharField(max_length=255) def __str__(self): return self.name The problem is, I added the permission to an instance of "customUser" in shell and checked it with user.has_perm("can_see_soru_list"). This returned False. Although, if I check it with user.user_permissions.all() I can see the permission object there and even call it to an instance like perm = user.user_permissions.all()[0]. Why has_perm() function return false is what I don't understand. Here is what I get in python manage.py shell: >>> user = customUser.objects.get(username="testuser1") >>> user.has_perm("can_see_soru_list") False >>> user.user_permissions.all() <QuerySet [<Permission: soruweb | soru | Can See The List>]> >>> user.user_permissions.all()[0] <Permission: soruweb | soru | Can See The List> >>> perm = user.user_permissions.all()[0] >>> perm.codename 'can_see_soru_list' >>> p = Permission.objects.get(codename="can_see_soru_list", content_type=c) >>> p == perm True Quick edit: I tried clearing cache with delattr(user,"_perm_cache") or something like that and I tried getting the user object from database again, at first within the same shell, second time opened new one and tried at it. … -
Page not found (404): No Post matches the given query.
I am trying to Create a 'Like' button on a post. a post belongs to a group. However, in my view function, Im getting a 404 error because it cant find the individual post, even though it is in the URL. here are the relevant files: (posts/urls.py): from . import views from django.urls import path app_name = 'posts' urlpatterns = [ path('create/<int:group_id>/', views.create, name='create'), path('edit/<int:group_id>/<int:post_id>/', views.edit, name='edit'), path('delete/<int:group_id>/<int:post_id>/', views.delete, name='delete'), path('like/<int:post_id>/', views.like, name='like'), ] (post/views.py): from django.shortcuts import render, get_object_or_404, redirect from groups.models import Group from .models import Post from .forms import PostForm from django.utils import timezone def like(request, post_id): post = get_object_or_404(Post, pk= post_id) if request.method == 'POST': post.likes_total += 1 return redirect('/groups/index' ) # post.save() else: return render(request, 'groups/detail.html', {'group':group}) (groups/detail html) {% for post in posts %} <h2>{{post.title}}</h2> <h5>{{post.body}}</h5> <p>{{post.pub_date_pretty}}</p> <p>{{post.author}}</p> <a href="{% url 'posts:edit' group.id post.id %}">Edit</a> <a href="{% url 'posts:delete' group.id post.id %}">Delete</a> <a href="javascript:{document.getElementById('like').submit()}"><button class="btn btn-primary"> Like ({{post.likes_total}})</button></a> {% endfor %} <form method ='POST' id= 'like' action="{% url 'posts:like' group.id %}" > {% csrf_token %} <input type="hidden" > </form> Just don't understand why its not able to grab the post. any help would be really appreciated! -
Error: Actions may not have an undefined "type" property when submitting react form
I was following a tutorial here on how to link react with redux to a django api. I have the django API set up and confirmed working. But trying to connect react to it I've run into an issue I cannot solve. Note: The code from the tutorial can be viewed on github. I think the issue in in the Login.js file, the code of which is below: const Login = (props) => { if (props.isAuthenticated) { return ( <Redirect to='/'/> ) } return ( <div className="login-page"> <FormHome {...props}/> </div> ) }; const mapStateToProps = (state) => ({ errors: authErrors(state), isAuthenticated: isAuthenticated(state) }) const mapDispatchToProps = (dispatch) => ({ onSubmit: (username, password) => { dispatch(login(username, password)) } }) export default connect(mapStateToProps, mapDispatchToProps)(Login); Every time I submit the form, I get an error Error: Actions may not have an undefined "type" property. Have you misspelled a constant? I've basically copy and pasted most of the code from that tutorial/repo. Yet whenever I try to submit the form, it gives me that error. -
Django: model object can save value even in not-defined field?
I have a Symbol model: class Symbol(models.Model): market = models.CharField( max_length=20, null=True, blank=True, ) and generate some Symbol model data. What I was surprised at: >>> s = Symbol.objects.first() >>> s.i_dont_know = 1 >>> s.save() It doesn't occur any error? Why does it not occur any error? -
Redis Celery Cassandra for real time statistics
I have 8 instances with 5000 Input threads each, each thread will receive 2Kb of data every 10 seconds. I have a separate DB instance to store the entire data from 8 instances after computations and processing. I am planning to store the data initially to the corresponding Redis instance before moving to the database since it will free my input threads very quickly. I will receive around 65Mb of data per 10 seconds from each instance, so around 550 MB data as a whole from 8 instances. I am planning to run Django celery workers at each instance which will migrate the data from the corresponding Redis to DB instance. I have some interdependent data between each Redis instance which I need to compute/accumulate before/after storing to the DB. Am I on the right track. Where should I compute the interdependent data, after pushing to DB or before pushing with some lock mechanisms to handle conflicts during concurrency? Please lead me on the right track. -
file being uploaded as binary strings in django using ajax
I have an issue with uploading a file with django using ajax (multipart/form-data) Here is my client code: $.ajax({ type: 'POST', url: parameters.uploadFile, data: fd, processData: false, contentType: false, xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; parameters.onProgress(percentComplete); } }, false); return xhr; }, error: parameters.error, }).done(parameters.done); where var file = $(this)[0].files[0]; var reader = new FileReader(); var fd = new FormData(); fd.append('data', file); fd.append('name', file.name); and <form enctype="multipart/form-data" method="post"> <button class="dndAlternative">Browse</button> <input type="file" name="upload" > </form> on the server side: if request.is_ajax(): image_path = request.FILES['data'].file.name ext = request.POST['name'].split('.')[-1] When I upload a file (any kind - jpg, png, csv) it used to get uploaded fine. But since a week or so, request.FILES and 'request.POST` are both being empty and all the file data is seen like this: As you see processData is set to false. could you please explain what's going wrong? -
Python - How to handle none type in filters with Mongoengine?
I have a basic program to filter a list. if request.data["isToday"] == True: today = datetime.date.today() else: today = None get_posts = Posts.objects( Q(title__contains = request.data["searchQuery"]) & Q(post_date = today )) if the date is passed it works fine. when None is passed it returns an empty list. Basically if today=None i want to show all the posts, if searchQuery is given then both the filters has to be applied. Am i missing some basic logic here? -
How can I select clicked content?
How can I select clicked content?Now I am making a system when I click a button, the data is shown in nav tag. I wrote codes in index.html <style> nav { width: 312px; height: 100%; transition: all 0.2s; transform: translate(312px); position: fixed; top: 0; right: 0; z-index: 1000; background-color: #FFF; } nav.open { transform: translate(0); } </style> </head> <script> $(function(){ $('.btn_menu').click(function(){ $('nav').toggleClass('open'); }); }) </script> <section id="center"> {% for d in data %} <button type="button" class="btn_menu"> {{ d.title }} </button> {% endfor %} </section> <nav> <h1>HomePage</h1> <h4>{{ d.ttitle }}</h4> <p>{{ d.dteail }}</p> </nav> in views.py class TopView(TemplateView): model = Data template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['data'] = Data.objects.all() return context When I click a button, all data is shown in nav tag of index.html.I want to show only clicked data in nav tag.I think I wrote codes so, but what is wrong in my codes?How should I fix this?