Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set cookie in GraphQL mutation
I need to update a cookie in GraphQL mutation using graphene and Django. My first idea was to add cookie to context (which is request) and then set it in middleware. I have a very simple mutation that looks like that: class SetWantedCookieMutation(graphene.Mutation): class Arguments: wanted_cookie = graphene.String(required=True) ok = graphene.Boolean(required=True) def mutate(self, info, wanted_cookie): # set cookie here info.context.wanted_cookie = wanted_cookie return SetWantedCookieMutation(ok=True) And Django Middleware is that: class CookieMiddleware(MiddlewareMixin): def process_response(self, request, response): if (hasattr(request, 'wanted_cookie')): response.set_cookie('wanted_cookie', request.wanted_cookie) return response But I cannot get currency_code in my CurrencyCookieMiddleware. Any ideas how to set cookie in mutation/moddlewere? Or what are other ways to set cookie through graphene mutation? -
Django "PostgreSQL" add non-nullable field
I'm new learner in django, i have a minor problem i added slug field in model.py file and i run python manage.py makemigrations code: . . . slug=models.SlugField(unique=True) So, command prompt said that, (sorry for my bad english) 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: My questions is; What should I do? -
Getting Django admin emails for deleted pages
I am reporting a weird behavior with Django admin emails (or at least I think it's weird as I don't really know the cause). When a server error occurs, for instance I navigate to a page that does not exist, I get the 500 error and the relative email gets sent to me and this is correct, all good. The problem I am having is that I am getting a lot of this admin emails for old pages that I have deleted (even very old, like deleted more than one year ago). I am not navigating to those pages, and I'm pretty positive there are no links on my website (or other websites) that point to those pages. Also, my google analytics is not recording visits to these specific pages, while if I navigate to a 500 error page on my browser, google analytics records the visit. I really have no clue about this, any ideas? A little more about the setup: the website is in the sports analytics field. We try to analyze all the matches that we cover and provide information about the match on a specific page. I set up the website so that each analyzed match … -
How can I capitalize first word of "lorem" template tag output in Django 2.2?
Django provides a useful "lorem" template tag that will output some "lorem ipsum" text, but the text is all lowercase. How can the first word be capitalized, to get "Lorem ipsum ... "? I know that if I had a string I could run it through a filter, but I don't know how to filter the output of a tag. -
Sending href and id of clicked link from page to django using Ajax
I have an on click JQuery event handler that I want to use to send the href and id of any clicked link to my Django server. But I am having a hard time finding a good tutorial/info about using Django with Ajax. Let's say I want to send the id and href of the link, have Django check if the link has https, and send the href along with a message back as a response. Something like: $("a").on("click", function(e){ e.preventDefault(); if(e.target.href){ let id = e.target.id; let href = e.target.href; $.ajax({ url: "/nameOfFunction/", data: {"id":id, "href":href}, type: "POST", success: function(response) { if(response.msg=="yes"){alert(response.href+" is Secure")} else{alert(response.href+" is Not Secure")} }, error:function(error) { console.log(error); } }); } }); def nameOfFunction(request): if ("https" in request.POST.get("href")): msg = "yes" else: msg = "no" return ({"msg":msg, "href":href}) Can someone help me fix this so that it works? -
Reverse for 'tkr_ratio' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['dashboards/api/tkr_ratio$']
Caught an exception while trying to render: django.urls.exceptions.NoReverseMatch: Reverse for 'api_tkr_ratio' with arguments '('',)' not found. 1 pattern(s) tried: ['dashboards/api/tkr_ratio$'] Here is the urls.py: path('api/tkr_ratio', views.api_tkr_ratio, name = 'api_tkr_ratio'), Here is the views.py: def api_tkr_ratio(request, ticker1 = 'SPY', ticker2 = 'AAPL'): tickers_values = TSDB.objects.filter(TICKER__in = [ticker1, ticker2]).values("DATE", "TICKER", "CLOSE") tickers_list = [] for ticker in tickers_values: tickers_list.append([ticker['DATE'], ticker['TICKER'], ticker['CLOSE']]) df = pd.DataFrame(tickers_list, columns = ['DATE', 'TICKER', 'CLOSE']) df = df.pivot_table(values = 'CLOSE', index = 'DATE', columns = 'TICKER') print(df) json_list = [] df['RATIO'] = df[ticker1]/df[ticker2] for i in df[['RATIO']].itertuples(): json_list.append([totimestamp(i[0])*1000, i[1]]) return JsonResponse(json_list, safe = False) Here is the HTML template where I am trying to run the script: <script> var tkr_data = { ticker1: "ticker1", ticker2: "ticker2" } $.getJSON('{% url 'dashboards:api_tkr_ratio' tkr_data %}', function(data) { Highcharts.chart('container', { chart: { zoomType: 'xy' }, title: { text: 'Ticker Ratio' }, xAxis: { type: 'datetime', gridLineColor: '#F7F7F7', labels: { format: '{value:%m/%d/%y}', align: 'center' }, }, yAxis: { title: { text: 'Ticker Ratio (%)' }, labels: { format: '{value:.0f}%' } }, }); }); </script> I don't have the slightest clue of where this error is coming from. I'm going to assume that it is what I am passing in $.getJSON(). (I am new … -
Displaying size adjusted buttons on specific points on a line in HTML/CSS
I am a newbie in HTML/CSS and am building a web application using Django right now. This application draws it's data from a precalculated database. Each entry has a certain length and contains several child entries, whichs length each is a fraction of the whole length of the parent entry. As python dictionary it looks like this: {entry1: {'length': 10000, {child1}: {'start':1, 'end':1000 }, {child2}: {'start':2000, 'end':6000}, ...} The length of each child is end-start here. What I am trying to do is to display each entry as a line in HTML/CSS, and each child entry is shown as button on that line. The size of each button on the line should reflect it's length (which is a fraction of the parent entry length, but it's different for each child entry). Importantly, each child entry has a certain position on the parent entry (For example: The parent entry length is 10000, child 1 is at 1-1000, child 2 is at 2000 to 6000 and so on) The result I want to get to is something like this: I have several tens of entries that I want to display like this, eventually even making graphic connections from one entry to the … -
Django - redirecting a user to a specific view after GET to a separate view, changing language settings
I have a site with that offers 2 language choices - English & Japanese. To change between the languages, A user clicks a button taking them to a view which changes the setting. Previously, it had always redirected to the home page but now I want to take them to where they were before. The current path is passed as a url param which is then saved to a response variable, which then has it's language cookie set before being returned. For some reason, when I use the parameter in the redirect function, the language cookie doesn't set at all but using reverse (i.e. when it was hard coded to go back home) wass working fine. How do I get the redirect function with the param to work like the one set with reverse? Thanks in advance! Code: Template Links: <a href="{% url 'language' 'en' %}?q={{ request.path }}" class="lang-choice btn btn-primary">English</a> <a href="{% url 'language' 'ja' %}?q={{ request.path }}" class="lang-choice btn btn-info">日本語</a> Urls: path('lang/<str:language>/', v.change_language, name='language') View: def change_language(request, language): # language is 'en' or 'ja' redirect_page = request.GET.get('q') # e.g. '/about/' # note: redirect_page == reverse('about') is True # make sure language is available valid = False for l … -
Python: Not able to read properties from property file
I'm trying to read configurations from a property file and store those properties in a variable so that it can be accessed from any other class. I'm able to read the configuration from the config file and print the same but I'm getting an exception when those variables are accessed from some other class. my config file Config.cfg.txt [Ysl_Leader] YSL_LEADER=192 Generic class where i will store my properties in a variable. ConfigReader.py import configparser class DockerDetails: config = configparser.RawConfigParser() _SECTION = 'Ysl_Leader' config.read('Config.cfg.txt') YSL_Leader = config.get('Ysl_Leader', 'YSL_LEADER') print(YSL_Leader) Another class where I'm trying to get the get the 'YSL_Leader' value def logger(request): print(ConfigReader.DockerDetails.YSL_Leader) Exception: File "C:\Users\pvivek\AppData\Local\Programs\Python\Python37-32\lib\configparser.py", line 780, in get d = self._unify_values(section, vars) File "C:\Users\pvivek\AppData\Local\Programs\Python\Python37-32\lib\configparser.py", line 1146, in _unify_values raise NoSectionError(section) from None configparser.NoSectionError: No section: 'Ysl_Leader' FYI: I'm not getting any exception when I run ConfigReader.py alone -
Preventing Django templates base.py from resolving every possible foreign key relationship in an inline
I am attempting to create an Inline on an existing Django Admin class, but am finding the page render times to be far too slow. I have identified the problem to lie in django templates/base.py "resolve" function, or in the subsequent render function (Django 2.1). It would seem all my "Track" objects are being loaded for all forms in the line in all cases. How can I increase the performance of this function by changing my code? Should I restructure the Recording-->Tracklist-->TracklistTrack-->Track relationship? Could I cache my model objects somehow? Is using a .through model in an inline unwise? To begin finding the problem, I started using a profiler. When running a timer on the code, the profiler in question causes negligible slowdown. I can see that the vast majority of my 22s function call is as follows: ncalls tottime percall cumtime percall filename:lineno(function) 123 0.001 0.000 18.194 0.148 django/forms/widgets.py:232(_render) 123 0.002 0.000 18.190 0.148 django/forms/renderers.py:29(render) 848104 1.037 0.000 3.867 0.000 django/template/base.py:668(resolve) I looked at stack overflow posts which suggested overriding both "queryset" and "formfield_for_db". When printing context in the django functions, I can see that all of my Tracks are being piped through base.py resolve, and presumably, this is … -
Django does not work after shutdown the PC
Everything worked perfectly, I turned off the computer and Django's project no longer works on any computer. When I try to do python manage.py runserver I get the error: ImportError: No module named custom_rest_permissions But my own modules are there and I can access with the Eclipse link if I press on them... Eclipse autocomplete the imports too and does not work anyway. Everything worked perfectly before I turned off the computer. I attach a picture. -
Foreign key to_field shows error when running migrate: return int(value) ValueError: invalid literal for int() with base 10: 'who_by'
So this is what I want to happen: I want model B > who_by to equal model A > who_by I am connecting model B > who_by to model A > who_by currently by using a Foreign key to_field. I ran the manage.py makemigrations (foldername) command and it ran successfully and created the migration file but when I run the manage.py migrate command it doens't work and shows me an error. Here is my code for the models.py file: #models.py from django.db import models from django.contrib.auth import get_user_model class A(models.Model): who_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) class B(models.Model): who_by = models.ForeignKey(A, to_field='who_by', on_delete=models.CASCADE, unique=True) & here is the full stack trace: (virtual_env-VO8CRmfn) C:\Users\username\Projects\project_name>manage.py migrate System check identified some issues: WARNINGS: app_name.A.who_by: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. Operations to perform: Apply all migrations: account, accounts, admin, auth, contenttypes, sessions, sites, socialaccount, app_name Running migrations: Applying app_name.0002_auto_20190624_1339...Traceback (most recent call last): File "C:\Users\username\Projects\project_name\manage.py", line 21, in <module> main() File "C:\Users\username\Projects\project_name\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\username\.virtualenvs\virtual_env-VO8CRmfn\lib\site- packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\username\.virtualenvs\virtual_env-VO8CRmfn\lib\site- packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\username\.virtualenvs\virtual_env-VO8CRmfn\lib\site- packages\django\core\management\base.py", line 323, … -
How to post form then if back button pressed, redirect to another page?
I apologize for not having a better title first. What I want to achieve is, after saving data to DB with a form, I don't want the user to be able to go back on the previous page to the form again. Instead when the user presses the back button after posting the form, he/she should be redirected one page before. For example this can the flow: User is in admin page -> goes to add blog page -> fills the forms and saves the data to DB, then is redirected to another page (say main page). Now when he/she presses the back button, it will be redirected to the form with already filled data in the input fields (which I don't want to). How can I make it that after posting and being redirected, when he presses the back button, he/she will be redirected to admin page instead. Thank you beforehand. -
Terminal gives me "invalid syntax" error when running python runserver
I am trying to start a new django project. However, whenever I run the server I get a "SyntaxError: invalid syntax" error. This is the actual prompt that terminal gives me: Joshuas-MacBook-Pro-2:src JoshGarza$ python manage.py runserver File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax This the code in manage.py: import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trydjango.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) -
How to ignore some migrations in production
By mistake, now there is an inconsistency in the production and my local Django Migrations and the makemigrations command will generate correct migrations that when I locally run with an empty database. for example, this migration will generate: class Migration(migrations.Migration): dependencies = [ ('campaign', '0208_auto_20190619_0929'), ] operations = [ migrations.RemoveField( model_name='bannerad', name='average_price', ), migrations.RemoveField( model_name='bannerad', name='click', ), .... blah migrations.AlterField( model_name='bannerad', name='size', field=models.IntegerField(choices=[(0, '120x240'), (1, '120x600'), (2, '970x250'), (3, '160x600'), (4, '240x240'), (5, '300x100'), (6, '300x250'), (7, '468x60'), (8, '600x300'), (9, '728x90')]), ), ] but in the production running the generated migrations already migrated (for example the Bannerad model in production database has not average_price) and when I run the migrate command in production. How can I fix this issue? -
django signals module object has no attribute 'post_save'
I am trying to when "Salon" object created, create a "Vault" object this is the models.py from django.db import models,signals from django.contrib.auth.models import User class Vault(models.Model): salon = models.ForeignKey(Salon, on_delete=models.CASCADE, null=False, unique=False) cash = models.PositiveIntegerField() class Salon(models.Model): salon_ismi = models.CharField(max_length=25,unique=False) adres = models.CharField(max_length=255, unique=False) ulke = models.CharField(max_length=25, unique=False) sehir = models.CharField(max_length=24, unique=False) kasa = models.PositiveIntegerField(blank=True, unique=False) class Meta: ordering = ('-pk',) verbose_name_plural = "Salonlar" def __unicode__(self): return u'%s' % self.pk def __str__(self): return self.salon_ismi def get_absolute_url(self): return reverse('kentyonetim_salon_detail', args=(self.pk,)) def create_vault(self, sender, instance, created, **kwargs): """Create Vault Model for every new Salon Model.""" if created: Vault.objects.create(salon=self.salon_ismi,) signals.post_save.connect(Salon.create_vault, sender=Salon, weak=False, dispatch_uid='models.create_Vault') When I try to run the server, it gives me an error: AttributeError: module 'django.core.signals' has no attribute 'post_save' Please help me out. Would be much appreciate. Thank you. -
Use db function in query (django)
i am trying to filter query through function applied to column on parent query. how I use function to an outerref? example MY_QUERY=Subquery(Goal.objects.filter(year=ExtractYear(OuterRef("created"))).values("target")[:1]) thelist = list(MyModel.objects.annotate(goal=MY_QUERY)) i get error resolvedouterref object has no attribute error tho :( -
How to upload files based on primary key of foreignkey?
Basically I am trying to create an app which can allow user to upload lessons material such as documents on their specific posts. However, I am unsure of how I should display the documents uploaded based on the primary key of the posts. As of now, my posts are displaying all the documents that are being uploaded by the particular user. This is my 'Post' model class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default = 'default0.jpg', upload_to='course_image/') description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField(default = 0) def __str__(self): return self.title -
Save and Continue in Django Forms
I have created a django form which at the moment I can only save the POST. Would like to add Save and Add another button in my templates and views function. Has anyone found a solutions. -
How to loop a django modelform?
My template is: <form method="POST" action="{% url 'academics' %}"> {% csrf_token %} {% for query in queryset %} <input type="text" name="Student" class="form-control" id="id_Student" value="{{query}}"> <input type="text" name="Hour" class="form-control" required id="id_Hour"> <input type="text" name="Subject" class="form-control" required id="id_Subject"> <input type="checkbox" name="Presence" id="id_Presence"> {% endfor %} <button type="Submit" id="submit">Submit</button> </form> My views.py is: def academics(request): if request.user.is_staff: form = forms.AttendanceForm() context = { 'form': form, 'queryset': User.objects.filter(profile__Year='SY',profile__Department='CSE') } if request.method == "POST" : form = forms.AttendanceForm(request.POST) if form.is_valid(): student = request.POST.get('Student') hour = request.POST.get('Hour') subject = request.POST.get('Subject') boolean = request.POST.get('Presence') def bool(boolean): if boolean == 'on': return 'True' else: return 'False' form = Attendance(Student=student,Hour=hour,Subject=subject,Presence=bool(boolean)) form.save() return render(request, 'console/academics.html',context) My models.py is: class Attendance(models.Model): Student = models.CharField(max_length=100, blank=False) Hour = models.CharField(max_length=1, blank=False) Subject = models.CharField(max_length=8, blank=False) Date = models.DateTimeField(default=timezone.now) Presence = models.BooleanField(default=False, blank=False) def __str__(self): return f'{self.Student}' My objective is i need to loop the form from a loop based on a query. The number of queries i get, the number of forms i need to submit at once. In the above template i can only submit the last form ie., if i get three queries, only the third form is submitted. How to create multiple objects at the same time? -
How to use oneToMany in Django
I am trying to add OneToMany field in django rest models. But Django is not giving an options for it. Can anyone suggest something similar to java @OneToMany in Django framework -
How to return a JsonResponse from a class?
We're using DRF for our backend. I'm trying to create a class to handle non-fatal messages throughout our system, returned as a JsonResponse - like APIException, but without raising an exception. The idea is to be able to do something like this: return APIMessage("This is my message.") ...with optional args to specify/overwrite message_type, message_code, and status_code. The first problem I ran into was that __init__ can't return a value. From this post, I found the way I should be doing it, but I now get this error... __new__() takes 1 positional argument but 2 were given Here's my class... class APIMessage(object): default_message = None default_message_code = 'message' default_message_type = 'status' default_status_code = 200 def __init__(self, message=None, message_code=None, message_type=None, status_code=None): if message is None: message = self.default_message if message is None: raise APIMessageRequired() if message_code is None: message_code = self.default_message_code if message_type is None: message_type = self.default_message_type self.status_code = status_code if status_code is None: self.status_code = self.default_status_code self.result = { 'result': { 'message': message, 'message_code': message_code, 'message_type': message_type, } } def __new__(cls): return JsonResponse(cls.result, status=cls.status_code) I realize it's wanting an explicit "self" arg, but from the example code in the above linked post, the __new__ method should have "cls" as its … -
Angular Service Worker in Django not working in Offline Mode
I am using Angular and Django to create a Progressive Web App (PWA) application. More specifically I am using the @angular/pwa package and want to have a webapp which also works offline. As described below, using a simple http-server from npm yields the correct results, but once the Angular build is deployed to Django, the webapp doesn't work in offline mode. Setup I am building the Angular front end with the following command: ng build --prod --deploy-url="/static/" --base-href="/" --outputHashing=none Then I put the files in webappBackend/webappBackend/static/. I have also added this directory as a static directory in settings.py. Things I had to fix before running the Django server: --deploy-url doesn't add a prefix to the manifest.webmanifest and to favicon.ico in the index.html <script src="/static/runtime-es2015.js" type="module"></script> <script src="/static/polyfills-es2015.js" type="module"></script> <script src="/static/runtime-es5.js" nomodule></script> <script src="/static/polyfills-es5.js" nomodule></script> <script src="/static/main-es2015.js" type="module"></script> <script src="/static/main-es5.js" nomodule></script></body> --deploy-url doesn't add a prefix to the files in ngsw.json, so I had to fix that in for app and asset resources and also in the hashTable. Here I only include some of the changes for easier reading: "urls": [ "/static/favicon.ico", "/static/index.html", "/static/main-es2015.js", "/static/main-es5.js", "/static/polyfills-es2015.js", "/static/polyfills-es5.js", "/static/runtime-es2015.js", "/static/runtime-es5.js", "/static/styles.css" ] I had to add a URL pattern to catch the … -
How to save file in django rest
I have problem with saving files to my server. I need to upload and save files, but id doesn't work for me. I can send file from my UI to my rest api, but i am not able to save the files. My Models fs = FileSystemStorage(location='/media/attachments/') ... class TicketLog(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.DO_NOTHING, related_name='ticket_log') created_date = models.DateTimeField(auto_now=False, auto_now_add=True) created_by = models.ForeignKey( User, on_delete=models.DO_NOTHING, related_name='ticketlog_creator') note = models.TextField() class Meta: ordering = ['pk'] def __str__(self): return self.note class TicketFiles(models.Model): ticketlog = models.ForeignKey(TicketLog, on_delete=models.CASCADE, related_name='log_file', blank=True, null=True) attachment = models.FileField(upload_to='attachments', storage=fs) class UploadWithFile(APIView): parser_classes = [MultiPartParser, ] def post(self, request): content = request.data['file'] data = json.loads(request.data['data']) queue = Queue.objects.get(pk=data['queue']['id']) priority = Priority.objects.get(pk=data['priority']['id']) status = Status.objects.get(pk=data['status']['id']) created_by = User.objects.get(pk=data['ticket_log'][0]['created_by_id']) ticket_data = Ticket( name=data['name'], priority=priority, status=status, queue=queue, created_date=datetime.datetime.now(), created_by=created_by ) ticket_data.save() log_data = TicketLog( ticket=ticket_data, created_date=datetime.datetime.now(), created_by=created_by, note=data['ticket_log'][0]['note'] ) log_data.save() file_data = TicketFiles( ticketlog=log_data ) file_data.attachment.save(content.name, content) file_data.save() return HttpResponse(content) It seems that everything works fine and the database is updated correctly, but the files are not saved on server. -
How to create custom block in wagtail?
Its my StreamField: body = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ]) And my question is: how to add my own Block that i can pass to StreamField? I meant block that contains multiple images, somehting like block? I didn't find answer for my question in wagtail docs.