Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to indent Django templates properly
I work in SublimeText 3. When writing Django templates I have a mixture of html and functions. I like to indent my code so that block, if and other such statements are indented. For example: Manual formatting {% extends "accounts/base.html" %} {% block content %} <h1>Password changed</h1> <p>Your password was changed.</p> {% endblock %} However, when I run any autoformatter HTML-CSS-JS-Prettify it ignores these brackets and treats them as text: After formatting {% extends "accounts/base.html" %} {% block content %} <h1>Password changed</h1> <p>Your password was changed.</p> {% endblock %} Although plugins like Djaneiro give great tag highlighting, I haven't been able to find a way to get SublimeText to treat these as tags. Has anyone had any luck? -
i can't reach the new url after defined the view function and write the url and adding some data
strong texti was creating a new URL route after write the view function and creating the template and adding some data to use it and i still can't reach my URL views.py def new_topic(request, pk): board = get_object_or_404(Board, pk=pk)7 return render(request, 'new_topic.html', {'board': board}) urls.py urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^boards/(?P<pk>\d+)/$', views.board_topics, name='board_topics'), url(r'^boards/(?P<pk>\d+)/$', views.new_topic, name='new_topic'), url(r'^admin/', admin.site.urls), ] new_topic.html {% extends 'base.html' %} {% block title %}Start a New Topic{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li> <li class="breadcrumb-item active">New topic</li> {% endblock %} {% block content %} {% endblock %} ''' i expected when i write in the url that : 127.0.0.1:888/boards/3/new/ i see what i wrote in new_topic template but it show me this error: Page not found (404) Request Method: GET Request URL: `http`://127.0.0.1:8000/boards/4/new Using the `URLconf` defined in `myproject`.`urls`, `Django` tried these URL patterns, in this order: ^$ [name='home'] ^boards/(?P<pk>\d+)/$ [name='board_topics'] ^boards/(?P<pk>\d+)/$ [name='new_topic'] ^admin/ The current path, boards/4/new, didn't match any of these. -
Django User Rating System
I have an e-learning project with courses on different topics and I want to implement a rating system for the users. I started with a ManyToManyField to the user model. The rating of a user increases when he gets rated by other users. But I want to link the rating to the courses, so that it increases on every completed course. Im thinking of a button at the end of every course that says "completed" and that will increase the rating of the user when he gets there and clicks on it. But if I then want the courses to have different levels of difficulty, I would need to add different ratings to the buttons, which does not make sense. So the rating must be connected to the level of the course in a manner that they both add up. Thank you for any suggestions -
How to interrupt input reading in Django view when clicking a link
I'm working on a django based lock/access system with an RFID reader. The problem is that if while waiting for the reader to detect a tag, I click a link on the template already displayed, the server keeps waiting for the card in the background. It follows that if then I come back to the access page and reload the reading function, it puts that request below the one before. The problem also occur if I use basic input() function instead of reader.read_id() function from mfrc522 library import mfrc522 # ... other imports # main access view def access_result(request): reader = mfrc522.SimpleMFRC522() # CRITICAL PART card_id = reader.read_id() try: if RFIDCard.objects.get(card_id=card_id): card = RFIDCard.objects.get(card_id=card_id) if card.remaining_accesses > 0 and card.expiration_date >= datetime.date.today(): card.remaining_accesses -= 1 # ... some other lines of code (not relevant) except RFIDCard.DoesNotExist: message = 'Card not registered' description = 'It seems that we haven\'t registered this card. ' \ 'Please ask for help at the reception' return render(request, 'rfid/access_result.html', { 'message': message, 'description': description }) I'd like to interrupt the reading if the user goes elsewhere clicking on a link of the page displayed before (and during) the reading. Is there a simple way I could … -
Highcharts - Pass a dictionary as data for a timeline series
So, I've been using Highcharts for quite a while, and I was trying to make a Timeline Chart. I've seen some example code on the internet and noted that the data attribute is basically a dictionary. So I made a dictionary from some data, using python/pandas etc, and it looks like this: [{'name': '2017-12-07 - Chat', 'label': 'some text', 'description': 'some text'}, {'name': '2017-12-15 - Whatsapp', 'label': 'some text', 'description': 'some text'}] I pass this in a context in django and then call it in the html template, together with the js code for the chart: <script type="text/javascript"> var _dict = {{dict|safe}}; </script> <script src="/static/vendors/highcharts/cs_timeline.js"></script> And then in the javascript file, I use the dict as the data attribute, using some code I've got from the official Highcharts example: Highcharts.chart('hist', { chart: { type: 'timeline' }, xAxis: { visible: false }, yAxis: { visible: false }, title: { text: 'Timeline of Space Exploration' }, subtitle: { text: 'Info source: <a href="https://en.wikipedia.org/wiki/Timeline_of_space_exploration">www.wikipedia.org</a>' }, series: [{ dataLabels: { connectorColor: 'silver', connectorWidth: 2 }, data: _dict }] }); This works fine for every chart I've done, but isn't working for this one. I'm having trouble identifying where the problem is; the format, the … -
Webpack use folder name instead of Url for public path
I am using react and django. I am trying to use code-splitting in my components, so in my webpack.config.js I have this output: { path: path.join(__dirname, "frontend/static/frontend"), filename: "[name].bundle.js", chunkFilename: "[name].chunk.js", publicPath: "/frontend/static/frontend/" }, but when it requests it in the browser it goes to /en/account/quiz/drug-abuse/frontend/static/frontend/2.chunk.js instead of static/frontend/2.chunk.js my javascript files are located in my static folder for django but react routing starts at /en/, I am guessing that is why the confusion is happening. Is there anyway to make the webpack file look for http://domainblahblah.com/static/frontend/2,chunk.js -
Django race condition in simultaneous ModelForm submission
My model has a field working_hour which is IntegerField, I am using ModelForm and django-crispy-forms.Assume tow different people has rendered form with working_hour value 20 and both of them want to increase working_hour by 10 and they updates the working_hour form field from 20 to 30.When they both submit the form, updated working_hour becomes 30 in database, but it should be 40. models.py class OverallHour(models.Model): working_hour = models.PositiveIntegerField() forms.py class OverallHourForm(ModelForm): class Meta: model = OverallHour def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Submit('submit', 'UPDATE')) overall_hour_form.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="row justify-content-center"> <div class="col-md-8"> <div class="card bg-light"> <div class="card-body"> {% crispy form %} </div> </div> </div> </div> {% endblock content %} Can you please advice me how to fix this problem? -
I Wagtail how to disable certain admin menu items for the certain users?
For the group of users I want to disable some menu items. I thought I will use the following: from wagtail.contrib.modeladmin.options import ModelAdmin as WModelAdmin class WPartnerAdmin(WModelAdmin): ... def get_menu_item(self, order=None): menu_item = super().get_menu_item(order=order) # if (user_discrimination_logic): # menu_item.is_shown = lambda *a: False return menu_item But it seems that I don’t have access to the request object in the ModelAdmin, therefore don’t know how to extract the user data. Is there a way? -
Django __init__() takes at least 2 arguments (1 given)
Im getting this error when I try to login to my django app. I dont know what is happening, it worked 30 minutes ago and I havent touched anything since then. views.py def login_page(request): form = LoginForm(request.POST or None) context = { "form": form } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request,username=username,password=password) if user is not None: login(request,user) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path,request.get_host()): return redirect(redirect_path) else: request.notifications.add('Hello world.') messages.add_message(request, messages.INFO, 'Hello world.') return redirect("/") else: print("Error") return render(request, 'accounts/login.html',context) forms.py class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control","placeholder":"Your Username"})) password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"form-control","placeholder":"Your Password"})) Traceback File "/usr/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/django_project/accounts/views.py" in login_page 42. user = authenticate(request, username=username,password=password) File "/usr/local/lib/python2.7/dist-packages/lockout/decorators.py" in wrapper 43. result = function(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/contrib/auth/init.py" in authenticate 68. for backend, backend_path in _get_backends(return_tuples=True): File "/usr/lib/python2.7/dist-packages/django/contrib/auth/init.py" in _get_backends 29. backend = load_backend(backend_path) File "/usr/lib/python2.7/dist-packages/django/contrib/auth/init.py" in load_backend 23. return import_string(path)() Exception Type: TypeError at /login/ Exception Value: init() takes at least 2 … -
Django pass parameter when using urls include
In urls.py I dynamically create objects and want to create urls for each of them. I can iterate over them and include another urls file into my main urls.py like this: urlpatterns = [path(object.url, include('bar.urls')) for object in objects] However, in my application I want to pass the variable object to bar.urls that can be passed to the views afterward. I wonder if I can do something like this: urlpatterns = [path('foo', include('bar.urls', my_var=object)) for object in objects] and in bar: # bar.urls (got my_var somehow) urlpatterns = [path('foo', views.foo, object=my_var)] # bar.views def foo(request, object) # use object -
Django store foreign then submit form
How to use foreign key to create a new value and use that to submit the form before failing the if form.is_valid(). Issue is the foreign key is doesn't exit, want use to input the data and which like to use that as foreign key value and submit the form. MODEL: class AirportCode(models.Model): name = models.CharField(max_length=4, default=None, blank=True, unique=True) class AddData(models.Model): airportcode = models.ForeignKey(AirportCode, on_delete=models.SET_NULL, null=True) FORM: class Airportcode_Form(forms.ModelForm): class Meta: model = AirportCode fields = ('name',) class AddData_Form(forms.ModelForm): class Meta: model = Pull fields = ('airportcode',) def __init__(self, *args, **kwargs): super(AddData_Form, self).__init__(*args, **kwargs) self.fields['airportcode'].queryset = CODE.objects.none() if 'airportcode' in self.data: c = self.data.get('airportcode') self.fields['code_pull'].queryset = CODE.objects.filter(name=c) VIEW: def save(request): if request.method == 'POST': if form.is_valid(): add = form.save(commit=False) add.airportcode = form.cleaned_data['airportcode'] add.save() return redirect(save) else: messages.error(request, form.errors) context = {'form': form } return render(request, template_name, context) Getting error when submitting form, as the field Airportcode is not selected. Thanks for the help in advance -
Django. REST Framework. Rename SerializerMethodField()
In the django rest framework, I have a serializer, it takes fields from the model, combines it under one tag, and displays it in xml. Everything is simple. I understand how it works. But what I don’t understand is how to rename the parent tag. I will show: #serializers.py class kvSerializerLivingSpace(serializers.ModelSerializer): unit = serializers.CharField(default='qm') class Meta: model = kv fields = ['unit', 'value'] class kvSerializer(serializers.ModelSerializer): living_space = serializers.SerializerMethodField() class Meta: model = kv fields = ['living_space'] def get_living_space(self, obj): return kvSerializerLivingSpace(obj).data I need living_space through a hyphen. To make it look like living-space I know that i can rename tags as follows: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields.update({ 'living-space': kvSerializerLivingSpace() }) But this does not work for serializers.SerializerMethodField() Thank! -
Why is GET and POST request converting to OPTIONS request for cross-origin request for django rest framework and reactjs frontend?
I was looking to run my django and reactjs web application on mobile by connecting it to mac via hotspot, and changing the host to the ipaddress of the mobile. Thus, I changed my localhost to 192.168.43.19 in /etc/hosts/, and thus, my code is easily shared between mobile and mac, and I am able to run the localhost app on my mobile which is connected to mac via hotspot. The backend is created in django rest framework. The problem is that all the get and post calls to the api created in the backend in django is being converted to options calls, and thus there are no returns, and the code is not working properly. While searching online, it said that the issue is because by default Access-cross-origin-policy is not allowed. To try handling the issue, I added the frontend url in CORS_ORIGIN_WHITELIST in the settings file of the django app, but it didnt work. It will be really helpful, if someone could recommend me the correct way to handle this? -
Django request nonexistent permissions for User creation
In my Django project I have a custom User model named Employee, which is configured in the settings as follows: AUTH_USER_MODEL = 'employees.Employee' When I try to add a new Employee via the admin interface, everything works as expected if I am logged in as a superuser. However, if I do not have the superuser roll, Django responds: Your user does not have the "Change user" permission. In order to add users, Django requires that your user account have both the "Add user" and "Change user" permissions set. Both "Change employee" and "Add employee" permissions have been granted to the user; "Change user" and "Change user" permissions do not exist, since the original User model does not exist (is replaced with Employee) How to solve this issue? -
When running the server the image,tittle and price didn't display on the webpage. I've just started learning programming 5 months ago. Help me please
from django.shortcuts import render def index(request): products = [ {'title': 'Fuct "playboy" pocket tee', 'price': 30, 'image': 'https://instagram.fmkz1-1.fna.fbcdn.net/vp/a6d3c0ce1196c2613b202f5c6917b2a7/5DF11D66/t51.2885-15/e35/s1080x1080/69037434_409676526336836_2753352954002356161_n.jpg?_nc_ht=instagram.fmkz1-1.fna.fbcdn.net'}, {'title': 'Levis big E 507XX type 2 selvedge jacket', 'price': 90, 'image': 'https://instagram.fmkz1-1.fna.fbcdn.net/vp/d3f3c4e7e0e44158e48ce3ac0cc92fd5/5E0D553F/t51.2885-15/e35/s1080x1080/61871643_497887490776394_4216653965002551874_n.jpg?_nc_ht=instagram.fmkz1-1.fna.fbcdn.net'}, {'title': 'vintage nike big swoosh', 'price': 40, 'image': 'https://instagram.fmkz1-1.fna.fbcdn.net/vp/f396f9a17e49ae57d862620cefae2bd6/5DF7D52A/t51.2885-15/e35/s1080x1080/67370121_563369154199572_8476318391380511268_n.jpg?_nc_ht=instagram.fmkz1-1.fna.fbcdn.net'}, ] context = { 'products': products, } return render(request, 'webapp/index.html', context) -
Creating a simple multiplayer game, currently working on mitigating latency, does this sound right?
I'm essentially making this game multiplayer: http://jsfiddle.net/PxpVr/16/embedded/result/ You can check it out at apollius.com To mitigate latency, I'm sending out the game state to both clients every time a player turns. Should I be updating the state periodically instead? I've gotten a lot of advice that is all over the place. Please help -- thanks in advance apollius -
Factory_boy - implicitely generate random values based on field type
I'm new to Factory_boy. I need it to generate data to my Django project so I'm using DjangoModelFactory. class UserFactory(DjangoModelFactory): class Meta: model = 'user.User' User.objects.last().__dict__ {'_state': <django.db.models.base.ModelState at 0x7f788c3aed30>, 'id': 67, 'password': '', 'last_login': None, 'is_superuser': False, 'username': '', 'first_name': '', 'last_name': '', 'email': '', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 8, 30, 18, 50, 9, 104838, tzinfo=<UTC>), 'is_office_user': False} Is there a way it tries to generate random data based on field type? I have a huge models and I don't want to explicitely define each field. -
What pythonic solution to use when creating a task to run in the background?
I am using Django (1.11) for an API. The endpoint that I am working on creates an excel document from DB data, but will often take over a minute to process (the hosting site will timeout the request if it takes over 1 minute). I want to have a request that starts a background/subprocess/async task/etc... that does the processing in the background and saves to a shared storage location, while the response hands back a "ticket number" for the front-end to use to check back periodically to see if the task is done or not. (thereby not triggering the one minute timeout) The problem I am having is that I'm not sure what to use for the background process part. I have used threading and subprocessing in the past, and more recently I have heard good things about asyncio. I don't care about what the background process returns, I only care that it completes its task (which can be checked through searching the shared storage). I also don't want the background processes to accumulate, so I need something that will self-close as soon as it's done with processing the data. What is the best way to tackle this issue? Thanks! -
ModuleNotFoundError: No module named 'tzwhere'
In my windows 10 os When i run my python project i got error ModuleNotFoundError: No module named 'tzwhere' I've tried to install tzwhere pip install tzwhere ERROR: Command errored out with exit status 1: command: 'c:\users\raj\envs\py1\scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\temp\pip-install-3lryfis_\shapely\setup.py'"'"'; file='"'"'C:\temp\pip-install-3lryfis_\shapely\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info cwd: C:\temp\pip-install-3lryfis_\shapely\ Complete output (9 lines): Traceback (most recent call last): File "", line 1, in File "C:\temp\pip-install-3lryfis_\shapely\setup.py", line 80, in from shapely._buildcfg import geos_version_string, geos_version, \ File "C:\temp\pip-install-3lryfis_\shapely\shapely_buildcfg.py", line 200, in lgeos = CDLL("geos_c.dll") File "c:\users\raj\appdata\local\programs\python\python37\Lib\ctypes__init__.py", line 356, in init self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module could not be found ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. from tzwhere import tzwhere tzwhere = tzwhere.tzwhere() I need to install tzwhere in my windows command prompt -
Annotate QuerySet using raw SQL
In case I am asking the wrong question, let me first state the end goal: I need to allow users to filter a ListView by a field that's not in the primary model (Salesleadquote), but instead the field comes from a model (Salesleadbusinessgroup) with a FK to a related model (Saleslead). The way I am trying to approach this is by annotating a field on Salesleadquote. The models: class Salesleadquote(models.Model): salesleadquoteid = models.AutoField(db_column='SalesLeadQuoteId', primary_key=True) salesleadid = models.ForeignKey(Saleslead, models.DO_NOTHING, db_column='SalesLeadId') ... class Saleslead(models.Model): salesleadid = models.AutoField(db_column='SalesLeadId', primary_key=True) ... class Salesleadbusinessgroup(models.Model): salesleadbusinessgroupid = models.AutoField(db_column='SalesLeadBusinessGroupId', primary_key=True) salesleadid = models.ForeignKey(Saleslead, models.DO_NOTHING, db_column='SalesLeadId') businessgroupid = models.ForeignKey(Businessgroup, models.DO_NOTHING, db_column='BusinessGroupId') The desired result (queryset), in SQL: SELECT slq.*, slbg.BusinessGroupId FROM crm.SalesLeadQuote slq LEFT JOIN (SELECT SalesLeadId, BusinessGroupId FROM crm.SalesLeadBusinessGroup ) slbg ON slbg.SalesLeadId = slq.SalesLeadId WHERE slbg.BusinessGroupId IN (5,21) I know I can get a RawQuerySet by doing something like Salesleadquote.objects.raw("SELECT salesleadquote.*, \ salesleadbusinessgroup.businessgroupid \ FROM salesleadquote \ LEFT JOIN salesleadbusinessgroup \ ON salesleadquote.salesleadid = salesleadbusinessgroup.salesleadid \ WHERE salesleadbusinessgroup.businessgroupid IN (5,21)") But I need the functionality of a QuerySet, so my idea was do annotate the desired field (businessgroupid) in Salesleadquote, but I've been struggling with how to accomplish this. -
django: db: what is the diff between connections vs connection
In Django database queries: i found two ways to get the last query: from django.db import connections connections['default'].queries[-1] Or from django.db import connection connection.queries[-1] What is the difference between connections['default'] and connection when to use what. -
Overriding Django's DurationField display
My model has a DurationField which is editable in Django Admin. I don't like how Django (inheriting its behavior from Python) displays negative durations, so I've tried to monkey patch it: test = lambda: duration.duration_string(datetime.timedelta(seconds=-5)) == \ '-00:00:05' if not test(): _duration_string = duration.duration_string def duration_string(duration): if duration.days < 0: return '-' + _duration_string(-duration) return _duration_string(duration) duration.duration_string = duration_string assert test() This code gets run as part of my AppConfig.ready() method. However, in Admin, the field still displays values formatted the default way. Is there some other way to customize how a DurationField's value is rendered in Admin? -
Celery shared data
I have implemented websocket in Django app using Django-channels, now the front-end send some data through the websocket and i want the current running celery task to be able to read it. I tried creating shared memory static object, but not working. SimulationInputs.add(simulation_id=simulation.id, init_data=init_inputs) return InteractiveSimulationTask.delay_or_fail( simulation_id=simulation.id ) class SimulationData: data = '' class SimulationInputs: data = None @classmethod def init_manager(cls, manager): manager = Manager() cls.data = manager.dict() @classmethod def add(cls, simulation_id, init_data): cls.data[simulation_id] = init_data @classmethod def write(cls, simulation_id, simulation_data): if cls.data.get(simulation_id): cls.data[simulation_id] = simulation_data @classmethod def read(cls, simulation_id, simulation_data): simulation_data.data = cls.data.get(simulation_id) # manage.y if __name__ == "__main__": SimulationInputs.init_manager() class InteractiveSimulationTask(JobtasticTask): def calculate_result(self, simulation_id, **kwargs): while True: SimulationInputs.read(simulation_id=self.simulation.id, simulation_data=simulation_data) The task always throw exception cls.data.get(simulation_id): NoneObjectType has no method get I need to share data between the celery task and the main process. Any hint? -
ModuleNotFoundError --- Exception Value: No module named 'cart.contexts'
def add_to_cart(request, id): """Add a quantity of the specified product to the cart""" quantity=int(request.POST.get('quantity')) cart = request.session.get('cart', {}) if id in cart: cart[id] = int(cart[id]) + quantity else: cart[id] = cart.get(id, quantity) request.session['cart'] = cart return redirect(reverse('index')) -
Inconsistent results with queries of JSONFields in Django
I have a model like this: class Task(models.Model): data = JSONField(encoder=DjangoJSONEncoder) and data is populated with either {deleted: true} or {}, but in the future might also have {deleted: false}. I'm trying to find how many Tasks are not deleted, but I get inconsistent results depending on what type of query I use. If I use Task.objects.exclude(data__deleted=True), I get 0, which is incorrect. If I use Task.objects.exclude(data__deleted='true'), I get 58, which is incorrect. If I use Task.objects.filter(data__deleted__isnull=False), I get 29, which is correct but only happens to works since I don't have any {deleted: false} in the database currently. Calculating manually like this: count = 0 for task in Task.objects.all(): if not task.data.get('deleted'): count += 1 also works because count is 29. What is the proper query to use to filter the results correctly?