Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add an array based filed in django model
I'm making an app atm where I get dummy data from a json file. My filed in this file looks like this: { "model": "card.model", "pk": 2222, "fields": { "meal_1": 5555, "meal_2": 5556, "meals": "[5555, 5556]" } } { "model": "meal.model", "pk": 5555, "fields": { "name": "Pizza", "vagan": True } } { "model": "meal.model", "pk": 5556, "fields": { "name": "Sandwich", "vagan": False } } I have a Meal class that contains: name, photo, description. I have also Card class that gets info right from json file. class Card() { meal_1 = models.ForeignKey( Meal, related_name='meal_1" ) meal_2 = models.ForeignKey( Meal, related_name='meal_2" ) meals=[] ?? } How can I add an array field that will contain a reference to these meals. What I want to achieve is loop over this meals and place into django template. Now I do this by reference to each filed: instance.meal_1.name... etc. -
Getting AttributeError for django view
I get below error for my django view. Exception Type: AttributeError Exception Value: 'int' object has no attribute 'user' Exception Location: /home/djangox/work/proj1/proj1env/lib/python3.6/site-packages/django/contrib/auth/decorators.py in _wrapped_view, line 20 I use Django 2.2.6 with Python 3.6.8. The error code line is in check_timetable_timing_conflict view in line : student_conflict_message,conflict_student = check_student_timing_conflict(kurskod,kursgunu,kursbasla_time,kursbitis_time) The check_timetable_timing_conflict view is : @login_required(login_url='/accounts/login/') def check_timetable_timing_conflict(request): conflict = 0 if request.method == 'GET': kurskod = int(request.GET['kurskod']) kursgunu = request.GET['kursgunu'] kursbasla = request.GET['kursbasla'] kursbitis = request.GET['kursbitis'] kursbasla_list = kursbasla.split(':') kursbitis_list = kursbitis.split(':') kursbasla_time = kursbasla_list[0]+":"+kursbasla_list[1]+":00.000000" kursbitis_time = kursbitis_list[0]+":"+kursbitis_list[1]+":00.000000" # >>> Diğer kurslarla saat çakışması kontrolü. courseobj = Courses.objects.filter(coursecode=kurskod).values("coursecode","courseroom_id__code","courseroom_id__name", "uuid").first() ttobjectsall = TimeTable.objects.filter(crsdate=int(kursgunu), course_id__courseroom_id__code=courseobj['courseroom_id__code']) ttobjectsnoconflict = (TimeTable.objects.filter(crsdate=int(kursgunu), course_id__courseroom_id__code=courseobj['courseroom_id__code'], finish_hour__lte = kursbasla_time, ) | TimeTable.objects.filter(crsdate=int(kursgunu), course_id__courseroom_id__code=courseobj['courseroom_id__code'], start_hour__gte = kursbitis_time, )) ttobjects_conflict = ttobjectsall.exclude(pk__in=ttobjectsnoconflict) if ttobjects_conflict.count() > 0: conflict = 1 conflicts = [] conflicts.append(str(conflict)) conflicts.append("") if ttobjects_conflict.count() > 0: for obj in ttobjects_conflict: conflict_courseobj = Courses.objects.filter(coursecode=kurskod).values("courseroom_id__name").first() conflicts[1] = conflicts[1] + "<img src=\"/static/img/redarrow1010.png\" height=\"20\" width=\"20\">"+" Seçilen <b>[KRS-"+str(kurskod)+"]</b> kursu <b>[KRS-"+str(obj.course_id)+" >> "+str(obj.start_hour)+" <> "+str(obj.finish_hour)+"]</b> kursu ile çakışıyor. Derslik: <b>"+str(conflict_courseobj['courseroom_id__name'])+"</b>\n" # >>> Seçilen kurs öğretmenlerinin seçilen saatte başka ders çakışması var mı kontrolü. teacher_conflict_message,conflict_teacher = check_teacher_timing_conflict(kurskod,kursgunu,kursbasla_time,kursbitis_time) # >>> Seçilen kurs öğrencilerinin seçilen saatte başka ders çakışması var mı kontrolü. student_conflict_message,conflict_student = check_student_timing_conflict(kurskod,kursgunu,kursbasla_time,kursbitis_time) if conflict == 1 or … -
Model objects to be grouped by date field in another model
I had two models, one called reviews and the other called answers, as you can see from its names, one review has many answers ( exactly 7) a classic one to many relationship. I'm able to do all the common stuff with this straight forward relationship, filtering, prefech_related, even prefetching only some answers with a condition. Now, I want to do a group by review date with the answers objects in that day, as you can see, my problem is how I can do that because I will group many objects with just one field, the normal aggregate in Django are just sum and count, but I want the objects I was searching for a while about this and I can't see a solution where this can be done with orm to produce a queryset then serialize it or in SQL Thank you -
Django: Creating a variable in the template depending on the current request.path (without using {% with %})
I'm trying to add pagination to my first Django project and I'm struggling to wrap my head around something. Say I pass in the context as a dictionary e.g. bugs = { 'critical': <QUERY TO BRING BACK CRITICAL>, ... 'all': <QUERY TO BRING BACK ALL> } context = { 'bugs': bugs, } Then inside of my template: {% if request.path == '/bugs/critical' %} {% if bugs.critical.paginator.count >= 5 %} {% if bugs.critical.has_previous %} do something {% endif %} {% endif %} {% elif request.path == '/bugs/all' %} {% if bugs.all.paginator.count >= 5 %} {% if bugs.all.has_previous %} do something {% endif %} {% endif %} {% endif %} I have something like this, but with more than just critical and all, and I want to how I can condense down my code so I only have one pagination to update, and the bugs.all or bugs.critical is like a template variable depending on path? I tried this by doing: {% if request.path == '/bugs/critical' %} {% with key='critical' %}{% endwith %} {% endif %} But it seems to use the with to set variables, it has to be done within the with block, meaning I'd still have to use the same … -
How to load up all the CV information trough one model CV which inherits info from other models in django
Im working on a job portal website with django. What I did: I created a user With that user I created studentprofile and a cv where I added several educations, experience and skillsets. What do I want to do? I want to load up all my CV details(educations,skillsets,experience) which I added in the CV in one method to display it trough my studentprofile.html. I also cannot match my AbstractUser id with my customUser Studentprofile. Each time when I go to AbstractUser id-2, it gives me studentprofile id which is not matching. However if I can get solution with the first problem I will be very happy :) Thanks in advance I made those models. CV inherits all the subclasses My view at the moment: enter code here Method to call information out of the db and render it for the html def student_profile_view(request, id): user = User.objects.get(pk=id) student = StudentProfile.objects.get(id=4) education = Education.objects.get(id=2) experience = Experience.objects.get(id=2) skillset = SkillSet.objects.get(id=2) context = { 'user': user, 'student': student, 'education': education, 'experience': experience, 'skillset': skillset } return render(request, 'jobportal/account/student_profile.html', context, { }) -
django migrate subquery returned more than 1 value
I'm using Django and SQL Server to create a simple django model as: from django.db import migrations, models class Migration(migrations.Migration): initial = False dependencies = [ ] operations = [ migrations.CreateModel( name='Person', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=40)), ('last_name', models.CharField(max_length=40)), ], options={ 'db_table': 'api].[persons', 'managed': False, }, ), ] Now when i try to run migration using migrate command, I'm getting error as: Traceback (most recent call last): File "C:\Python3\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) File "C:\Python3\lib\site-packages\sql_server\pyodbc\base.py", line 547, in execute return self.cursor.execute(sql, params) pyodbc.Error: ('21000', '[21000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. (512) (SQLExecDirectW); [21000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The statement has been terminated. (3621)') This is what my Database settings look like: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'Myname', 'HOST': myhost, 'USER': 'user', 'PASSWORD': 'pass', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'unicode_results': True, } }, 'test': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'name', 'HOST': 'host2', 'USER': 'test_user', 'PASSWORD': 'test_pass', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'unicode_results': True, … -
Django file input from Forms not reaching model
I am a noob in django and am not able to figure out the issue in my code. Basically I am trying to upload some images to my server using a form. Whenever I save the form, it is only taking the default image specified in my model, not the images I uploaded in my form. print(request.Files) before calling form.is_valid() is giving output as: <MultiValueDict: {'id_image01': [<InMemoryUploadedFile: image01.jpg (image/jpeg)>], 'id_image02': [<InMemoryUploadedFile: image02.jpg (image/jpeg)>], 'id_image03': [<InMemoryUploadedFile: image04.jpg (image/jpeg)>], 'id_image04': [<InMemoryUploadedFile: image07.jpg (image/jpeg)>]}> which I presume says that the image is correctly loaded in the memory. My code goes like this: views.py def create_puzzle(request): if request.method == 'POST': print(request.FILES) form = DocumentForm(request.POST, request.FILES) if form.is_valid(): puzzleImages= form.save(commit=False) puzzleImages.username= request.user.username puzzleImages.save() return redirect('/puzzle/index.html') else: form = DocumentForm() return render(request, 'puzzle/create_puzzle.html', { 'form': form }) my Forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('birthday_message', 'video_url', 'image01', 'image02', 'image03','image04', 'image05', 'image06', 'image07', 'image08', 'image09', 'image10') captcha = ReCaptchaField( public_key='###########', private_key='###########', ) my models.py class Document(models.Model): description = models.CharField(max_length=255, blank=True) image01 = models.ImageField(default='default/image01.png', upload_to=user_directory_path) image02 = models.ImageField(default='default/image02.png', upload_to=user_directory_path) image03 = models.ImageField(default='default/image03.png', upload_to=user_directory_path) image04 = models.ImageField(default='default/image04.png', upload_to=user_directory_path) image05 = models.ImageField(default='default/image05.png', upload_to=user_directory_path) image06 = models.ImageField(default='default/image06.png', upload_to=user_directory_path) image07 = models.ImageField(default='default/image07.png', upload_to=user_directory_path) image08 = models.ImageField(default='default/image08.png', upload_to=user_directory_path) image09 … -
Django Query to get count of all distinct values for column of ArrayField
What is the most efficient way to count all distinct values for column of ArrayField. Let's suppose I have a model with the name MyModel and cities field which is postgres.ArrayField. #models.py class MyModel(models.Model): .... cities = ArrayField(models.TextField(blank=True),blank=True,null=True,default=list) ### ['mumbai','london'] and let's suppose our MyModel has the following 3 objects with cities field value as follow. 1. ['london','newyork'] 2. ['mumbai'] 3. ['london','chennai','mumbai'] Doing a count on distinct values for cities field does on the entire list instead of doing on each element. ## Query MyModel.objects.values('cities').annotate(Count('id')).order_by().filter(id__count__gt=0) Here I would like to count distinct values for cities field on each element of the list of cities field.which should give the following final output. [{'london':2},{'newyork':1},{'chennai':1},{'mumbai':2}] -
django-rest-auth registration with username and email, but making email for login alone
I am trying to create users asking for username and email, but using only the email to authenticate users with Django-rest-auth, the email is key as it will be used to log in to the user. but the username also has its importance in my app as when searching up a user, I would want to do something like this "accounts//". in trying to do this I have added a backend. please, what can I do, so when signing up I can input my username and email? backend.py class EmailAndUsernameBackend(ModelBackend): """ this model backend would help me use both username and email, remember to overide your AUTHENTICATION_BACKENDS to this one """ def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: user = UserModel.objects.get(Q(email=username) | Q(username=username)) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user in my settings.py, apart from my installed apps and the authentication backends, i have: AUTHENTICATION_BACKENDS = ( # 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', 'core.backends.EmailAndUsernameBackend', ) # to use old_password when setting a new password OLD_PASSWORD_FIELD_ENABLED = True LOGOUT_ON_PASSWORD_CHANGE = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_EMAIL_FIELD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = … -
How to create more then one prefetch_related (alias) for the same relation?
I have three models Feature, Product and FeatureProduct: class Feature(BaseModel): title = models.CharField(verbose_name='Имя характеристики', max_length=64, null=True, blank=True) image = models.FileField() ... class Product(BaseLedModel): ... class FeatureProduct(BaseModel): feature = models.ForeignKey(Feature, on_delete=models.CASCADE, related_name='feature_products') product = models.ForeignKey(LedProduct, on_delete=models.CASCADE, related_name='feature_products') value = models.CharField(verbose_name='Значение', max_length=64, null=True, blank=True) ... What I want to do: Product.objects.prefetch_related( Prefetch( 'feature_products', FeatureProduct.objects.filter(feature__visible_at_store=True) ), Prefetch( 'feature_products', FeatureProduct.objects.filter(feature__image__isnull=False, value__isnull=True) ) ) Of course I can't use "feature_products" two times in prefetch_related, but what would be the best way to achieve this? I haven't manage to find and information about posibility using alias for prefetch_related. My final goal is just to loop over products and features: for products in products: for feature_product in products.feature_products_alias1.all(): .... for feature_product in products.feature_products_alias2.all(): .... -
Show already selected item in dropdown in django template
Hi I have a dropdown like this <select name="category" data-placeholder="select Category here" multiple class="chosen-select" tabindex="8" required> <option value=""></option> <option>Transport</option> <option>Accommodation</option> <option>Ware House</option> <option>Readymade</option> </select> And I am getting selected element of this dropdown from database Filter query like this categories=Categories.objects.filter(vendor=uid) when I for loop like this {% for category in categories %} <option value=""></option> <option value="{{ category.category }}"{% if category.category == 'Transport' %}selected{% endif %}>Transport</option> <option value="{{ category.category }}"{% if category.category == 'Accommodation' %}selected{% endif %}>Accommodation</option> <option value="{{ category.category }}"{% if category.category == 'Activity' %}selected{% endif %} >Activity</option> <option value="{{ category.category }}"{% if category.category == 'Readymade' %}selected{% endif %}>Pre Packaged Plan</option> </option> {% endfor %} In this case For example If I have 2 options selected in database then it prints Options two time but seleted result is correct. Any help would be highly appreciated thanks. -
How do I prevent my javascript code from zooming in when I scroll up?
you can find the code here. Unfortunately I didnt write it but I think that it's going to be amazing for my company when I figure out how to use it. All I want is for the program to stop zooming in when I try to scroll up but, being green here with javascript, every time I make a change to the code the whole program crashed. If you need to beautify the code you can copy it and paste it here. Here is the manual for the project. -
Converting Image uploaded from html page to numpy array without saving it in Django Webapp
I want to make a Webapp where I can show prediction of my keras model on html page i.e such webapp where user will upload some image and my model will make prediction of what that image belongs to and show the output on html page. For this I am taking image as input from form but after that I don't want to save the image but directly convert that image to numpy array with some resizing so that I can feed that numpy array to my model.predict() function and get the output. How to do it without saving the image ? -
'save() prohibited to prevent data loss due to unsaved related object' even when parent object is saved
Having issues with saving an object to DB. I read other similar posts and still can't understand why it fails because I do save the Monitor object before saving State. What am I missing here? monitor = Monitors( hostname=form['hostname'], type = form['type'], interval = form['interval'], ftt = form['ftt'], alert_type = form['alert_type'], alert_enabled = form['alert_enabled'], params = params) try: monitor.save() state = States(monitor=monitor, state=2) state.save() except Exception as err: return render(request, 'error.html', {'error': err}) -
Read and Create HashTags
I will use Python to create an app to read some files and display the content implementing some especific rules. Do you know any libraries that do this? -
Properly print html pages to pdf
I have a html page that contains a bootstrap container and responsive images. When it rendered in browser, I want the user have the option to print the page and get a well rendered PDF. However, some images are being splatted in page transitions. Images are in thumbnail classes. {% forloop ----- %} <div class="thumbnail"> <img class="ImageShot" src="{{i.HQ_image.url}}"> </div> {% endfor %} -
architecture choice for dashboard
I'd like to develop a web dashboard for a dmp. What is the most widely used and/or most effective language-framework to use for this kind of website? The key points are: In this moment the database is quite small: the output from the cloud engine consists of 3 tables of 500-100-20mb but in the future it might become bigger I'll develop the first part of the architecture, others in the future might add some blocks (that's why I need a popular architecture). I'd like to deploy some tensorflow (or sklearn) models that work in real time. The database will be updated on monthly basis. I was thinking about node.js or django+highcharts but I'm not sure at all. I know that this question is somehow generalist but any reply could help make up my mind. Thanks! -
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.