Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to access session data from views.py created outside of views.py
I need to pass a jwt token generated in backend.py to views.py. In backend.py i save it like this: s = SessionStore() s['id_token'] = id_token s.create() key1 = s.session_key in views.py i try to get the session_key from that session like key2 = request.session.session_key But the two keys differ. What am i doing wrong and how can i access s['id_token'] in views.py? -
How to store data from YAML file in django model
I know it is possible to store YAML data in the Django model using the JSON field. However, I would prefer to use the Django model instead of a JSON field. The reason being that when I store as JSON blob, I can query it although it might be harder to do considering I don't have a schema making it a bit messy when I need to change something later e.g when I add a new field to the YAML files, with normal Django model, this is easy to do with migration. But with JSON, it can be a bit harder. So I need help on how I can use a Django model with different fields instead of a JSON field -
The view acc_app.views.merchant_messages didn't return an HttpResponse object. It returned None instead
Here I'm creating a chat system between merchants and admin, but every time I send a message via form it's showing this error. Request Method: POST Request URL: http://127.0.0.1:8000/merchant-dashboard/messages/ Django Version: 3.1 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'acc_app', # app 'widget_tweaks', 'rest_framework'] Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 186, in _get_response self.check_response(response, callback) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 307, in check_response raise ValueError( Exception Type: ValueError at /merchant-dashboard/messages/ Exception Value: The view acc_app.views.merchant_messages didn't return an HttpResponse object. It returned None instead. MyCode views.py @csrf_exempt def message_list(request, receiver=None): .... elif request.method == 'POST': # message = request.POST['message'] # admin = UserAccount.objects.get(is_superuser=True) # send_message = Message.objects.create(sender=request.user, receiver=admin, message=message) # send_message.save() serializer = MessageSerializer(data=request) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @login_required(login_url='login-user') def merchant_messages(request): if request.method == "GET": message_list(request, receiver=request.user) admin = UserAccount.objects.get(is_superuser=True) all_messages = { 'receiver': UserAccount.objects.get(email=admin), 'messages': Message.objects.filter(sender=admin, receiver=request.user) | Message.objects.filter(sender=request.user, receiver=admin) } return render(request, 'dashboard/merchant/message-task.html', all_messages) HTML file <form method="POST" id="chat-box"> {% csrf_token %} <div class="input-group"> <input name="message" typetype="text" class="form-control" placeholder="Enter Message"/> <span class="input-group-btn"> <button class="btn btn-success" type="submit">SEND</button> </span> </div> </form> It works fine to show the received messages, but can't … -
Model assignment in Django
I have a question regarding Model-Assignment in Django. I have a Model Field where i can add an amount of pieces of a product. I want to be able to assign for example 100 pieces of the product to diffrent locations in the warehouse. For example: Product A = 100 pieces. 30 pieces are linked to warehouse 1 30 pieces are linked to warehouse 2 40 pieces are linked to warehouse 3 how would you solve this problem? I'm kinda new in python & django. Best Regards, Marcel -
Python/Django loop optimization
i am currently working on a Django website and at a certain point need to generate a dataset for a graph out of model data. Over the last days i have been trying to optimize the code to generate that data, but its still relatively slow with a dataset which will definetely get a lot larger when the website is up. The model i am working with looks like this: class Prices(models.Model): name = models.CharField(max_length=200, blank=False) website = models.CharField(max_length=200, blank=False, choices=WEBSITES) date= models.DateField('date', default=date.today(), blank=False, null=False) price = models.IntegerField(default=0, blank=False, null=False) class Meta: indexes = [ models.Index(fields=['website']), models.Index(fields=['date']) ] It stores prices for different items(defined by the name) on different websites. For the graph representation of the model I need two arrays, one with all the dates as the y-Axis and one with the prices of the item at that date(which might not be available, not every item has a date entry for every day on every website). And all of that for every website. My code for generating that data looks like this atm: for website in websites: iterator = Prices.objects.filter(website=website).iterator() data = [] entry = next(iterator) for date in labels: if entry is not None and date == … -
Django ckeditor paste images without text
I am using django-ckeditor with the Image plugin. I wish to copy-paste some equations from MS-Word into the ckeditor as an image. The issue is that the equation related text also appears beside the image. Is there any way to only show the image? Please note that I am not using the Paste from Word plugin nor am I interested in Mathjax plugin. I tried using the Paste from Word plugin along with this workaround but it had no effect. The image part only appears when I'm using the Image plugin. -
ReactJS form submit this.props.history.push('/downloads') not linking through to the new page
I am trying to Push to a new page once a user has filled out a form using this.props.history.push inside the function below. handleSubmit = async event => { event.preventDefault() try { const res = await newEnquiry(this.state.formData) this.props.history.push('/downloads') console.log(res) } catch (err) { console.log(err.response.data) } } The ReactJS form is working fine on the /contacts page, and submits information to my Django back-end so I know it's working OK, however I cannot get the redirect to work and it's giving me this error message. <form onSubmit={this.handleSubmit}> is inside my form tag and that's working fine so I am pretty sure it's not a problem with my form. -
How I can count values in Django?
I am trying to count data from the table, I have a relation between 2 tables and I want to display records after the count in the Django template, Please let me know how I can display count values in Django. here is my Html file code. {% for a in product.GetRelatedname.all %} {{a.test_data_id.count}} {% endfor %} but its counting nothing ` -
Publishing my Djangoapp on pythonanywhere.com
The error im getting in my wsgi.py: Error running WSGI application ImportError: cannot import name 'application' File "/var/www/ufuck7_pythonanywhere_com_wsgi.py", line 43, in from todo import application # noqa -
django ForeignKey relation how to get data other tables
I have 3 models class product(models.Model): name = models.CharField(max_length=30) class order(models.Model): order_number = models.CharField(max_length=30) class order_products(models.Model): order_id = models.ForeignKey(order,null=True) product_id = models.ForeignKey(product,null=True) One order has multiple products is this relation is correct and if it is correct then if i get all the order then how can i get it related product data? -
Pass initial argument from django to django dash app
I want to pass a variable from django view to DjangoDash application. In details, I want to use the id that I receive from get method in Django view to the DjangoDash in order to make some plots with filtered data based on that id. I followed this approach https://github.com/GibbsConsulting/django-plotly-dash/issues/173 which was very helpful, but still can't have access of the variable in the DjangoDash. views.py def getID(request): queryid= request.GET['queryid'] context = {'data':{"query_id":queryid}} template_name="djangoDash.html" return render(request, template_name, context) In order to use the DjangoDash Plotly I used this with initial argument the content data from the view. djangoDash.html ..... {% plotly_app name='djangoDash' ratio=0.45 initial_arguments=data %} .... When I define the djangoDash app I use this app = DjangoDash('djangoDash', id='query_id', serve_locally=False, suppress_callback_exceptions=True) And I use this id as an input over my layout to use it for the queries with the bellow callback. layout = html.Dic([ dcc.Input(id='query_id'), html.Div(id='result'), ]) @app.expanded_callback(dash.dependencies.Output('result', 'children'), [dash.dependencies.Input('query_id', 'value')]) def display_output(query_id): result= query_id return result The error I get when I load the page is File "/home/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/.local/lib/python3.6/site-packages/django/views/decorators/csrf.py", … -
Django Ajax Dynamic variable Uncaught ReferenceError
I am trying to send some variable from textarea to django view via Ajax. I am getting this error. Uncaught ReferenceError: saveLinks is not defined at HTMLButtonElement.onclick ((index):794) Also, I could return variables in for loop my Spider.id variable keep sending "1". View.py from django.views.decorators.csrf import csrf_exempt @csrf_exempt def saveLinks(request): if request.is_ajax(): id = request.GET.get('spider_id') p1 = get_object_or_404(Spiders,id = id) files = request.GET.get('text') files = files.replace("https://"+p1.spider_url+"/","") files = files.split(";") for file in files: new_data = Urls(spider_id=int(p1.id),url_tag=file) new_data.save() return redirect(request.META['HTTP_REFERER']) index.html {% for spider in spiders%} <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Yeni Linkler</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="recipient-name" class="col-form-label">Market : {{spider.spider_name}}</label> </div> <div class="form-group"> <label for="message-text" class="col-form-label">Linkler</label> <textarea rows=15 class="form-control" name="id_amount" id="id_amount"></textarea> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Kapat</button> <button type="button" class="btn btn-primary" value="id_amount Links" onclick="saveLinks({{spider.id}})">Save</button> </div> </div> </div> {% endfor %} Ajax - script function saveLinks(output) { var text = document.getElementById('id_amount').value; jquery.ajax({ method: 'GET', url: '{% url ' Bot: saveLink ' %}', type: 'GET', data: { 'text': text, 'spider_id': parseInt(output) }, dataType: 'text', success: function () { location.reload(); } }).done(function (data) { console.log('SUCCESS') }).fail(function (xhr, text, error) { console.log(text, error) }); } … -
Automatically search all fields for all models in django admin
I want to be able to search all models for all fields in Django admin, without having to setup ModelAdmin and searchfields individually. example: I have all my models in model.py: # This is an auto-generated Django model module. from django.db import models class Diagnosis(models.Model): id = models.BigAutoField(primary_key=True) code = models.CharField(max_length=255) starting_node = models.ForeignKey('Node', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'diagnosis' def __str__(self): return 'Diag #' + str(self.id) + ' - ' + self.code class DiagnosisHistory(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=255, blank=True, null=True) date = models.DateTimeField(blank=True, null=True) id_user = models.TextField(blank=True, null=True) report = models.TextField(blank=True, null=True) json_report = models.TextField(blank=True, null=True) vin = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'diagnosis_history' # and so on and the admin.py where I register the models: from django.contrib import admin from . import models # Do not care. Register everything for cls in [cls for name, cls in models.__dict__.items() if isinstance(cls, type)]: admin.site.register(cls) I don't want to run through each Model and manually create a ModelAdmin with each field -
How to Print all values for Single object in Django?
i am selecting last object from my table using following Code data= MyModel.objects.last() This is Displaying object. i want to display full array of 'data' object.for that i am using Following Code data= MyModel.objects.last().values() However its not Working.How to do that? -
Emulating linux command line in python django web app
I was looking for technology to create GUI(in C++ or Python) to C command-line app. I've found some desktop libraries(e.g. Tkinter), but I was not satisfied with them, so I thought that I could use Python Django and Angular to create a pretty web app that will serve as my GUI. And here is a problem as I am new to this technology is there any way to emulate Linux shell using django in the web app. For me this is crucial for debugging the application. -
Django Dynamics URL No Reverse Match at /
I am trying to create a dynamic url but keep getting the same error. What have I done wrong here, to cause this issue? I am trying to use the default id field. Error Message NoReverseMatch at / Reverse for 'update_ticket' with arguments '('',)' not found. 1 pattern(s) tried: ['update_ticket/(?P<pk>[^/]+)/$'] views.py def updateTicket(request, pk): ticket = Ticket.objects.get(id=pk) form = TicketForm(instance=ticket) if request.method == 'POST': form = TicketForm(request.POST, instance=ticket) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'itdb/ticket_form.html', context) urls.py path('update_ticket/<str:pk>/', views.updateTicket, name="update_ticket"), -
How to implement a people availability api in DRF?
python: 3.7 django 3 I am trying to build an API using DRF to arrange a meeting between people base on each person. One person can have many availability dates while availability date can be share for many persons. I have the following schema: from django.db import models # models.py class Availability(models.Model): date = models.DateField() start = models.TimeField() end = models.TimeField() class Meta: unique_together = ('date', 'start', 'end') class Person(models.Model): email = models.EmailField(max_length=70, primary_key = True) date = models.DateField() start = models.TimeField() end = models.TimeField() availability = models.ManyToManyField(Availability) My wish is that after a person insert his Availability I would like to iterate over the time and insert it to the Availability model as hourly Availability Exmaple: A person Availability could be the following (19.09.2022, 09:00 - 12:00) I would like to do the following: iterate over the person time and save each Hour in the Availability table, meaning insert (19.09.2022, 09:00, 10:00), (19.09.2022, 10:00, 11:00), (19.09.2022, 11:00, 12:00) for each insert save in the Person field with the availability id which was created I am not sure how to implement the logic,I thought about the following: should I in the serializers.py in the Person create function iterate and insert … -
Python Django: Process DataFrame and perform calculations to use in chart.js
I'm trying to get my head around dataframes. I'm trying to get a key-value list with as key the date and as value the total SUM price of all the provided stocks on that day. I was reading on dataframes and noticed that some people mentioned that using iterrows() is not advised and that you should do you calculations within the dataframe. But I'm failing to see how I should do that and have a list that I can pass through to my chart.js data. Code data = yf.download( # or pdr.get_data_yahoo(... # tickers list or string as well tickers = "AAPL GOOGL NIO"), # use "period" instead of start/end # valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max # (optional, default is '1mo') period = "ytd", # fetch data by interval (including intraday if period < 60 days) # valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo # (optional, default is '1d') interval = "1d", # group by ticker (to access via data['SPY']) # (optional, default is 'column') group_by = 'ticker', # adjust all OHLC automatically # (optional, default is False) auto_adjust = False, # download pre/post regular market hours data # (optional, default is False) prepost = False, # use threads for mass downloading? (True/False/Integer) # (optional, default … -
what is the best way to learn Django 3 (Django learning path)
i am a full stack developer and i use "node.js" but i wanna learn django i don't how i start i searched on udemy and all course start full stack from scratch and i tried to learn from the official website but i couldn't, i need to know what should i learn with django what the database is most used i am good with python -
TypeError: got an unexpected keyword argument 'entry'
I am in the middle of creating an encyclopedia project. On the home page is a list of entries and I want all the entries to be linked to their entry page. Currently when I click on the link to an entry on the homepage, in this case the entry is called CSS, this is the error I get: TypeError at /wiki/CSS/ entry() got an unexpected keyword argument 'entry' Request Method: GET Request URL: http://127.0.0.1:8000/wiki/CSS/ views.py def css(request): return render(request, "entries/css.html", { "css_entry": util.get_entry("css") }) def entry(request): return render(request, entry, "encyclopedia/index.html", { "entry": util.get_entry({"entry"}) }) urls.py urlpatterns = [ path("", views.index, name="index"), path("css/", views.css, name="css"), path("<str:entry>/", views.entry, name="entry") ] index.html <ul> {% for entry in entries %} <li><a href = "{% url 'entry' entry %}">{{ entry }}</a></li> {% endfor %} </ul> The frustrating thing is if I enter into the browser: http://127.0.0.1:8000/wiki/CSS/ it works and the page loads fine but not when I click the link from the homepage. Plus, if I remove the entry argument leaving it as {% url 'entry' %} then the homepage stops working and I get the following error: NoReverseMatch at /wiki/ Reverse for 'CSS' not found. 'CSS' is not a valid view function or … -
Django: ManyToManyField with intermediary model error
Django is not managing our databases for us, therefor I created the table RulesetRuleMap to handle the ManyToMany relationship between Ruleset and Rule: Each Ruleset can consist of multiple Rules and each Rule can be used in multiple Rulesets. Models class Rule(models.Model): id = models.BigAutoField(primary_key=True) percentage_of_total = models.FloatField(blank=False, null=False) _rule_parameter = models.ForeignKey('RuleParameter', models.DO_NOTHING, blank=False, null=False) class Meta: managed = False db_table = '_rule' class Ruleset(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=300, blank=False, null=False) description = models.CharField(max_length=300, blank=False, null=False) rules = models.ManyToManyField('Rule', through="RulesetRuleMap") class Meta: managed = False db_table = '_ruleset' class RulesetRuleMap(models.Model): id = models.BigAutoField(primary_key=True) _rule = models.ForeignKey('Rule', models.CASCADE) _ruleset = models.ForeignKey('Ruleset', models.CASCADE) class Meta: managed = False db_table = '_ruleset_rule_map' Serializers class RulesetRuleMapSerializer(serializers.ModelSerializer): class Meta: model = db_models.RulesetRuleMap fields = '__all__' class RuleSerializer(serializers.ModelSerializer): class Meta: model = db_models.Rule fields = '__all__' class RulesetSerializer(serializers.ModelSerializer): rules = RuleSerializer(many=True) class Meta: model = db_models.Ruleset fields = '__all__' def create(self, validated_data): rules_data = validated_data.pop('rules') ruleset = db_models.Ruleset.objects.create(**validated_data) rules_storage =[] for rule_data in rules_data: rule, created = db_models.Rule.objects.get_or_create(**rule_data) rules_storage.append(rule) ruleset.rules.add(*rules_storage, through_defaults={}) return ruleset On a homepage the user can add/modify a Ruleset and add/modify the assosiated Rules. On submission we receive a payload like this: { "id": None, "name": "Split_50.0_Param1_50.0_Param2", "description": "test", "rules": [ … -
The best way to divide card-deck into rows in django template - django
i want to show 6 item in page in same design , like this photo https://pasteboard.co/Jrkehgg.png i have this code in html page : {% for android in single_android_post %} <div class="card-deck"> <div class="card"> <img class="card-img-top" src="{{ android.get_image }}" height="240px" width="230px" alt="اذا رأيت هذه الجمله فيرجى التواصل معنا واخبارنا بمكان الخطا لاصلاحه"> <div class="card-body"> <h5 class="card-title">{{ android.name }}</h5> <p class="card-text"> {{ android.app_contect}} </p> </div> <div class="card-footer"> <small class="text-muted">{{ android.post_date}}</small> <small class="firstsmall"><a class="bg-orange" href="" title="">{{ android.post_tag}}</a></small> </div> </div> </div> {% endfor %} i tried this code but each card take all page in width ,,, how to fix it ? -
Django: No such table while rewriting the "User" class
I'm making a Django project with Django 3.1. I was trying to rewrite the User class in Django. This is what I wrote in app_questions/models.py: import django.contrib.auth.models from django.contrib.auth.models import AbstractUser class User(AbstractUser): #pass settings.py: AUTH_USER_MODEL = 'app_questions.User' Also I created an superuser before I did these all. After that I did makemigrations and migrate in the cmd and ran the server. I open the admin page and try to edit the User I created beforehand, but when I click the edit page, this error occured: OperationalError at /admin/app_questions/user/1/change/ no such table: app_questions_user_groups Request Method: GET Request URL: http://127.0.0.1:8000/admin/app_questions/user/1/change/ Django Version: 3.1 Exception Type: OperationalError Exception Value: no such table: app_questions_user_groups Exception Location: C:\Users\*\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute Python Executable: C:\Users\*\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\*\\django_sample\\vitural_env\\zeaf', 'C:\\Users\\*\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\*\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\*\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\*\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\*\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages'] I found a few posts to solve this. These are methods I tried: makemigrations and migrate (same error) migrate (appname) --fake (same error) Add things into the User class (error in /admin: no such column) migrate --sync-db (same error) migrate --run-syncdb (same error) $ manage.py (appname) zero (failed: Unknown command) migrate --fake (appname) zero (same error) They all didn't solve the problem. Posts in 2016 or 2017 seems … -
HyperlinkedRelatedField Nesting Hyperlinks - object has no attribute
I have two models: Parent and Child. Child has a ForeignKey field in the model, which points to the Parent Model. I am trying to add a HyperlinkedRelatedField to the Parent serializer, which should create a list of all hyperlinks in a single item, which point to the Child instances, that have parent_id in them. In other words, what I want to get: [ { "id": 1, "name": "Parent 1", "children": [ "http://localhost:8000/child/1/", "http://localhost:8000/child/2/" ] }, { "id": 2, "name": "Parent 2", "children": [ "http://localhost:8000/child/3/" ] }, ... ] However, when I add the code, I receive the error: 'Parent' object has no attribute 'childen' I tried to read the REST DOCUMENTATION (particularly HyperlinkedRelatedField), tried to change the moles such as shown in the example by adding the related_name field, but it doesn't work for me. More specifically, it just doesn't want to see or connect to the child. Also, I tried to change the attributes in the HyperlinkedRelatedField to make it work, but it always gives me the error that is stated up-top. I have been trying to Google the problem, which gave me some of the results, but they don't apply to me or I just don't understand … -
Django - if value add 3 and update to IntegerField
I'm making a score app. Users can guess the next game result / winner. Now if the user guess the winning team, I want the userscore (points) to add 3 to the DB field. For this I got following Models: class Customer(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) points = models.IntegerField(null=True, default=0) class Tipp(models.Model): user = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) result_hometeam1 = models.IntegerField(null=True, blank=True) result_guestteam1 = models.IntegerField(null=True, blank=True) class Game(models.Model): hometeam1 = models.ForeignKey(Teams, on_delete=models.CASCADE, related_name="hometeam1", blank=True, null=True) result_hometeam1 = models.IntegerField(null=True, blank=True) guestteam1 = models.ForeignKey(Teams, on_delete=models.CASCADE, related_name="guestteam1", blank=True, null=True) result_guestteam1 = models.IntegerField(null=True, blank=True) E.G the user guess results: hometeam1 vs. guestteam1 10:20 and the final result is 15:20 the user guess the right winner and the points row should get 3 points to the current value. I tried to do in the template but thats not a good choice: {% if game.get.result_hometeam1 <= user_tipp.get.result_hometeam1 %} {{ users.get.points|add:3 }} {% endif %} I havn't found a method to do this if statement in the views.py. I searched for Query Expressions in the Docs but I couldn't found a solution.