Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Message doesn't close
I'm making a website and when I give invalid input to my login & register pages (or any other), an error message pops up, however when I click on the '⨯', I can't close it. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ main.html: <html lang="en"> {% load static %} <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Favicon --> <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" /> <!-- Icon - IconMonster --> <link rel="stylesheet" href="https://cdn.iconmonstr.com/1.3.0/css/iconmonstr-iconic-font.min.css" /> <!-- Mumble UI --> <link rel="stylesheet" href="{% static 'uikit/styles/uikit.css' %}" /> <!-- Dev Search UI --> <link rel="stylesheet" href="{% static 'styles/app.css' %}" /> <title>DevSearch - Connect with Developers!</title> </head> <body> {% include 'navbar.html' %} <!-- {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} --> {% for message in messages %} <div style="display: flex; justify-content: center;"> <div class="alert alert--{{message.tags}}"> <p class="alert__message">{{message}}</p> <button class="alert__close">⨯</button> </div> </div> {% endfor %} {% block content %} {% endblock content %} </body> <script src="{% static 'uikit/app.js' %}"></script> </html> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ JavaScript: // Invoke Functions Call on Document Loaded document.addEventListener('DOMContentLoaded', function () { hljs.highlightAll(); }); let alertWrapper = document.querySelector('.alert') let alertClose … -
How to have a Python Django map with a satellite view using from django.contrib.gis.db import models?
I know python and I know a bit of Django. Lately I have been trying to upgrade my maps that I use in my app to a satellite view. Right on my map I am able to draw multiple polygons and save it to the database (postGres). I am using the following to draw the map: from django.contrib.gis.db import models ... ... myMap = models.MultiPolygonField(verbose_name="Boundaries Map", null=True, blank=True, srid=4326) The only thing I wanted to do is instead of having the map View have a Satellite view. Does anyone know any way of doing it? -
RelatedObjectDoesNotExist?
can someone help me to understand want seam to be the problem I Create a model in a e-comers website. models: class Customer (models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(null=True, max_length=200) email = models.CharField(null=True, max_length=200) def __str__(self): return self.name then in views i add it to the cart: def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] context = {'items': items} return render(request, 'ecomeres/cart.html', context) -
Django Templates vs React - Already started down the templates route
I'm currently in the process of learning Django to make a web application for my workplace. I initially had the thought of just learning Django first to get the hang of it, then once I had the core logic in place I would then move over to a React for the UI (also need to learn how to use React), instead of templates. I'm now at the point where I could switch, but I've now only just discovered that I should be developing the backend with the Django REST framework to provide APIs for React (and other front ends). Is this something I can easily transfer to? Or is there a way to use React with my existing Django setup? I'm on a slightly tight timeframe and don't exactly need the core features of React right now. Is it better to get the main web application online sooner with Templates (continuing development down that route) or transition now to React and the REST API and finish the rest of the features after? Will it become too big of a task down the track to transition? -
Override create() method in ModelSerilizer and get object by ID (Django 3.2)
Main Model class Main(models.Model): title = models.CharField(max_length=255) event = models.ForeignKey('Event', null=True, on_delete=models.CASCADE) Event Model class Event(models.Model): day = models.DateField(u'Day of the event', help_text=u'Day of the event', null=True) JSON Structure example: { "titre": "main", "event": { "id": 13, #can't filter or get object by id "day": "2022-01-30", } } Override create() in Serializer: class MainSerializer(serializers.ModelSerializer): event = EventSerializer() class Meta: model = Main fields = '__all__' def create(self, validated_data): event_data = validated_data.pop('event') event = Event.objects.get(id=event_data['id']) main = Main.objects.create(event=event, **validated_data) return main So I encounter an error "KeyError id" and I can't add the object. -
How to make graphql query that can find "latest" or "min" or "max"
I'm trying to use graphql with python to retrieve the latest item added to a temperature table. The temperature table has 2 columns: timestamp and value. My models.py is: from django.db import models class Temperature(models.Model): timestamp = models.DateTimeField(auto_now=True) value = models.FloatField() def __str__(self): return f"the value:time is {self.value}:{self.timestamp}" and schema.py is: import graphene from graphene_django import DjangoObjectType from temperature import models class Temperature(DjangoObjectType): class Meta: model = models.Temperature class Query(graphene.ObjectType): temperature = graphene.Field(Temperature, id=graphene.Int()) def resolve_temperature(self, info, **kwargs): id = kwargs.get("id") if id is not None: return models.Temperature.objects.get(pk=id) return None schema = graphene.Schema(query=Query) I want to make one query thatt returns the latest temperature added, like this: query { currentTemperature { timestamp value } } And another query that returns the min and max temperatures over a timespan, like this: query { temperatureStatistics(after: "2020-12-06T12:00:00+00:00", before: "2020-12-07T12:00:00+00:00") { min max } } I am having a lot of trouble finding documentation on how to accomplish this. I've looked at these graphql docs and this stackoverflow post. I've looked at other things as well but these are the only things that came close to helping. -
Using graphene-django to get "max" from DB
How do you implement an SQL "max" equivalent with graphql? The query should return the object from the database with the max value in a certain column. I have tried things like this from this stackoverflow post with no success: query { table_name(limit: 1, order_by: {time: desc}) { data time } } Where is tells me: { "errors": [ { "message": "Unknown argument \"limit\" on field \"table_name\" of type \"Query\".", "locations": [ { "line": 2, "column": 15 } ] }, { "message": "Unknown argument \"order_by\" on field \"table_name\" of type \"Query\".", "locations": [ { "line": 2, "column": 25 } ] } ] } I have also looked at these graphql docs that didn't tell me anything. Am I supposed to implement this in the schema.py file with a resolver? -
How To Create Model Django For Fixed Question And Integrated with user document?
I have three user in my app. AUTHOR REVIEWER ADMINISTRATOR The flow in app like this: AUTHOR input data document data document will receive by REVIEWER and then he will review that document. REVIEWER will do review with answer five fixed question provided by ADMINISTRATOR. My question is how to create models? I have tried created models like this : models.py from django.db import models from django.conf import settings from dashboard.models import UserUsulan class Question(models.Model): question = models.TextField() def __str__(self): return str(self.question) class Review(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) usulan = models.ForeignKey(UserUsulan, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.BooleanField(default=False) def __str__(self): return str(self.usulan) And then i'm confused. How To Show The Reviewer Question to Template. Please help, your answer very precious to me. Thanks -
Django does not save the form (nothing happens)
\\models.py class BasicSettings(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) settings_description = models.BooleanField(default=False) settings_photo = models.BooleanField(default=False) settings_username = models.BooleanField(default=False) settings_background = models.BooleanField(default=False) \\views.py try: basic_settings = request.user.basicsettings except BasicSettings.DoesNotExist: basic_settings = BasicSettings(user=request.user) if request.method == 'POST': basicsettings_form = BasicSettingsForm( request.POST, instance=basic_settings) else: basicsettings_form = BasicSettingsForm(instance=basic_settings) return render(request, 'dashboard.html', {'basicsettings_form': basicsettings_form}) \\forms.py class BasicSettingsForm(forms.ModelForm): class Meta: model = BasicSettings fields = ( 'settings_description', 'settings_photo', 'settings_username', 'settings_background', ) widgets = { 'settings_description': forms.TextInput(attrs={'type': 'checkbox', 'class': 'checkbox', 'id': 'test1'}), 'settings_photo': forms.TextInput(attrs={'type': 'checkbox', 'class': 'checkbox', 'id': 'test2'}), 'settings_username': forms.TextInput(attrs={'type': 'checkbox', 'class': 'checkbox', 'id': 'test3'}), 'settings_background': forms.TextInput(attrs={'type': 'checkbox', 'class': 'checkbox', 'id': 'test4'}), } \.html <form method="POST"> {% csrf_token %} {{ basicsettings_form }} <button type="submit">Dad9adbaiduaadtest</button> When I click on the submit button, the page just refreshes but nothing happens. What might be the reason for this? The code above is just a snippet. Maybe nothing happens because I have multiple forms in one view? The whole view looks like this https://pastebin.com/Bu5NLTX1 but I just wanted to give you the relevant part -
Showing derived value in ModelForm's generated HTML Django
I want to display a ModelForm field with a derived value (from a JS script) in its "row", something like this: /budgetsheet/ Expenses Value Percentage foo 30 0.3 Where the value in bold is the one derived. Here's how I imagined it in HTML: budgetsheet.html ... <head> ... <script> function get_val() { ... document.getElementById("derived_val").value = val } </script> </head> <body> ... <form> <p> {{ expenses }}</p> <p id="derived_val">&nbsp</p> <p>{{ percentage }}</p> ... </form> <body> Where the value in bold is the derived value not in the model fields: models.py class BudgetSheet(models.Model): ... foo = models.FloatField(...) def get_val(self): ... return val While typing this I figured the easy way out is to just add the derived value as a field in the model itself, but it'll still be a problem in terms of restricting it to be not editable (doesn't use input field or is in greyed out input field). It will also add a repetitive field in the model, too. Just wanted to see if there are other solutions to this that are better, or if this solution can get over these problems, and others that may come. Thanks! -
Pylance & Docker - Import "somepackage" could not be resolved
How to deal with this issue when the packages are all inside Docker? For now I have to install the packages locally to enable the intellisense. P.S. The packages DO WORK without installation on local machine. Just wonder how to enable the intellisense like file locating and autocomplete. I feel like I am working on Notepad++ instead of VS Code without intellisense. -
Requests and requests_toolbelt not uploading file to django
I'm trying to upload a file to a django app, to keep track of the upload progress i'm using requests_toolbelt, the http response gives me 200, but the file is not being uploaded. What am i doing wrong? upload_url = 'http://127.0.0.1:8000/upload' client = requests.session() client.get(login_url) csrftoken = client.cookies['csrftoken'] login_data = {'username': username, 'password': password, 'csrfmiddlewaretoken': csrftoken} response = client.post(login_url, data=login_data) client.get(upload_url) csrftoken = client.cookies['csrftoken'] data = encoder.MultipartEncoder(fields={'file': open(file, 'rb'), 'csrfmiddlewaretoken': csrftoken}) monitor = encoder.MultipartEncoderMonitor(data, callback) response = client.post(upload_url, data=monitor, headers={'Content-Type': monitor.content_type}) -
are there two concepts of groups in CentOS
I am currently trying to deal with the permission issues with the /var/www folder for my django Project. Before I could do anything I had to make a user group and put www-data into the user for permission issues. But aparently sudo groupadd webusers command adds a group in the amazon centOs based instance, and when i try to use the command again, it says groupadd: group 'webusers' already exists However when I try to add the user, $ sudo usermod -aG webuser www-data usermod: group 'webuser' does not exist This happens, I am confused hehe... help -
Django ModelForm non-required CharField giving errors
I have a ModelForm for a model that has a couple of files and with every file, a type description (what kind of file it is). This description field on the model has CHOICES. I have set these file uploads and description uploads as hidden fields on my form, and not required. Now the file upload is working, but the description is giving field errors, the placeholder in the dropdown is not a valid choice, it says. That's true, but since it is not required, I would like it to just be left out of the validation and I am stuck on how. My codes, shortened them up a bit to keep it concise. models.py class Dog(models.Model): FILE_TYPE_CHOICES = [ ('SB', 'Stamboom'), ('RB', 'Registratiebewijs'), ('SJP', 'SJP-diploma'), ('CDD', 'CDD-diploma'), ('WT', 'Workingtestdiploma'), ('MISC', 'Overig'), ] dog_id = models.UUIDField(unique=True, default=uuid.uuid4) file_1 = models.FileField(upload_to=user_directory_path, blank=True, validators=[extension_validator]) desc_1 = models.CharField(choices=FILE_TYPE_CHOICES, blank=True, max_length=5) forms.py (I excluded all these fields from the model-code above to keep it more clear, but this is to demonstrate that these fields are not required. If I print the required attribute of 'desc_1' in the view, it also says false class DogForm(ModelForm): class Meta: model = Dog fields = ('stamboomnummer', 'stamboomnaam', 'date_of_birth', … -
Check how many users answered keeps returning first value
I am trying to see how many users answered each option however it will give me the result of how many people answered the first option. Result object is where all answered are saved to. Do I need to make a loop in the html? Would this not work as you cant call Result in to html and filter it ? How would I go around doing this. I see the counter is staying to the first value and keeps looping for each option, but I am confused on a fix for this. HTML <!DOCTYPE html> <html> <head> <title>Admin Panel</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: relative; display: flex; justify-content: center; flex-direction: column; padding: 10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -webkit-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -moz-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 5px; } … -
How to create a report showing revenue by product by year in Django?
Starting with this model: class LineItem(models.Model): created = models.DateTimeField(default=timezone.now) price = models.DecimalField(max_digits=8, decimal_places=2) product = models.CharField(max_length=15) From this, I want to create a report like this: Product. | 2020 | 2021 | 2022 ProdA | $10,000.00 | $9,500.00 | $3,200.00 ProdB | $110,000.00 | $98,000.00 | $35,300.00 ProdC | $119,500.00 | $54,000.00 | $25,300.00 To do this, I could use multiple queries to create a sequence of dictionaries, something like this: [ { "product": "ProdA", 2020: 10000.00, 2021: 9500.00, 2022: 3200.00, }, { "product": "ProdB", 2020: 110000.00, 2021: 98000.00, 2022: 35300.00, }, { "product": "ProdC", 2020: 119500.00, 2021: 54000.00, 2022: 25300.00, }, ] But I'm wondering if there's a better way (e.g, with one query). I'd appreciate any ideas. -
creating a custom user model in django using AbstractBaseUser
I am trying to create a custom user model, when i run python manage.py createsuperuser it promote to enter the username, then password, and confirm password, when i hit enter after that i get this error django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.email model.py : class UserManager(BaseUserManager): def _create_user(self, username, password=None, **extra_fields): if not username: raise ValueError("User must have a username") if not username: raise ValueError("User must have a password") user = self.model( username=username ) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_admin', False) return self._create_user(username, password, **extra_fields) def create_superuser(self, username, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_admin', True) return self._create_user(username, password, **extra_fields) class User(AbstractBaseUser): username = models.CharField(max_length=255, unique=True) email = models.EmailField(max_length=255, unique=True) active = models.BooleanField(default=True) admin = models.BooleanField(default=False) staff = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.username the entire errorlog: PS C:\Users\PC\Desktop\nitrofleet> python manage.py createsuperuser Username: lol Password: Password (again): This password is too short. It must contain at least 8 characters. This password is too common. This password is entirely numeric. Bypass password validation and create user anyway? [y/N]: y Traceback (most recent call last): File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return … -
Python & Django Simple Project
I have small app I am building out about books. I have main app titled 'books' and a startapp, 'titleBooks' , I included a templates folder for my .html files with a base.html. The problem I am getting is when I run the files on 'python manage.py runserver' I do not GET a response from the pages/home.html file with django code (for loop) just to print out the books in db. I am not sure why django does not see the code or file. Within pages/home.html file I do {% extend 'base.html' %} which it can read that file but not the home.html file. Any help is greatly appreciated. settings file below: [![enter image description here][1]][1] -
Is there a --max-requests flag for Daphne?
I have this ASGI applicate with Django and Daphne, and I'm using the following command. daphne -b 0.0.0.0 -p $PORT server.asgi:application Is there a way to add --max-requests and --max-requests-jitter to actively prevent memory leaks? Maybe something like: daphne -b 0.0.0.0 -p $PORT --max-requests 1000 --max-requests-jitter 50 server.asgi:application -
Error install requirements.txt Django project Mac M1
I got my Django project via gitlab and put it on my Macbook M1 but when I put myself in the virtual environment and I install the requirements I have a long error message that appears, I don't don't know how to fix this. Could it be because of the apple silicon chip? Here is the error message: Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: /Users/pierro/Documents/permacool/api_permacool/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/f2/r4cvtlb53hb3r3bvpzkmqnyr0000gn/T/pip-install-zdiid0g3/mysqlclient_87a039d3b25c4c3f8c32778ba1e13516/setup.py'"'"'; __file__='"'"'/private/var/folders/f2/r4cvtlb53hb3r3bvpzkmqnyr0000gn/T/pip-install-zdiid0g3/mysqlclient_87a039d3b25c4c3f8c32778ba1e13516/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/f2/r4cvtlb53hb3r3bvpzkmqnyr0000gn/T/pip-record-bh773nfm/install-record.txt --single-version-externally-managed --compile --install-headers /Users/pierro/Documents/permacool/api_permacool/include/site/python3.8/mysqlclient cwd: /private/var/folders/f2/r4cvtlb53hb3r3bvpzkmqnyr0000gn/T/pip-install-zdiid0g3/mysqlclient_87a039d3b25c4c3f8c32778ba1e13516/ Complete output (43 lines): mysql_config --version ['8.0.28'] mysql_config --libs ['-L/opt/homebrew/opt/mysql-client/lib', '-lmysqlclient', '-lz', '-lzstd', '-lssl', '-lcrypto', '-lresolv'] mysql_config --cflags ['-I/opt/homebrew/opt/mysql-client/include/mysql'] ext_options: library_dirs: ['/opt/homebrew/opt/mysql-client/lib'] libraries: ['mysqlclient', 'zstd', 'resolv'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/opt/homebrew/opt/mysql-client/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,0,3,'final',0)"), ('__version__', '2.0.3')] running install running build running build_py creating build creating build/lib.macosx-10.14-arm64-3.8 creating build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb creating build/lib.macosx-10.14-arm64-3.8/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.14-arm64-3.8/MySQLdb/constants copying MySQLdb/constants/CLIENT.py … -
Object showing instead of the value
I am running through an object and finding out how many people have answered however I try to add it into the context, the object is returned. The Value returned: <calendar.TextCalendar object at 0x7f90f2e7e5e0> Do I need to changed so I do the loop in the html or can I stick to doing it in the views? It returns the memory address Im assuming HTML <!DOCTYPE html> <html> <head> <title>Admin Panel</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: relative; display: flex; justify-content: center; flex-direction: column; padding: 10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -webkit-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -moz-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 5px; } .form_container { margin-top: 20px; } #form-title{ color: #fff; } #questionTitle { text-align: left; } .login_btn { width: 100%; background: #33ccff !important; color: white !important; } .login_btn:focus { box-shadow: none … -
Google meet clone django or nodejs
I have a django rest app and i want to add an app like google meet to it. Currently I am using django rest framework + channels. I would like to know if in terms of performance django rest framework + channels will be enough for me to manage the different user calls or messages. Should I use django rest + nodejs ? what is the best solution for you ? what technology would you have used ? Do you have any advice ? Thank you -
How to Display Other User's Profile on Django
Currently, I am trying to make a page for other users' profiles. The page includes a section for their profile, which contains profile picture, username, email, and bio. And another section for all of the posts the user posted. But I cannot display the profile section properly. This is what I managed to do so far The Profile module: from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') bio = models.CharField(max_length=225, blank=True, default='') def __str__(self) -> str: return f"{self.user.username}'s Profile" def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: img.thumbnail((300,300)) img.save(self.image.path) The Post module: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self) -> str: return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) The view: class UserProfileView(ListView): model = Post template_name = 'blog/user_profile.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') The blog/user_profile.html: {% extends 'blog/base.html' %} {% block title %}{{ view.kwargs.username }}'s … -
IntegrityError null value in column "name" of relation "tag" violates not-null constraint
I have created an API and am currently testing my post request with Postman. However, I keep getting this error. views.py def post(self, request, *args, **kwargs): serializer = TagSerializer(data=request.data) tag_input = Tag.objects.create(name=request.POST.get("name"), language=request.POST.get("language")) if serializer.is_valid(): serializer.save(tag_input) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) serializers.py class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('id', 'name', 'language') def create(self, validated_data): return Tag.objects.create(**validated_data) def to_representation(self, data): data = super().to_representation(data) return data models.py class Tag(models.Model): name = models.CharField(max_length=256) language = models.CharField(max_length=256) objects = models.Manager() def create(self, validated_data): tag_data = validated_data.pop('tag') Tag.objects.create(**tag_data) return tag_data def __str__(self): return self.name or '' -
Django migration OperationalError: index [name] already exists
I hope someone can help me. I have three environments as part of my django development lifecycle, dev, uat and live. Django 3.2.6 with python 3.9.6. I'm trying to add a couple of fields to two of my models but I'm getting an error when I try to migrate the live database, the dev and uat database migrations worked fine. Here is the migration code, generated by makemigrations # Generated by Django 3.2.6 on 2022-01-26 21:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tasks', '0015_activity_next'), ] operations = [ migrations.AddField( model_name='activity', name='delegated', field=models.BooleanField(default=False), ), migrations.AddField( model_name='activity', name='notified', field=models.BooleanField(default=False), ), migrations.AddField( model_name='adviser', name='digest', field=models.BooleanField(default=True, verbose_name='Send digest of assigned activities once per day?'), ), migrations.AddField( model_name='adviser', name='email', field=models.EmailField(default='i.pigney@tpio.co.uk', max_length=254), ), ] Nothing complex, just adding two fields to my Activity Model and another two fields to my Adviser model. I wasn't expecting any problems but... here is the error traceback: $python manage.py migrate ... Running migrations: Applying tasks.0016_auto_20220130_1904...Traceback (most recent call last): File "/home/.../projects/myproject/myprojectenv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/.../projects/myproject/myprojectenv/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: index tasks_activity_provider_id_1557b363 already exists The above exception was the direct cause of the following exception: Traceback (most …