Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to Render Link From Model Into Img Tag HTML
Models.py: class Product(models.Model): product_name = models.CharField(max_length=100) price = models.FloatField() weight = models.FloatField() image_link = models.URLField(max_length=500, default="http://polyureashop.studio.crasman.fi/pub/web/img/no-image.jpg") description = models.CharField(max_length=500) seller = models.ForeignKey('login_app.User') reviews = models.ManyToManyField('login_app.User', related_name="reviews") cart = models.ManyToManyField('login_app.User', related_name="carted") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = ProductManager() Views.py: def productdetails(request, product_id): try: request.session['user_id'] except KeyError: return redirect("/") product = Product.objects.get(id = product_id) print product #users = User.objects.filter(joiners = plan_id).all() context = { 'product': product, #"user":users, } return render(request, 'commerce/productdetails.html', context) HTML: <img src="{{product.image_link|urlize}}" alt="Image Not Found"> Whenever I run this output on the webpage is: https://pisces.bbystatic.com/BestBuy_US/images/products/5190/5190001_sa.jpg;maxHeight=460;maxWidth=460" alt="Image Not Found"> -
How to login a user with JavaScript via Django Rest API? (No Jquery)
I need to send an Ajax post request to Django Rest API to log a user in. How do I do this in Vanilla Javascript by sending the details- username, password, and email? I am looking for code in pure Javascript without jQuery. -
How can I differentiate between users with lookup
I have two classes Customer and Restaurant that have OneToOneField with the django built in User. When I go to a page I am trying to determine which User it is. What I am doing doesnt work because the User model will always return True for having a restaurant attribute, so it never makes it past the first if statement... models.py class Restaurant(models.Model): restaurant_user = models.OneToOneField(User, on_delete=models.CASCADE) restaurant_name = models.TextField(max_length=50) about = models.CharField(max_length=500) class Customer(models.Model): customer_user = models.OneToOneField(User, on_delete=models.CASCADE) about = models.CharField(max_length=500) views.py def dashboard(request): if User.restaurant: return render(request,'usermanage/dashboard_restaurant.html') elif User.customer is not None: return redirect(request, 'usermanage/dashboard.html') else: return render(request, 'usermanage/dashboard.html') -
multiprocessing django model database
My database in the implementation of this script, the database has lost data, may be more or less, there will be a lot of empty data. thank you The following list of configuration information: Sqlite3 Django1.9.8 Python 2.7.6 def flush_price(): logging.error("Sub-process(es) begin.") logging.error(int(time.time())) key = '2500_wine_info.xlsx' lists = import_excel(key) lwin11s = [] for item in lists: lwin11s.append(str(item['LWIN11'])[:11]) contracts = Contract.objects.filter( is_del=False, wine__lwin11__in=lwin11s ) lwins = [] for contract in contracts: lwins.append(str(contract.wine.lwin)) new_arrs = arr_split(lwins, 50) now = conversion_reduce_8_time() for index in range(1, 3641): date_now = (now - datetime.timedelta(days=index)).strftime('%Y-%m-%d') pool = multiprocessing.Pool(processes=len(new_arrs)) for new_arr in new_arrs: pool.apply_async(request_price, (new_arr, date_now, )) pool.close() pool.join() break logging.error(int(time.time())) logging.error("Sub-process(es) done.") def request_price(new_arr, date_now): headers = { 'CLIENT_KEY': CLIENT_KEY, 'CLIENT_SECRET': CLIENT_SECRET, 'ACCEPT': 'application/json', 'CONTENT-TYPE': 'application/json', } data = { 'lwin': new_arr, 'priceType': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'], "currency": "EUR", "priceDate": date_now, } price_obj = download_page(VINEX_PRICE_API, request_type=1, data=json.dumps(data), headers=headers) if price_obj.status_code == 200: price_obj = price_obj.json() if price_obj['httpCode'] == '200': lwin_details = price_obj['lwinDetail'] for lwin_detail in lwin_details: # 取得参数 lwin = lwin_detail['lwin'] # 取得对象信息 contract = Contract.objects.filter(is_del=False, wine__lwin=lwin).first() wine = contract.wine # 设置历史数据更新 RedWinePriceData.objects.filter( is_del=False, contract=contract, lwin=lwin, ).first() redwinepricedata = RedWinePriceData() redwinepricedata.contract = contract redwinepricedata.lwin = lwin # 改变数据 redwinepricedata.priceDate = … -
Django 's models and mysql table
#if Milestone.objects.filter(milestone__in=self.milestone_map[self.proj_type]).count() != len(self.milestone_map[self.proj_type]) hello,everybody! Background:django 1.4 with python 2.7,Milestone is a mysql table __in What does it mean? -
Django : Emails never sent
I am trying to debug email sending locally in my project but emails are never sent. My config is : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending e-mail. EMAIL_HOST = 'localhost' # Port for sending e-mail. EMAIL_PORT = 1025 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False And then I wrote a test that does : subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, ["test9823982938@yopmail.com"]) msg.attach_alternative(html_content, "text/html") msg.send() And I try to see it with : python -m smtpd -n -c DebuggingServer localhost:1025 But nothing ever appears. I tried different values for EMAIL_BACKEND but nothing ever works. What am I missing ? -
Leer archivo SentiWordNet_3.0.0_20130122.txt en menor tiempo usando Django
Tengo una libreria llamada SentiWordNet, esta tiene mas de 117,000 lineas. Al tener un texto, voy tomando cada palabra y la busco en SentiWordNet.txt de una por una con el siguiente codigo: for pal in filtro: archivo = open("SentiWordNet_3.0.0_20130122.txt") for linea in archivo: if not linea.startswith("#"): columna = linea.split("\t") palabra_senti = columna[4].split(" ") palabras = [w.split("#")[0] for w in palabra_senti] if pal in palabras: elemento = elemento + 1 positivo = columna[2] negativo = columna[3] resultado_diferencia = (float(columna[2]) + float(columna[3])) parcial = parcial + resultado_diferencia resultado_palabra = float(resultado_diferencia)/ float(elemento) if not pal in palabras_encontradas: palabras_encontradas.append(pal) El problema es que para hacer un analisis a un texto de 500 palabras tarda casi 2 minutos en analizarlo por completo y al querer hacer el mismo analisis en Heroku me sale el siguiente mensaje despues de un minuto: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. Con textos menores a 300 lineas si hace el analisis correctamente. Existe alguna forma de hacer el codigo mas eficiente? Sera mejor pasar el archivo txt de SentiWordNet a una base de datos e ir a cansultarla de la misma manera? … -
MultiValueDictKeyError when using DropzoneJS with Django
I'm currently making a profile picture feature for a website, I started using DropzoneJS but I'm having an issue submitting the file. The picture will drop into the zone fine, but it appears with an "X" over it, and when I hover over the picture I can see the MultiValueDictKeyError error. Which is the same error I get when I click the submit button without selecting a file. So I assume the issue is that the file isn't being submitted by the button? How do I do that? HTML/JS: <script type='text/javascript'> Dropzone.options.myDropzone = { init : function() { var submitButton = document.querySelector("#submitBtn") myDropzone = this; submitButton.addEventListener("click", function() { myDropzone.processQueue(); }); this.on("addedfile", function() { document.getElementById('submitBtn').style.visibility = "visible"; }); this.on('addedfile', function(){ if (this.files[1]!=null){ this.removeFile(this.files[0]); } }); } }; Dropzone.options.myAwesomeDropzone = { accept: function(file, done) { console.log("uploaded"); }, init: function() { this.on("addedfile", function() { if (this.files[1]!=null){ this.removeFile(this.files[0]); //document.getElementById('submitBtn').style.visibility = "visible"; } }); } }; </script> <!-- Modal --> <div id="picModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close"></span> <form action="{% url 'profile_test' %}" method='POST' enctype="multipart/form-data" class="dropzone" id="my-dropzone">{% csrf_token %} <button id='submitBtn' type='submit' style='visibility: hidden;'> Submit </button> <input id='submit-all' type='file' name='uploaded_image'/> {{form}} </form> </div> </div> </body> -
Connecting to stream
i am building a web app using Django that will use get-stream,i have tried this before using a tutorial, i got it working the first time earlier this year, now when i run any of my web apps (test and official) i get an error which i seem not to understand, the error seems to be about the API keys and they are correct and i have double checked them. i get this error running the server, making migrations and syncing databases. i followed the steps again and did not get any luck. Thank you in advance for your help. Screen shot of what i get -
How to place and order django objects from 2 models into template table?
I'm trying to place "information" into a table that has rows and columns called "categories" and "stylings". My model and view are shown below. model.py class Headings(models.Model): categories = models.CharField(max_length=20) stylings = models.CharField(max_length=20) class Information(models.Model): headings = models.ForeignKey(Headings) info = models.CharField(max_length=100) views.py class InformationListView(ListView): model = Information def get_context_data(self, **kwargs): context = super(InformationListView, self).get_context_data(**kwargs) context['categories_ordered'] = Headings.objects.order_by('categories') context['stylings_ordered'] = Headings.objects.order_by('stylings') return context So far I've been able to start my template table with <table> <tr> <th>Styles</th> {% for cols in categories_ordered %} <th class="rotate"><div><span>{{ cols.categories }}</span></div> {% endfor %} </th> </tr> {% for row in stylings_ordered %} <tr> <td>{{ row.stylings }}</td> {% for col in categories_ordered %} <td> ... need algorithm that places the correct info in this cell. {{ Information.info }} </td> {% endfor %} </tr> {% endfor %} </table> There could be 6 different categories and 6 different stylings, but maybe only 4 information objects. So the hard part (imo) is placing the information in the correct cell in the table. I've tried different things but nothing that seems to be close. I imagine this is a fairly common problem that is solved all the time. Thanks -
Node is not in primary or recovering state upon removal of instance from replication set
I currently have 4 mongo instances in a replication set, one of them is obsolete and needs to be removed, but when I run rs.remove("hostname") my django application instantly starts throwing Node is not in primary or recovering state upon removal of instance from replication set until I add the instance back in. This is my rs.status() rs_pimapi:PRIMARY> rs.status() { "set" : "rs_pimapi", "date" : ISODate("2017-07-28T01:27:05.607Z"), "myState" : 1, "term" : NumberLong(-1), "heartbeatIntervalMillis" : NumberLong(2000), "optimes" : { "lastCommittedOpTime" : { "ts" : Timestamp(1501205225, 1), "t" : NumberLong(-1) }, "appliedOpTime" : Timestamp(1501205225, 1), "durableOpTime" : Timestamp(1501205222, 1) }, "members" : [ { "_id" : 25, "name" : "10.231.158.108:27017", "health" : 1, "state" : 1, "stateStr" : "PRIMARY", "uptime" : 7212131, "optime" : Timestamp(1501205225, 1), "optimeDate" : ISODate("2017-07-28T01:27:05Z"), "electionTime" : Timestamp(1500629818, 1), "electionDate" : ISODate("2017-07-21T09:36:58Z"), "configVersion" : 278273, "self" : true }, { "_id" : 29, "name" : "10.0.1.95:27017", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "uptime" : 20216, "optime" : Timestamp(1501205222, 1), "optimeDurable" : Timestamp(1501205222, 1), "optimeDate" : ISODate("2017-07-28T01:27:02Z"), "optimeDurableDate" : ISODate("2017-07-28T01:27:02Z"), "lastHeartbeat" : ISODate("2017-07-28T01:27:04.286Z"), "lastHeartbeatRecv" : ISODate("2017-07-28T01:27:04.373Z"), "pingMs" : NumberLong(1), "syncingTo" : "10.231.158.108:27017", "configVersion" : 278273 }, { "_id" : 30, "name" : "10.0.0.213:27017", "health" : 1, … -
django password_reset can not submit form
I can not submit the forms if extends from top html,if i delete {% extends 'accounting/password_reset_base.html' %}, the form can submit and send email, please help to fix this, thanks {% extends 'accounting/password_reset_base.html' %} {% load static%} {% block headertitle_password %} Forgot Your Password ? {% endblock %} {% block passwordbase %} <div class="container"> <md-card> <div class="container_password"> <form method="post">{% csrf_token %} <div> <input id="id_email" maxlength="254" name="email" type="email" /> </div> <button type="submit" >Reset my password</button> </form> </div> </md-card> </div> {% endblock %} -
How to pass foreign key to serializer when creating parent at the same time?
Just to preface, I'm a beginner and I realise my conventions may not be exactly standard so I would be grateful if you would correct me for anything I'm doing completely wrong. Currently, my API is called using: http:127.0.0.1:8000/weather/<latitude>,<longitude> I am pulling weather data from some API, but also want to store it in a database at the same time. To represent the weather, I have two models, Location and Currently which hold the coordinates and weather information. In this case, the parent is Location. My issue is I don't know how to pass the Location foreign key to CurrentlySerializer. In the code below I'm not passing it in at all and I receive the obvious "location field is required" error. views.py def get(self, request, *args, **kwargs): # Process latitude and longitude coordinates from URL coordinates = kwargs.pop('location', None).split(",") latitude = coordinates[0] longitude = coordinates[1] # Retrieve weather data. forecast = get_weather(latitude, longitude) currently = forecast['currently'] # Serialize and confirm validity of data. location_serializer = LocationSerializer(data=forecast) if not location_serializer.is_valid(): return Response(location_serializer.errors, status=status.HTTP_400_BAD_REQUEST) currently_serializer = CurrentlySerializer(data=currently) if not currently_serializer.is_valid(): return Response(currently_serializer.errors, status=status.HTTP_400_BAD_REQUEST) response = location_serializer.data + currently_serializer.data return Response(response, status=status.HTTP_200_OK) models.py class Location(models.Model): ... some fields class DataPoint(models.Model): ... some fields … -
djstripe customers not deleted
I have a test website that will be using stripe and djstripe 0.8.0 for subscription payments. I had the test data set up to test the payments system was working. I then deleted the stripe test data. However, when I open the django admin console and navigate to djstripe > customers, I have the following records displayed, but no users/customers attached to them: There are no records in the corresponding database table. I have even deleted the customers from stripe and the database itself. Still cannot get rid of these records. If I try to access the records or delete the records from the admin console, I receive the following error message: AttributeError: 'NoneType' object has no attribute 'email' File "C:\Users\me\desktop\myappname\env3\lib\site-packages\djstripe\settings.py", line 94, in get_subscriber_model_check_subscriber_for_email_address(subscriber_model, "The customer user model must have an email attribute.") File "C:\Users\me\desktop\myappname\env3\lib\site-packages\djstripe\settings.py", line 70, in _check_subscriber_for_email_address if ("email" not in subscriber_model._meta.get_all_field_names()) and not has attr(subscriber_model, 'email'): AttributeError: 'Options' object has no attribute 'get_all_field_names' How do I delete these records? -
Websocket connection by Apache2 + mod_wsgi + Django
I am deploying a django project on apache2 using mod_wsgi. I can confirm to see Django's page from apache2 server but websocket cannot connect, I think that Django-channels doesn't start by apache2. So I solve this problem to install 'asgi_redis' to start Django-channels. 'pip3 instal asgi_redis' I changed channel layer. CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, "ROUTING": "mysite.routing.channel_routing", }, } And I tried the follow command. 'python3 manage.py runworker' But the following error occured. 2017-07-27 08:07:59,660 - INFO - runworker - Using single-threaded worker. 2017-07-27 08:07:59,661 - INFO - runworker - Running worker against channel layer default (asgi_redis.core.RedisChannelLayer) 2017-07-27 08:07:59,663 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/redis/connection.py", line 439, in connect sock = self._connect() File "/usr/local/lib/python3.5/dist-packages/redis/connection.py", line 494, in _connect raise err File "/usr/local/lib/python3.5/dist-packages/redis/connection.py", line 482, in _connect sock.connect(socket_address) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/redis/client.py", line 572, in execute_command connection.send_command(*args) File "/usr/local/lib/python3.5/dist-packages/redis/connection.py", line 563, in send_command self.send_packed_command(self.pack_command(*args)) File "/usr/local/lib/python3.5/dist-packages/redis/connection.py", line 538, in send_packed_command self.connect() File "/usr/local/lib/python3.5/dist-packages/redis/connection.py", line 442, in connect raise ConnectionError(self._error_message(e)) redis.exceptions.ConnectionError: Error 111 connecting … -
How to read Jinja from a model in Django?
I want to store small Django templates in a database and include them in my view. What I need to do is call something like <ul> {% for each item in foo.items.all %} <li>{{ item.snippit }}</li> %} </ul> Where snippet is a string like this product is made from {{ bar.percent }} &percnt; recycled materials I need to know how I would go about rendering this text as Jinja before sending it to the client -
MultiValueField does not work with ModelChoiceField
The code: (where AddressInput is a MultiWidget) class AddressFormField(MultiValueField): widget = AddressInput def __init__(self, queryset, empty_label="---------", to_field_name=None, limit_choices_to=None, *args, **kwargs): fields = ( ModelChoiceField(queryset, empty_label=empty_label, to_field_name=to_field_name, limit_choices_to=limit_choices_to, *args, **kwargs), CharField() ) super().__init__(fields=fields, require_all_fields=False, *args, **kwargs) #self.widget.choices = self.fields[0].widget.choices #### if not commented out, I get another error: AttributeError: 'RelatedFieldWidgetWrapper' object has no attribute 'decompress' def compress(self, data_list): if not data_list[1]: return None if not data_list[0]: raise ValidationError('Invalid address') return data_list[0] class AddressForeignKey(ForeignKey): def formfield(self, **kwargs): # This is a fairly standard way to set up some defaults # while letting the caller override them. defaults = {'form_class': AddressFormField} defaults.update(kwargs) return super().formfield(**defaults) I get this error: AttributeError: 'AddressInput' object has no attribute 'choices' Because ModelChoiceField did not declare it. Passing the widget to ModelChoiceField does not work as it makes a copy if it's an instance. Thus I set the choices attribute manually as you can see in the commented out code. But then I got another error which I didn't resolve: AttributeError: 'RelatedFieldWidgetWrapper' object has no attribute 'decompress' -
short polling versus websockets for short duration requests
So we have a Django backend server that communicates with a large number of 3rd party servers. These 3rd party servers all use socket connections for communication, not HTTP. Each user request to our service will communicate (over a socket) with one of many possible 3rd party servers. Each 3rd party server can take 1-20 seconds to respond, although usually it is around 1-5 seconds. Of course when a user goes to our webpage to make a request for one of those 3rd party services, we want to respond to our user as quickly as possible, ie don't block on our server waiting for a response. When the 3rd party server responds, then we want to push the response back to the user's browser. Certainly this is a common problem. But the key here is that we will be issuing requests to our web server every 5 seconds or so (e.g. using JavaScript/AJAX in our web pages). I understand that if we were able to create a websocket connection for the response and leave it open, and/or if our requests were really long duration (say >30 seconds), then websockets would be a good way to go for server push. However, … -
Class Variables vs Methods in Django Class Based Views
I am a self-taught amateur ever trying to understand fundamentals of Python, Django and programming in general. I'm looking to understand an issue I was having. So I have this class class ContractsView(InventoryView): template_name = "contracts.html" page = "Contracts" primary_table, secondary_table = build_contracts_tables(**{"commodity": None}) and it uses the following function: def build_contracts_tables(**kwargs): print('fire') primary_table_query = Purchase.inventory.current_contracts_totals(**kwargs) primary_table_fields = ("total_meats", "total_value", "meat_cost") primary_table_html = build_table([primary_table_query,], *primary_table_fields) if primary_table_query else err_str secondary_table_query = Purchase.inventory.current_contracts(**kwargs) secondary_table_fields = ("invoice", "supplier", "variety", "meats", "value", "meat_cost", "ship_date") secondary_table_html = build_table(secondary_table_query, *secondary_table_fields) if secondary_table_query else err_str return primary_table_html, secondary_table_html Somehow, the view is sending something to the template, as it does render some data. However, the data doesn't update right away (it eventually does), meaning I will refresh it after changes to the database, but old data will persist. Additionally, I don't ever see my print appear in the console. However, when I convert the class variables into functions, it works just fine: class ContractsView(InventoryView): template_name = "contracts.html" page = "Contracts" def primary_table(self): x,y = build_contracts_tables(**{"commodity": None}) return x def secondary_table(self): x, y = build_contracts_tables(**{"commodity": None}) return y Could someone help me understand the rule I am breaking in my original attempt? -
Django Rest Framework - return list of Users or single User with ModelViewSet based on Permissions
I have seen several posts similar to this question, but none that solve my issue. I am using Django Rest Framework's ModelViewSet. I have two views, a detail view and a list view. I want it so that if a superuser accesses my list view, he gets all the users. If a normal user accesses a list view, he can only see himself. If a superuser accesses the detail view, he can view any user. If a normal user accesses a detail view that is not his, he gets an authentication error. I first attempted this with permissions only, but realized that with a query set of all for the list view the has_object_permission is not run allowing an authenticated non-superuser to view everyone. This is because object permissions are only run with a get command. I attempted to only override get_object, but get_object is not called for the list view so it made no difference. So I tried to override get_quertyset without get_objects, but this broke my detail view. What I understand is that get_object is called first for a detail view, which then calls get_queryset if I don't override either of them. But if I override get_queryset, it … -
Django model foreign key in the same table
Before to send this kind of modification to my database, I just would like to know if what I do is OK or not. class Comments(models.Model): text = models.CharField(max_length=300, null=False) image = models.FileField(upload_to=user_directory_path_comments, validators=[validate_file_extension], blank=True, null=True) articles = models.ForeignKey(Articles, verbose_name="Article", null=False) author = models.ForeignKey(User, verbose_name="Auteur") in_answer_to = models.ForeignKey(Comments, verbose_name="En réponse au commentaire", blank=True, null=True) date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") def __str__(self): return self.text I have a model called Comments for listing the comments in my article's blog. I want to add the functionality to answer to a comment and so I add a field name where, if it's an answer, I add the ID of the comment. So, is it OK if I add a foreign key field, knowing that it's is about the same table ? This is not really a foreign key ? -
Django UpdateView form displaying in modal but not updating
So I have this update view: class UpdateRules(UpdateView): model = BlackList form_class = AddRules template_name= 'blacklist_form.html' success_url = reverse_lazy('posts:list') which displays this template blacklist_form.html: <form class="well contact-form" method="post" action=""> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">x</button> <h3>Editing Number</h3> </div> <div class="modal-body"> {% csrf_token %} {{form.as_p}} </div> <div class="modal-footer"> <input class="btn btn-primary" type="submit" value="Save" /> </div> </form> Then in the template where the modal is called/rendered I have this link for each object to be edited: <a class="contact" href="#" data-form="{% url 'posts:update_rules' obj.pk %}" title="Edit"> And this div to display the modal: <div class="modal" id="contactModal"> </div> Lastly, the jQuery: $(document).ready(function() { $(".contact").click(function(ev) { // for each edit contact url ev.preventDefault(); // prevent navigation var url = $(this).data("form"); // get the contact form url console.log(url); $("#contactModal").load(url, function() { // load the url into the modal $(this).modal('show'); // display the modal on url load }); return false; // prevent the click propagation }); $('.contact-form').on('submit',function() { $.ajax({ type: $(this).attr('method'), url: this.action, data: $(this).serialize(), context: this, success: function(data, status) { $('#contactModal').html(data); } }); return false; }); }); My problem is this: I'm able to get the update view form to display in the modal when I click the edit link for each object, but the submit … -
Making an instance that puts two instances from different models together
I'm trying to populate a model with two other instances from different models. It's hard to explain, so I'll show you with my code: models.py class StudentCourse(models.Model): student = models.ForeignKey(Student) course = models.ForeignKey(Course) tables.py class StudentCourseTable(tables.Table): selection = tables.CheckBoxColumn(empty_values=(), orderable=False) def render_selection(self, record): return format_html('<input type="checkbox", name="selection", class="course_check", value={} />', record.title) class Meta: model = Course fields = ('selection', 'title') attrs = {'class': 'table table-hover', 'id': 'student'} views.py def add_StudentCourse(request): context_dict = {} course_list = Course.objects.filter(status=True) table = StudentCourseTable(course_list) context_dict['table'] = table return render(request, 'students/add_studentcourse.html', context_dict) add_studentcourse.html <div class="box box-primary"> <form> {% if table %} {% render_table table %} {% endif %} </form> </div> template pic What I want to do is create a button that when the checkboxes are checked beside a course and the button is pressed, instances that match up the id of the current student (in the url, this page is only accessed once a new student is created) and the id of the courses that have a checkbox marked will be created in the StudentCourse model. Each instance only has one of each, and there's no limit to how many instances are created during one button press. And presumably I don't need a form. I … -
Django REST to React - getting social auth tokens without password
I want to pass info to React about the current authenticated user within an app that only uses social authentication on the backend (that is processed by social_django). All of my user and user token info is stored within django REST, and to access the tokens, I normally have to send POST requests to rest_framework.authtoken's obtain_auth_token view. My django root urls.py file looks like: ... from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ ... url(r'^obtain-auth-token/$', obtain_auth_token), ... ] However, in order to actually get the auth tokens associated with the users in my database, I need to supply the username and password within my POST request. Social authentication automatically creates new users without assigning any passwords, so how do I get those tokens? -
How can I create a django application that can run anaconda code?
I recently have tried working with django by going through the django documentation and ran into several problems. First, I uploaded the django package using anaconda navigator. Then, I tried creating a django project within a directory inside an anaconda environment, but got an error telling me that the project already exists elsewhere. So, I instead searched for the specific files and placed it into a file and ran the server command, but couldn't do to an error saying that it could not find the module named '{{project_name}}'. So, I am wondering how I can retry the whole process and fix the errors that have stopped me from starting a project. I already tried to get an answer here: What is the easiest way to start a Django project within an anaconda environment?