Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get unique values in django
i have a category model and list of posts related to those category also some post with same category name but when i wanted to make list of category section, it showing duplicate name of category as it related to posts like: food, food, desert, style, desert, but i want like: food, desert, style, here is my code... Thank you so much! views.py class ListCategory(ListView): model = Post paginate_by = 2 template_name = 'shit.html' context_object_name = 'queryset' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) cate = Post.objects.all() context['cate'] = cate return context models.py class Category(models.Model): title = models.CharField(max_length=20) thumbnail = models.ImageField() detail = models.TextField() featured = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-category', kwargs={ 'pk': self.pk }) class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() featured = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(Author,on_delete=models.CASCADE) thumbnail = models.ImageField() category = models.ForeignKey(Category, on_delete=models.CASCADE) tags = TaggableManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={ 'pk': self.pk }) templates {% extends "base.html" %} {% load static %} {% block content %} <div class="sidebar-box ftco-animate"> <ul class="categories"> <h3 class="heading mb-4">Categories</h3> {% for cat in cate %} <li><a href="{% url 'post-category' cat.category.pk %}">{{cat.category}}<span>(12) </span></a></li> {% endfor %} </ul> </div> {% endblock content %} -
displaying page with objects that may not exist?
So I have a page that is used to view an album page that also calls the artist id to display the associated artist of the album. In my database, 'Artist' and 'Band' are two different models. I am calling the artist id in this format : href="{% url 'artist_details' Artist_id=Album.Artist.id %}" So when loading an album page that does not contain an artist, but rather a band, is there a way to get around the NoReverseMatch error that happens due to there not being a valid artist id? (because it gets the band id instead) Thanks in advance -
Why are my models not showing up in django admin site?
I have made alot of models and forgot to register them when I made them, after I realized I didn't register them I went and registered them the usual way (shown below). I've deleted the database and all migrations (including __pycache__) but haven't deleted the __pycache__ in the inner project folder (that holds settings.py) because I don't know if that would cause problems or not. I've tried using admin.register(Comment,admin) but that didn't work and, as you know, isn't necessary. I'm not sure what other information I would need to give so please let me know what else you need to know. admin.register(PicturePost) admin.register(VideoPost) admin.register(TextPost) admin.register(Comment) admin.register(Report) I also have a function activated whenever a user is created to make a profile for them and that works for the superusers too. I don't think that would do anything to the superusers but I also don't know if that would somehow modify the permissions of the superuser so I figured I would provide that tidbit, here is the function. def create_profile(sender, **kwargs): user = kwargs['instance'] if user.is_staff: user.trust_level = 2 if kwargs['created']: user_profile = UserProfile( user=user, sex='Prefer Not To Say', age=0, relationship_stat='Prefer Not To Say', bio='my bio', location='', website='' ) user_profile.save() post_save.connect(create_profile, … -
How can I pass dynamic information from HTML to Django?
I am new to both HTML Django and I don't know the appropriate HTML terminology, so please bear with me. The relevant portion of the HTML file is this: <select id="getAlignment" value2="" onchange="location = this.value;"> <option value="">Select an alignment</option> {% for aln in some_Alignments %} {%if 'LSU' not in aln.name%} <option value2=getAlignment.value2 value="{% url 'alignments:detail' aln.name %}">{{ aln.name }}</option> {% endif %} {% endfor %} </select> The contents of value2 are assigned using Javascript: Vue.component('tree-menu', { delimiters: ['[[',']]'], template: '#tree-menu', props: [ 'nodes', 'label', 'depth', 'taxID' ], data() { return { showChildren: false } }, computed: { iconClasses() { return { 'fa-plus-square-o': !this.showChildren, 'fa-minus-square-o': this.showChildren } }, labelClasses() { return { 'has-children': this.nodes } }, indent() { return { transform: `translate(${this.depth * 50}px)` } } }, methods: { toggleChildren() { this.showChildren = !this.showChildren; // if (this.showChildren) { var button = document.getElementById("getAlignment"); var newValue = this.taxID button.setAttribute("value2", newValue); // } } } }); I would like to pass the contents of value2 to Django for use in selecting the appropriate url. The relevant Django url architecture is the following: from django.urls import include, path from . import views app_name = 'alignments' urlpatterns = [ path('', views.index, name='index'), path('rRNA/<str:name>/', views.rRNA, name='rRNA'), path('rProtein/<str:align_name>/', … -
How to show the list paragraphs that belong to the user's Company in the django admin form
I'm developing a project in Django. I have several registered companies, and all models are based on the company. #models.py class Company(models.Model): name = models.CharField(max_length=100) country = models.CharField(max_length=100) class XUser(User): phone = models.CharField(max_length=20, null=True, blank=True) card = models.CharField(max_length=20, null=False, blank=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.nombre class Book(models.Model): user = models.ForeignKey(XUser, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=30) class Paragraph(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) text = models.CharField(max_length=300) Now in my admin I define that every user can only see the books of his company. #admin.py @admin.register(Book) class BookAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) # return a filtered queryset return qs.filter(company=request.user.company) My question is this: When I try to create a Paragraph instance in the django management form, it shows me all the books and I want it to only show me the ones that belong to the user's Company. Any ideas? -
How can I say to Django I want a primary key to be filled by a foreign key?
I've got a class called Device which has the following properties: Device ----------- -idDevice -name -processor -vulnerable -infected and by DB normalization vulnerable and infected are not descriptive properties for the device itself, so they should be in another table ¿right? I know in MySQL it can be easily defined as: CREATE TABLE DEVICE( idDevice VARCHAR (20) NOT NULL, name VARCHAR (50) NOT NULL, processor VARCHAR (100) NOT NULL, PRIMARY KEY (idDevice) ); CREATE TABLE OTHERS_DEVICE( idDevice VARCHAR (20) NOT NULL, vulnerable BOOLEAN NOT NULL, infected BOOLEAN NOT NULL, PRIMARY KEY (idDevice) FOREIGN KEY (idDevice) REFERENCES DEVICE(idDevice) ); and it works! But in my Django models I've tryed something like this with no success: class Device(models.Model): idDevice = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=50) procssor = models.TextField() class Meta: ordering = ['idDevice'] def __str__(self): return self.idDevice class OthersDevice(models.Model): idDevice = models.CharField(max_length=20, primary_key=True) vulnerable = models.BooleanField() infected = models.BooleanField() idDevice = models.ForeignKey(Device, on_delete=models.CASCADE) class Meta: ordering = ['vulnerable', 'idDevice'] def __str__(self): return self.idDevice When making migrations I've got a message like: The field 'x' has been successfully added to 'table' when not refering the FK as the PK, but in this specific case console doesn't show this message. After reading Django documentation … -
OSError: [Errno 45] Operation not supported when collecting static using Django framework
Currently trying to setup a Django backend to connect a bootstrap theme. After moving files into a static folder. I am receiving errors when running the command: "python manage.py collectstatic" The error states: "OSError: [Errno 45] Operation not supported" The settings in settings.py are as follows: STATIC_ROOT= os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'btre/static')] -
Django Determine if Min is unique
class Score(models.Model): player = models.ForeignKey(User, verbose_name="Player", on_delete=models.CASCADE, null=True) strokes = models.IntegerField(blank=True, null=True) I'm having trouble using aggregation and annotation to accomplish the following with a set of Scores. Should I be using a different approach? For a set of Scores, find the minimum number of strokes, then determine if it is unique. For example, if I had a set of scores with the following stroke values: [4, 4, 4, 4, 5, 5] The minimum amount of strokes is 4, and 4 is NOT unique. [3, 4, 4, 4, 4, 5] The minimum amount of strokes is 3, and 3 is unique. -
how can i solve it please? [closed]
when i run python manage.py makemigrations , i face this Error : book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) ^ SyntaxError: invalid syntax how can i solve it ? from __future__ import unicode_literals from django.db import models import uuid # requierd for unique book instance from django.urls import reverse class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('Died', null=True, blank=True) def get_absolute_url(self): return '%s, %s' %(self.last_name, self.first_name) class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="unique ID for this particular book across" book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'No loan'), ('a', 'Available'), ('r', 'Reserved'), ) status = models.CharField(max_length=1, choices=LOAN_STATUS, blank=True, default='m', help_text='Book avaiable') class Meta: ordering = ["due_back"] def __str__(self): return '%s, (%s)' %(self.id, self.book.title) class Genre(models.Model): name= models.CharField(max_length=200, help_text=' Enter a book genre') def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) Author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text='Enter a brief description of the Book') isbn = models.CharField('ISBN', max_length=13, help_text='13 character <a href='# ') genre =models.ManyToManyField(Genre, help_text='Select a genre for this book') def__str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) -
Page not found (404) - No availability found matching the query
I'm getting a Page not found (404) on calling the Update and Delete views in my template. My models are in such a way that multiple Staff can have multiple Availability entries. So I created a view to list the availability entries of each staff and I thought it would make sense to use a URL pattern that uses both the staff's pk and the availability entry's pk in order to delete or update the specific availability entries of a staff. Example: To edit Staff #2's availability entry #4: http://127.0.0.1:8000/staff/2/availability/4/edit Any clue why I'm getting this error? I did some research and I'm wondering if I have to override the get_object method in the AvailabilityUpdateView and AvailabilityDeleteView? urls.py path('staff/availability/new/', views.AvailabilityCreateView.as_view(), name='availability_new'), path('staff/<int:pk>/availability/', views.AvailabilityListView.as_view(), name='availability_list'), path('staff/<int:pk>/availability/<int:pk_alt>/edit/', views.AvailabilityUpdateView.as_view(), name='availability_edit'), path('staff/<int:pk>/availability/<int:pk_alt>/delete/', views.AvailabilityDeleteView.as_view(), name='availability_delete'), Template <a href="{% url 'availability_edit' pk_alt=availability.pk pk=availability.staff.pk %}">Edit</a> | <a href="{% url 'availability_delete' pk_alt=availability.pk pk=availability.staff.pk %}">Delete</a> Views class AvailabilityUpdateView(UpdateView): template_name = 'crm/availability_form.html' form_class = AvailabilityForm model = Availability class AvailabilityDeleteView(UpdateView): template_name = 'crm/availability_confirm_delete.html' model = Availability success_url = reverse_lazy('staff_list') -
Unable to use RadioSelect buttons in Django to get an output
So I'm trying to basically create a site which takes in user input in form of RadiSelect buttons, and based on that button, a query has to be run on the database and results to be displayed. I am posting all the file sceenshots below: Models file Views file forms.py urls.py html file: html file Final output webpage being displayed if the person selects radio button of vendor 1, the output should be the money owed to vendor 1 by that user. I am unable to get where I am going wrong. Request you all to kindly help me out. -
Django - S3 - SQS Delivery Instead of Retrieving
I'm currently using Django with S3. When a new object is created a notification is sent through SQS.AWS documentation I'm receiving the notification by using boto3. Boto3 documentation.I can receive messages using the receive_message function, but I have to run the function every minute to see if new messages are available. Is there a way of getting the messages delivered automatically to my django app instead of having to retrieve them by continuously running a function every minute to see if there are new messages? Delivered instead of retrieved. -
Can I create a Django User Group from a CSV file?
I am creating a Django app using LDAP among other things. I am creating an admin view that will be based on an AD group. What I have so far: 1) A script that can pull AD group users/info and stores it in a CSV 2) A conditional in my view that changes what the user sees depending on whether or not they are in said group What I need: 1) A way to transfer that CSV data into a Django group so that new users will be added as an admin of the app once they are added to the AD group. Does anyone have experience with something like this? I honestly just have no idea where to start with this and just wanted to know if the capability exists period. -
Error while setting up Django. class 'werken' has no objects
`from django.shortcuts import render, redirect, get_object_or_404 from .models import Werken Create your views here. def home(request): werken = Werken.objects return render(request, 'werken/werken.html', {'werken': werken}) def detail(request, werken_id): werk = get_object_or_404(Werken, pk=werken_id) return render(request, 'werken/detail.html', {'werk': werk})`the error i have is: { "resource": "/c:/Users/jarmo/OneDrive/Bureaublad/project-challenge/portfolio-project/werken/views.py", "owner": "python", "code": "no-member", "severity": 8, "message": "Class 'Werken' has no 'objects' member", "source": "pylint", "startLineNumber": 7, "startColumn": 14, "endLineNumber": 7, "endColumn": 14 } the error -
Django get PK dynamically from views.py
I have a view that renders a comment form along with a template: views.py def news(request): if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = Article.objects.get(pk=2) print(comment.post) comment.author = request.user.username comment.save() return HttpResponseRedirect('') else: form = CommentForm() return render(request, '../templates/news.html', context={"form": form}) models.py class Comment(models.Model): post = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments', blank=True) author = models.TextField() text = models.TextField() def __str__(self): return self.text forms.py class CommentForm(ModelForm): class Meta: model = Comment fields = ('text',) In views.py, where comment.post is getting assigned to Article objects, I want the pk to be applied dynamically. I tried doing it in the templates, where putting {{ article.pk }} in the templates output the right pk for the Article object but I wasn't sure how I'd go about applying it to my form. The templates look simple: Article object, below it a comment form. The problem is simple, I want the news(request) function to dynamically apply the pk of the current Article object in order to make the comment go to the right post. -
Django webapp for Neo4jdata-exploration
I'm building a webapp with python (django) I would like to integrate one page allowing the user to explore the data in a neo4j like environment. Likely I imagine it to be a tabular view of a fixed cypher query on the right, the linked-data visualisation with the bubbles on the right. On the top a search field that can allow some filtering options on the query in real time both in the tabular view and the bubble view, possibly clicking on a bubble it would highlight the corresponding value in the tabular view. Do you think this is possible? Are there any examples I can take inspiration from online? Any opinion on your side before jumping straight into the development (I saw different libraries for the integration of neo4j in django, but I'm not sure which one is the best for me, some really just seem data querying - upload to/download from neo4j using django. I'm sorry if this is not totally clear, hope you will find the time to give me some of your precious advices. -
Django How to update model object fields from external api data
I have a script which runs on a scheduler to get data from an api which I then intend to use this data to update the current database model information. My model ShowInfo within main/models.py: from django.contrib.auth.models import User class ShowInfo(models.Model): title = models.CharField(max_length=50) latest_ep_num = models.FloatField() ld = models.BooleanField() sd = models.BooleanField() hd = models.BooleanField() fhd = models.BooleanField() following = models.ManyToManyField(User, related_name = 'following', blank=True) I managed to isolate the issue to this section of the script: else: #test if api fails for t in real_title: if t in data_title: #testing if the titles in the database and from the api match a = ShowInfo.objects.get(title=t) id = a.id b = next(item for item in show_list if item["title"] == t) a1 = ShowInfo(id = id, title = b["title"], latest_ep_num=b["latest_ep_num"], ld=b["ld"], sd=b["sd"],hd=b["hd"],fhd=b["fhd"]) a1.save() Some additional info about the lists (where show_list is a list of dictionaries gotten from an api): database = ShowInfo.objects.values() real_title = [] data_title = [] for show in show_list: real_title.append(show["title"]) for data in database: data_title.append(data["title"]) When the script runs I notice from browsing my database with DB Browser for SQLite that the objects were being inserted and not updating as i intended. The script is supposed to … -
How to stop AJAX function from running if form validation error
Submitting an video upload form via AJAX but the function continues to run if the form validation fails. To be more concise; the data success == True, but the form validation fails. $(document).ready(function(){ $(function () { var pleaseWait = $('#pleaseWaitDialog'); showPleaseWait = function () { pleaseWait.modal('show'); }; hidePleaseWait = function () { pleaseWait.modal('hide'); }; }); var $myForm = $('.form') $myForm.on('submit', function(event){ event.preventDefault(); var form = $(event.target) var formData = new FormData(form[4]); $.ajax({ xhr: function() { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { showPleaseWait(); // <--------------- This runs even when view returns error console.log('Percentage uploaded: ' + (e.loaded / e.total)) var percent = Math.round(e.loaded / e.total * 100); $('#progress-bar').attr('aria-valuenow', percent).css('width', percent + '%'); } }); return xhr; }, type: 'POST', url: form.attr('action'), enctype: 'multipart/form-data', processData: false, contentType: false, data: new FormData(this), success: function(data){ if (data.success) { window.location.href = data.url; } else if (data.error) { $("#top").html(data.error.title).addClass('form-field-error'); $("#div_id_title").removeClass('form-group'); } // <----------------- I want it to stop here }, error: function(xhr, status, error){ alert('err'); } }); }, ); }); How do I stop the function where the comment is? -
Extracting json dict from POST request
I want to make use of webhook provided by Townscript to update the is_paid field in my model. The format of the data is (a json dict):- link(Under server notification API column). A piece of useful information on the link was: We will send the data in following format using post parameter data. Here is the python code: def payment(request): if request.method == "POST": posts=request.POST["data"] result=json.dumps(posts) #converting incoming json dict to string paymentemail(result) # emailing myself the string (working fine) data = posts try: user = Profile.objects.filter(email=data['userEmailId']).first() user.is_paid = True user.save() except Exception as e: paymentemail(str(e)) # emailing myself the exception return redirect('/home') else: ....... The two emails correspoinding to the paymentemail() function in the above code were: "{\"customQuestion1\":\"+9175720*****\",\"customAnswer205634\":\"+917572******\", \"customQuestion2\":\"**** University\",\"customQuestion205636\":\"College Name\",\"ticketPrice\":**00.00, \"discountAmount\":0.00,\"uniqueOrderId\":\"***********\",\"userName\":\"********\", \"customQuestion205634\":\"Contact Number\",\"eventCode\":\"**********\",\"registrationTimestamp\":\"12-12-2019 22:22\", \"userEmailId\":\"***********@gmail.com\",etc....}" I understand that the backslashes are for escaping the quotation marks. Second email: (which is the exception) string indices must be integers Does that mean that data=request.POST['data'] gives me a string thus leading to an error when I use data['userEmailId']? How do I deal with this error? -
Django: How to change where staticfiles are stored?
I'm wanting to make it to where my staticfiles are stored in my project directory instead of my base directory when I run python manage.py collectstatic I want my base project directory to look like this: myproject/ app1 app2 app3 myproject/ staticfiles settings.py urls.py instead of this (normal version): myproject/ app1 app2 app3 myproject staticfiles I'm not totally sure how best to go about doing this. I've read the relevent docs and couldn't make sense of how to change where staticfiles are stored. Doc references: https://docs.djangoproject.com/en/3.0/howto/static-files/ https://docs.djangoproject.com/en/3.0/ref/settings/#static-files I've tried a couple of variations of my STATIC_ROOT setting: # version 1: STATIC_ROOT = os.path.join(BASE_DIR, "myproject/static") # version 2: STATIC_ROOT = os.path.join(BASE_DIR, "/myproject/static/") and neither of those worked to move where the staticfiles are stored. I would really appreciate some feedback on how to make this work. Thanks! -
Django sends TypeError: 'module' object is not iterable when adding Meta in Form
I've googled this error, but none of the answers I've seen seem to apply to my problem, which is this: I recently imported a Django project, and have been working on it, and it worked, until I was adding CRUD methods and views for a model. I added everything I needed, but when running the server, I got this error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\urls\resolvers.py", line 596, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'quiniela.urls' does not appear to have any … -
CSRF token missing or incorrect. Django + jQuery File Upload
I trying to implement jQuery File Upload on Django project. But every time I submit an image, an error has occurred: "CSRF verification failed. Request aborted." models.py class Photo(models.Model): title = models.CharField(max_length=255, blank=True) image = models.ImageField(upload_to='photos/') uploaded_at = models.DateTimeField(auto_now_add=True) main.js $(function () { /* 1. OPEN THE FILE EXPLORER WINDOW */ $(".js-upload-photos").click(function () { $("#image-upload").click(); }); /* 2. INITIALIZE THE FILE UPLOAD COMPONENT */ $("#image-upload").fileupload({ dataType: 'json', done: function (e, data) { /* 3. PROCESS THE RESPONSE FROM THE SERVER */ if (data.result.is_valid) { $("#gallery tbody").prepend( "<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>" ) } } }); }); template.html {# 1. BUTTON TO TRIGGER THE ACTION #} <button type="button" class="btn btn-primary js-upload-photos"> <span class="glyphicon glyphicon-cloud-upload"></span> Upload photos </button> {# 2. FILE INPUT TO BE USED BY THE PLUG-IN #} <input id="image-upload" type="file" name="file" multiple style="display: none;" data-url="{% url 'add_location_step_3_url' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"'> {# 3. DISPLAY THE UPLOADED PHOTOS #} {% for photo in photos %} <a href="{{ photo.file.url }}">{{ photo.file.name }} {% endfor %} -
I want to connect nginx and django on openshift
So I have an instance of nginx running on my openshift and another pod for a django app, the thing is I don't know how to connect both services. I'm able to access hte default url for nginx and the url for django. Both are working fine but I don't know how to connect both services. Is there a way to do it modifying the yaml of the services or the pods? I already try to build the container myself of nginx and is giving me permission issues, so I'm using a version of nginx thats comes preloaded in openshift. Any help would be greatly appreciated. thank you so much. -
Django create_superuser() missing 1 required positional argument: 'username'
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('user must have smartcard') if not username: raise ValueError('must have username') user = self.create_user( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin =True user.is_staff =True user.is_superuser=True user.save(using=self._db) return user class Account(AbstractBaseUser): username = models.CharField(max_length=100, unique=True) email = models.EmailField(verbose_name="email", max_length=30, unique=True) department = models.CharField(max_length=30, choices=DEPARTMENT) USERNAME_FIELD = 'email' REQUIRED_FIELD = ['username',] objects=MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True I just can't get what is wrong. While creating a superuser the prompt doesnt ask me for entering username I modified the settings.py file as well. Tried several times with various databases. I have also added the username in REQUIRED_FIELDS section. -
Django Pass id to URL after .exist query
i have created a view set where it carry out a check if the User has created the object or not, in case the object is not created it will redirect him to a form to fill it and if is exist it will redirect him to the next step. my current challenge is how to pass the id to the next view and set the foreign key based on it. models.py: class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( 'Startup Name' , max_length = 32 , null = False , blank = False ) class Startup_About ( models.Model ) : str_about = models.ForeignKey ( Startup , on_delete = models.CASCADE ) about = models.TextField ( 'About Startup' , max_length = 2000 , null = False , blank = False ) problem = models.TextField ( 'Problem/Opportunity' , max_length = 2000 , null = False , blank = False ) business_model = models.TextField ( 'Business Monitization Model' , max_length = 2000 , null = False ,blank = False ) offer = models.TextField ( 'Offer to Investors' , max_length = 2000 , null = False , blank = False ) def …