Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Different approaches in Django delete view
I'm working on Django website and I have problem in figuring out correct/good way to handle delete view. From what I found out there are two ways to approach it: 1 class ObjectDeleteView(DeleteView): model = Object def get_success_url(self): objectid = self.kwargs['object_id'] object = Object.objects.get(id = objectid) container = object.container containerid = container.id url = reverse('Containers:showContainerContent', args=[containerid]) return url def get_object(self): return get_object_or_404(Object, pk=self.kwargs['object_id']) 2 def objectDelete(request, object_id): object = Object.objects.get(id = object_id) container = object.container containerid = container.id url = reverse('Containers:showContainerContent', args=[containerid]) return HttpResponseRedirect(url) From what I can tell both are doing exactly the same thing - once object is deleted present user with page under Containers:showContainerContent. The big difference I am experiencing is error I am getting when running unit test for this (simple call of the website and check of response code). With option 1 I end up getting error django.template.exceptions.TemplateDoesNotExist: ContainerApp/object_confirm_delete.html Which I understand - I don't have this template, this is default template for DeleteView, hence error is correct. The thing is I don't want to have any extra page. Just redirect user and that's it. Also, I tested changing return url to return HttpResponseRedirect(url) in option 1, but result is the same. What should I … -
django/python sorting issue
I have a document that is built of sections, subsections, and clauses. Section 1 Subsections 1.1, 1.2, 1.3 Clauses 1.1.1, 1.1.2... 1.2.1, 1.2.2... They are models that have a "number" field to hold the identifier, but this field is a CharField because of the double dot syntax of some of the subsections and clauses, eg... Clause 1.2.1 If I want to sort the subsections, Django basic sorting algorithm will sort: 1.1 1.2 1.3 ... But it becomes problematic when I have more than 9 subsections or clauses in a group because sorting gives me: 1.1 1.10 1.11 1.2 1.3 ... Is there a way to have these ordered correctly in template, like: 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 I could convert them into floats and then sort them - but this wouldn't work for the clauses. -
@login_required page blank when log in
I have made a @login_required for a blog post so the user has to login to see it, but it seems to login but the page that comes up is blank. However when I look at the url it says I'm on the page. e.g "http://127.0.0.1:8000/accounts/login/?next=/payment/" Also when I back out of that page I'm logged in I've tried in the view if user: login(request, user) return HttpResponseRedirect(request.POST.get('next')) and added to the login.html Login.html {% block content %} <div style="max-width: 300px; margin: auto;"> <h2 style="text-align: center; font-size: 45px;">Login</h2> <form class="site-form" method="post"> {% csrf_token %} {{ form.as_p}} <input type="hidden" name="next" value="{{ next }}"> <button type="submit" style="background: #FC5C00; border: 0; color: #fff; font-size: 1.3em; display: block;margin: 0 auto;">Login</button> </form> </div> {% endblock content %} views.py def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): #login user user = form.get_user() login(request,user) if user: login(request, user) return HttpResponseRedirect(request.POST.get('next')) return redirect('/') else: form = AuthenticationForm() return render(request,'accounts/login.html',{'form':form}) All I need it to do is login to the page that has @login_required tag and show the page once it's logged in Thanks -
The view main.views.change_password didn't return an HttpResponse object. It returned None instead
I don't know why I ran into this problem. I am using django 2. I am creating a field to change password. Thanks in advance def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST,user=request.user) if form.is_valid(): form.save() return redirect('/profile') else: form = PasswordChangeForm(user=request.user) args={'form':form} return render(request,'main/change_password.html',args) -
Change the default md5 salting of django
I want to change the salting of md5 to be the same as the one I defined in my apapplication. That way I will be able to create users via the django administration page for those who have the same salting as those who will register in my application. -
Removing items from celery_beat doesn't remove them from database schedule
I'm using django-celery-beat in a django app (this stores the schedule in the database instead of a local file). I've configured my schedule via celery_beat that Celery is initialized with via app.config_from_object(...) I recently renamed/removed a few tasks and restarted the app. The new tasks showed up, but the tasks removed from the config didn't get removed from the database. Is this expected workflow -- requiring manual removal of tasks from the database? Is there a workaround to automatically reconcile the schedule at Django startup? I considered trying a PeriodicTask.objects.all().delete() in celery/__init__.py but that loses "last run" information for existing tasks. Although I could .exclude(name__in=beat_schedule.keys()).delete() instead. I've also seen problems with trying to execute Django queries inside of initialization areas. -
Multiple Database Routing Middleware
I have a problem correctly setting my middleware and routers to support multiple databases, one for each language (I decided to keep them separate). I tried to use this solution, but for now I didn't get much use of it. In my settings.py databases and middleware are defined as follows: DATABASES = { 'default': {}, 'ru': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db_ru.sqlite3', }, 'en': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db_en.sqlite3', } } DATABASE_ROUTERS = ['me.middleware.database_routing.DatabaseRouter'] MIDDLEWARE = [ 'me.middleware.database_routing.RouterMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] database_routing.py used in 'me.middleware.database_routing' fully corresponds to this middleware. I get an error when starting the server: RouterMiddleware() takes no arguments. I believe there's some shortcoming concerning the middleware code. Also I cannot migrate to my databases, I get ValueError: Cannot assign "<ContentType: ContentType object (1)>": the current database router prevents this relation. Maybe, there is some other solution? -
Model meta option: app_label not being included when using db_table
I am using the Meta class option, db_table on my model class in order to format the table names within my Django app accounts/models.py. When I do this and run migrations (makemigrations then migrate), it doesn't carry along the app label (the app name is in my INSTALLED_APPS list). I want to get <app_label>_<db_table> formatted tables. If I attempt to add the app_label option explicitly to the Meta class along with db_table it still isn't recognized as part of the migration plan and therefore never makes it to the database as <app_label>_<db_table>. Reference docs and Django version 2.2: https://docs.djangoproject.com/en/2.2/ref/models/options/ project/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', ] accounts/models.py class PasswordAttempt(models.Model): attempt_id = models.IntegerField(primary_key=True) security_id = models.ForeignKey(Security, on_delete=models.CASCADE) attempt_count = models.IntegerField(default=0) class Meta: app_label = 'accounts' # Shouldn't be necessary, but still doesn't work db_table = 'password_attempt' accounts/migrations/001_initial.py class Migration(migrations.Migration): initial = True dependencies = [ ] ...# Other models migrations.CreateModel( name='PasswordAttempt', fields=[ ('attempt_id', models.IntegerField(primary_key=True, serialize=False)), ('attempt_count', models.IntegerField(default=0)), ('security_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='accounts.Security')), ], options={ 'db_table': 'password_attempt', }, ), ] Everything seems fine and dandy until I drop in db_table in the Meta class. Once that happens I am losing my app label for that table name. I am … -
ModuleNotFoundError: No module named while starting gunicorn
I'm trying to deploy django project with gunicorn. I made the gunicorn.service file in sudo nano /etc/systemd/system/gunicorn.service. My gunicorn.service file looks like: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=hypernet Group=www-data WorkingDirectory=/home/hypernet/hypernet/hypernet/hypernet-backend ExecStart=/home/hypernet/virtualenvs/venv/bin/gunicorn \ --access-logfile - \ --workers 33 \ --bind unix:/run/gunicorn.sock \ backend.wsgi:application [Install] WantedBy=multi-user.target Whenever i try to start the service using: sudo systemctl restart gunicorn it gives me gunicorn.socket not found error and when i do: sudo journalctl -u gunicorn. It gives me this: File "/home/hypernet/virtualenvs/venv/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker May 08 16:39:43 Hypernet-Backend gunicorn[17148]: worker.init_process() May 08 16:39:43 Hypernet-Backend gunicorn[17148]: File "/home/hypernet/virtualenvs/venv/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_proce May 08 16:39:43 Hypernet-Backend gunicorn[17148]: self.load_wsgi() May 08 16:39:43 Hypernet-Backend gunicorn[17148]: File "/home/hypernet/virtualenvs/venv/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi May 08 16:39:43 Hypernet-Backend gunicorn[17148]: self.wsgi = self.app.wsgi() May 08 16:39:43 Hypernet-Backend gunicorn[17148]: File "/home/hypernet/virtualenvs/venv/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi May 08 16:39:43 Hypernet-Backend gunicorn[17148]: self.callable = self.load() May 08 16:39:43 Hypernet-Backend gunicorn[17148]: File "/home/hypernet/virtualenvs/venv/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load May 08 16:39:43 Hypernet-Backend gunicorn[17148]: return self.load_wsgiapp() May 08 16:39:43 Hypernet-Backend gunicorn[17148]: File "/home/hypernet/virtualenvs/venv/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp May 08 16:39:43 Hypernet-Backend gunicorn[17148]: return util.import_app(self.app_uri) May 08 16:39:43 Hypernet-Backend gunicorn[17148]: File "/home/hypernet/virtualenvs/venv/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app May 08 16:39:43 Hypernet-Backend gunicorn[17148]: __import__(module) May 08 16:39:43 Hypernet-Backend … -
How to get the sum of a field in Django
How would I render the total for values of a particular field? As you can see I am using reverse relations here because I have a foreign key (I'm not sure if that makes a difference). For instance what would I do if I wanted the total of the values in the 'ab' field. I know I have to use aggregate or annotate method. What would that look like in my particular situation? models.py class Batting(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) playerid = models.ForeignKey('PlayerLkup', models.DO_NOTHING, db_column='playerID', blank=True, null=True) g = models.IntegerField(db_column='G', blank=True, null=True ab = models.IntegerField(db_column='AB', blank=True, null=True) year = models.IntegerField(db_column='Year', blank=True, null=True) complete_name = models.CharField(max_length=50, blank=True, null=True) class PlayerLkup(models.Model): playerid = models.CharField(db_column='playerID', primary_key=True, max_length=255) birthday = models.IntegerField(db_column='birthDay', blank=True, null=True) namefirst = models.CharField(db_column='nameFirst', max_length=255, blank=True, null=True) namelast = models.CharField(db_column='nameLast', max_length=255, blank=True, null=True) views.py from django.shortcuts import render from .models import PlayerLkup def player_info(request, playerid): playerdata = PlayerLkup.objects.get(playerid=playerid) battingstats = playerdata.batting_set.all() return render(request, 'careerstats/playerpage.html', {'playerdata': playerdata, 'battingstats': battingstats}) -
Take control on select_related
I need to prefetch object for selected related parent object. For example I have 3 models: class Event(..): create_by = ForeignKey(User, related_name='events_set') class User(..): ... class ProfileImage(..): user = ForeignKey(User, related_name='profile_images_set') image = ImageField(..) So i need to get detail info about Event, I have got a guery like this: Event.objects.all().prefetch_related('..').select_related('created-by') The problem is that I also need to get the last image of event creator. I tried Prefetch but it only works to control prefetch_related. -
How to use get_context_data() in Django?
I'm trying to return the readtime of the body in a blog post. But I'm finding it difficult to do so with get_context_data() This is the view function to create a post: class BlogCreateView(LoginRequiredMixin, CreateView): model = Post template_name = 'blog/creator/new_post.html' fields = ['title', 'category', 'slug', 'body'] login_url = 'login' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Now, what I want to do is return the readtime for 'body' something like this: body = request.POST.get('body') post_read_time = readtime.of_html(body) post = Post(read_time=post_read_time) post.save() The problem is how to do this in my BlogCreateView class. I made some research and came across the get_context_data() function. So I tried this: class BlogCreateView(LoginRequiredMixin, CreateView): model = Post template_name = 'blog/creator/new_post.html' fields = ['title', 'category', 'slug', 'body'] login_url = 'login' post_read_time = '' def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) context_data['body'] = readtime.of_html('body') c = Post.objects.filter(read_time=context_data) return context_data def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) This is how I render the data in my template: <span>{{ post.read_time }}</span> I expect the output to return the read time but I've only made things worse. I'm getting this error instead: TypeError at /blog/post/new-post66/ {'object': <Post: We Should All Be Farmers>, 'post': <Post: We Should All Be … -
getElementsByClassName onclick and return data
I have many these links in my template <a href="javascript:void(0);" class="add_to_cart" data-slug="{{ product.slug }}">Add</a> And need click to the link and get certain data-slug. I try use JS and get all links so. var add_to_cart = document.getElementsByClassName('add_to_cart'); After I try for for(var i = 0; i < add_to_cart.length; i++) { product_slug = add_to_cart[i].getAttribute('data-slug') add_to_cart[i].onclick = function() { console.log(product_slug) } } And after click always console.log have last data-slug latest link in my template. How to fix it and get the data-slug of the item I clicked on. Help me, please. -
Handling many-to-many relationship from existing database using Django ORM
I'm starting to work with Django, already done some models, but always done that with 'code-first' approach, so Django handled the table creations etc. Right now I'm integrating an already existing database with ORM and I encountered some problems. Database has a lot of many-to-many relationships so there are quite a few tables linking two other tables. I ran inspectdb command to let Django prepare some models for me. I revised them, it did rather good job guessing the fields and relations, but the thing is, I think I don't need those link tables in my models, because Django handles many-to-many relationships with ManyToManyField fields, but I want Django to use that link tables under the hood. So my question is: Should I delete the models for link tables and add ManyToManyFields to corresponding models, or should I somehow use this models? I don't want to somehow mess-up database structure, it's quite heavy populated. I'm using Postgres 9.5, Django 2.2. -
Inline formset causing error: 'NoneType' object has no attribute 'is_ajax'
I am using bootstrap-modal-forms to show a user a formset with some inline forms. It is possible for the user to save the form if data is only entered into the original form, but if the inline formset has data then I get the following error: 'NoneType' object has no attribute 'is_ajax' The inline formset was working correctly before I tried to implement them in the modal form. The problem seems to arise only when the inline formset (projectimages) is saved it is a NoneType. My views.py class ProjectCreate(BSModalCreateView): form_class = ProjectForm template_name = 'project_form.html' success_message = 'Success: %(project_name)s was created.' def get_success_url(self): return reverse_lazy('project-detail', kwargs={'project': self.object.slug}) def get_context_data(self, **kwargs): data = super(ProjectCreate, self).get_context_data(**kwargs) if self.request.POST: data['projectimages'] = ProjectFormSet(self.request.POST, self.request.FILES,) else: data['projectimages'] = ProjectFormSet() return data def form_valid(self, form): form.instance.date_created = timezone.now() context = self.get_context_data() projectimages = context['projectimages'] with transaction.atomic(): self.object = form.save() if projectimages.is_valid(): projectimages.instance = self.object projectimages.save() return super(ProjectCreate, self).form_valid(form) My forms.py class ProjectForm(BSModalForm): class Meta: model = Project exclude = ['date_created', 'slug'] ProjectFormSet = inlineformset_factory( Project, ProjectImage, can_delete=True, form=ProjectForm, extra=1, ) My models.py class Project(models.Model): project_name = models.CharField(max_length=100) date_created = models.DateTimeField('Created on') slug = models.SlugField(unique=True) def __str__(self): return self.project_name def save(self, *args, **kwargs): self.slug = slugify(str(self)) super(Project, … -
Key error when appending model with the exact same fields?
So I have a model that represents an order list. I query this model every two days and filter the result using its datefield. I would like to take this queryset result and append it to another table with the exact same fields. How ever when I do I get a keyword argument error saying "'model' is an invalid keyword argument for this function" time_threshold = datetime.now() - timedelta(days = 3) orderlist = BoarsHeadList.objects.filter(order_date__gt = time_threshold) for order in orderlist: orderlist_dict = orderlist.__dict__ BoarsHeadOrderList.objects.create.(**orderlist_dict) models.py class BoarsHeadList(models.Model): Turkey = models.IntegerField(null = True) Ham = models.IntegerField(null = True) Roast_Beef = models.IntegerField(null= True) Rotisserie_Chicken = models.IntegerField(null= True) Bacon = models.IntegerField(null = True) store = models.ForeignKey(settings.AUTH_USER_MODEL , on_delete=models.CASCADE, null = True,) order_date = models.DateTimeField(auto_now_add=True, blank=True, null = True,) class meta: managed = True db_table = 'BoarsHead' class BoarsHeadOrderList(models.Model): Turkey = models.IntegerField(null = True) Ham = models.IntegerField(null = True) Roast_Beef = models.IntegerField(null= True) Rotisserie_Chicken = models.IntegerField(null= True) Bacon = models.IntegerField(null = True) store = models.ForeignKey(settings.AUTH_USER_MODEL , on_delete=models.CASCADE, null = True,) order_date = models.DateTimeField(auto_now_add=True, blank=True, null = True,) class meta: managed = True db_table = 'BoarsHeadOrder' -
How to get list of models that are executes while loading list view in admin
I am writing custom list view in django admin (map showing places of addresses) that will be available like this: And i need to get a list of models that are also used to generate list in the bottom of screenshot. I was looking for a right method in doc of ModelAdmin, but I didn't find anything interesting class CompanyAdmin(ImportExportModelAdmin): list_display = ['name', 'get_first_image', 'get_city', 'get_street] search_fields = ['name', 'categories__name', 'trades__name', 'tax_id', 'www', 'email'] list_filter = [('categories', CompanyCategoryTreeFilter), UserInStaffFilter] filter_vertical = ['categories', 'trades'] inlines = [AttributeValueInline, CompanyPersonInline, NoteReadOnlyInline, NoteInline, NoteHiddenReadOnlyInline] resource_class = CompanyResource def save_model(self, request, obj, form, change): if not obj.person_responsible_fk: obj.person_responsible_fk = request.user super().save_model(request, obj, form, change) class Media: js = ( 'js/contacts.js', ) change_list_template = 'admin/contacts/company/change_list.html' admin.site.register(Company, CompanyAdmin) I expect to get actual list of Companies that are used to load page with list, while it is loading. -
How to use GET and queryset in classed based views?
i have two models with random farmers and animals (names / weight ) and i want to use the GET method, in my template, to apply a filter in my view on my models. For instance: show me all data with the name "xyz" this was my approach: models.py class Farmer(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) city = models.CharField(max_length=40) <...> class Animal(models.Model): name = models.CharField(max_length=40) weight = models.DecimalField(max_digits=5, decimal_places=2) species = models.ForeignKey('Species', on_delete=models.CASCADE) farmer = models.ForeignKey('Farmer', related_name='farmername', on_delete=models.CASCADE) <...> so this is my template. when i submit a value it will show up in my browser adress template.html <...> <form action="" method="GET"> name: <input type="text" name="q"><br> <input type="submit" value="Search"> </form> <...> this was my approach to fit in the GET method and Q into my view views.py from django.views.generic import TemplateView from django.views.generic import View from django.shortcuts import render from django.db.models import Q <...> class HomeView(TemplateView): template_name = 'farmapi/search.html' http_method_names = ['get'] def get(self, request): query = request.GET.get("q") def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['farmers'] = Farmer.objects.filter(Q(first_name__icontains=query)|Q(last_name__icontains=query)) context['animals'] = Animal.objects.filter(Q(name__icontains=query)) return context This is the Error Message i get ValueError at /data/search/ The view farmapi.views.HomeView didn't return an HttpResponse object. It returned None instead. so as far as … -
Column field is not recognized/not defined
I have this model and here is my query - the error shows "submission_date" is not defined. However the "overall_rating" - which is another column, is working fine. I do not understand the reason. class businessdata(models.Model): submission_date = models.DateTimeField(null = False) product_id = models.CharField(max_length = 50) product_name = models.CharField(max_length = 150) model_number = models.CharField(max_length = 25) upc = models.CharField(max_length = 25) overall_rating = models.IntegerField(null = False) So this query works... categoryResult = businessdata.objects.filter(overall_rating = rating, product_name='XYZ') But this does not work... categoryResult = businessdata.objects.filter(submission_date >= fromdate, submission_date <= todate, overall_rating = 5).values(submission_date.strftime('%Y-%m-%d')).annotate(count = Count(submission_date.strftime('%Y-%m-%d'))) It says... name 'sumission_date' not defined -
Value of Select Option in Django's Views.py
I am using select tag in template along with a link having 'submit' type inside a form tag. When I select an option from the dropdown and click on the button, it goes to the next page but I am unable to get the value of the options selected. Its showing AttributeError 'Manager' object has no attribute 'month'. Here is my code: <form method="POST" action="{% url 'results' %}"> {% csrf_token %} <select name="mahina" id="month"> <option value="all">All</option> <option value="jan">January</option> <option value="feb">February</option> </select> <a href="{% url 'results' %}" type="submit">Search</a> </form> Here is my views.py from django.shortcuts import render from .models import Results def allresults(request): results = Results.objects if request.method == "GET": month = results.month year = results.year return render(request, 'results/allresults.html', {'results': results} -
Django template rendering: using tags vs using views
In Django, when rendering data in templates that's available through the request, we have 2 options: Obtain the data in the view, and pass it to the template engine through the context: def my_view(request): username = None if request.user.is_authenticated: username = request.user.username context = {'username': username} return render(request=request, template_name='test.html', context=context) With a template that has: <p>Hello, {{ username }}<p> Directly obtain the value from the request in the template: def my_view(request): if request.user.is_authenticated: return render(request=request, template_name='test.html', context={}) With a template that has: <p>hello, {{ request.user.username }}</p> Is there a difference between both in terms of 'correctness'? Is request in the second template just to be seen as a context for the request object or are there other implications? -
Too much information in Django's request.META object
I've recently been inspecting request.META for a particular view, and it looks to me that all of the environmental variables such as DJANGO_SECRET_KEY, DJANGO_DATABASE_NAME and DJANGO_SUPERUSER_PASSWORD...etc etc are contained within this object as extra to the default Django request.META data. How would I go about remove said variables from the META? Is this in any way accessible from the client side? I'm guessing I could use some middleware to strip these out, but has anyone else seen this behaviour? Is this normal/safe? N.B. I specify the above as ENVIRONMENT variables inside my docker-compose.yml file for the django web service. -
Unable to broadcast message using celery
I'm trying to use celery's build in support for broadcast routing using Broadcast and using rabbitmq as the broker. I have been able to successfully publish and receive message using the default direct exchange, now I'm trying to use the fanout exchange that rabbitmq provides. For this it seems celery has a built-in support using Broadcast class. My celery conf looks likes this: app.conf.task_queues = (Broadcast('broadcast_tasks'),) app.conf.task_routes = { 'tasks.tasks.sync_channels': { 'queue': 'broadcast_tasks', 'exchange': 'broadcast_tasks' } } And following is how I have defined my task in app/tasks/tasks.py @app.task(name='sync_channels') def sync_channels(data): logger.debug('Received here') pass When I open the rabbitmq management UI, i can see that a fanout exchange is created with name "broadcast_tasks" , but when I try to push a message to sync_channels task, it automatically creats a default (direct) exchange and a default queue binded to the default exchange and all my future messages to sync_channels task are pushed to the default exchange. It seems somehow I am not able to configure the Broadcast feature that celery provides. Below are some screenshots that may help you understanding the problem: I also need some understanding on how celery's Broadcast works. Also instead of using the Broadcast feature I tried … -
Checking my MongoDB and getting an unusual dbs
So today I was in my MongoDB and I type in show dbs. Other than my usual dbs there is an additional hacked_by_unistellar. Anyone might know what I can do here? It sounds like I have been hacked unless this is some terrible easter egg I have come across. Please advise. Thank you. -
How to Mock django chained queries using python unittest
func_to_test.py from models import MyModel def myFunc(): #Query 1 queryset_exists = MyModel.objects.filter(id=0).exists()) #Query 2 queryset_exists = MyModel.objects.filter(id=0) return True test.py from models from func_to_test import myFunc from unittest.mock import MagicMock, patch, Mock class TestMyFunction(unittest.TestCase): @patch('models.MyModel.objects') def test_myFunc(self, mymodel_alias): # Creating mock object for filter query response MyModel_Obj = MagicMock(spec=MyModel) MyModel_Obj.id=1 mymodel_alias.filter.return_value = [MyModel_Obj] mymodel_alias.filter.return_value.exists.return_value = True self.assertEqual(myFunc(), True) --------------------Error1----------------------------- mymodel_alias.filter.return_value.exists.return_value = True AttributeError: 'list' object has no attribute 'exists' Note If we change below as mymodel_alias.filter.return_value = [MyModel_Obj] ====to==== mymodel_alias.filter.return_value = MyModel_Obj --------------------Error2----------------------------- raise AttributeError("Mock object has no attribute %r" % name) AttributeError: Mock object has no attribute 'exists'