Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - AttributeError: Got AttributeError when attempting
I am new to the Django Rest Framework and I try to build an API that lets a user create projects. That means the user - authenticated via a knox token - should become the owner of the created project instance. However, I am getting the following error, when doing a POST-request to /api/project/: AttributeError: Got AttributeError when attempting to get a value for field `username` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `ManyRelatedManager` instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'username'. urls.py: urlpatterns = [ path('api/projects/', ProjectListCreate.as_view()), path('api/project/', ProjectCreate.as_view()), path('api/project/<int:pk>', ProjectDetailShow.as_view()) ] api.py: class ProjectListCreate(generics.ListAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer class ProjectDetailShow(generics.RetrieveUpdateDestroyAPIView): queryset = Project.objects.all() serializer_class = ProjectDetailSerializer permission_classes = [IsOwnerOrReadOnly] class ProjectCreate(generics.CreateAPIView): serializer_class = ProjectDetailSerializer permission_classes = [permissions.IsAuthenticated] def perform_create(self, serializer): serializer.save(owner=self.request.user) serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class ProjectSerializer(serializers.ModelSerializer): owner = UserSerializer(read_only=True) class Meta: model = Project fields = ('id', 'name', 'owner', 'mission', 'category', 'status') class ProjectDetailSerializer(serializers.ModelSerializer): owner = UserSerializer(read_only=True) participants = UserSerializer(read_only=True) class Meta: model = Project fields = ('id', 'name', 'owner', 'participants', 'mission', 'category', 'description', 'status') models.py: class Project(models.Model): STATUS_CHOICES = (...) … -
Can I access to request object in django @register.assignment_tag
I need to access request object in a custom html tag (Django ver 1.11). This tag is used in a top level html template which is used by almost all other templates in the proyect. My code is this: @register.assignment_tag(takes_context=True) def get_color_style(context): request = context.get('request', None) #<---Here request object is None try: color = ehealth_models.CssSkin.objects.get( clinic=get_current_clinic(request) ).color_scheme except (ehealth_models.CssSkin.DoesNotExist, ValueError): color = 'defaultcolor' less_rule = os.path.join( settings.BASE_DIR, static('less/' + color + '.less')[1:] ) color_values = dict() with open(less_rule, 'r') as f: file_str = f.read() file_str = file_str.replace('\n', '') for item in next(csv.reader([file_str], delimiter=';')): rule_item = next(csv.reader([item], delimiter=':')) if len(rule_item) == 2: color, color_value = None, None for value in rule_item: value = value.replace(' ', '') if value.startswith('@'): color = value.replace('@', '').replace('-', '_') elif value.startswith('#'): color_value = value color_values[color] = color_value return color_values Any idea? Thanks! -
Hashing file within DRF (POST HTTP request)
I'm creating a REST API and I'm not particularly savvy in Django. I'd like to post an uploaded file, but before doing so I'd like to create the sha256 of the file, like so: def sha256sum(filename): h = hashlib.sha256() b = bytearray(128*1024) mv = memoryview(b) with open(filename, 'rb', buffering=0) as f: for n in iter(lambda : f.readinto(mv), 0): h.update(mv[:n]) return h.hexdigest() In order for this to work, I require the actual file (or file path), and not the actual filename. My code in my viewsets.py: def create(self, request): serializer = FileSerializer(data=request.data) f = request.FILES["file"] # just gives the filename print(request.META) if serializer.is_valid(): f = serializer.save() print(f"f: {f}") res_name = sha256sum(f) print(f"res_name: {res_name}") return Response(serializer.data, status=status.HTTP_201_CREATED) Any ideas where I am going wrong? -
Starting monitor thread on django
Let me give a bit of context. I'm currently building a simple web page in which, by filling out a form and hitting send, a recon of a target website is ran. The idea is to monitor this targets that I have already scanned. My idea was to make some requests to my database and check which targets have not been found in the last week (if target not scanned in past week, run scan again) For doing this, I was trying to start a thread which, once a day, checks which targets need to be scanned again. The problem is that for doing this, I need to time.sleep my thread for 24 hours, this should not be an issue, but it seems that runserver is being delayed by this sleep time. Here is my monitor method which will be assigned to a thread def start_monitor(): while 1: today = dt.datetime.now() targets = mongo.get_targets() for target in targets: target_last_date = mongo.get_target_last_scan(target) date_diff = target_last_date - today if date_diff.days > 7: print('Running recon again') else: print('Not yet') wait_to_tomorrow() return The thread starts with monitor_thread = threading.Thread(name='Monitor Process', target=monitor.start_monitor()) monitor_thread.setDaemon(True) monitor_thread.start() Where should I start the thread? -
Python Django: You're using the staticfiles app without having set the STATIC_ROOT setting setting to a filesystem path
i am trying to deploy my site using heroku but when i run git push heroku master it shows: remote : raise ImproperlyConfigured("You're using the staticfiles app " remote : django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. remote: remote : ! Error while running '$ python manage.py collectstatic --noinput'. settings.py import django_heroku import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*******************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pytalk.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'pytalk.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': … -
Adding custom user authentication to django-rest-framework-simple-jwt
I want to add user login via One-time Password as well as the usual username/password method in django. In order to do so, either username/password or username/OTP are sent from client to sever and based on the provided pair of fields, I need to return access and refresh token if the user is authenticated. I am using django's simple-jwt. I know that I have to override TokenObtainPairView and TokenObtainSerializer. The problem is, I want to do the field validation part myself. In my views, I override simple-jwt's default view. #views.py class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer And I override the serializer like below: #serializers.py class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): try: request = self.context["request"] except KeyError: pass try: request_data = json.loads(request.body) if("username" in request_data and "password" in request_data): # default scenario in simple-jwt pass elif("username" in request_data and "otp" in request_data): # validate username/otp manually and return access/token pair if successful pass else: # some fields were missing raise serializers.ValidationError({"username/otp or username/password" : "These fields are required"}) except: pass So, if client passes user credentials in the forms below, I will be able to authenticate it and return token pair. { "username" : "Winston", "password" : "testpass" } or { "username" : … -
Django REST Framework: NestedSerializer in OneToMany relation
I have 2 related models: class Systems(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=2000, null=True, blank=True) class Teams(models.Model): system = models.ForeignKey(Systems, on_delete=models.CASCADE) name = models.CharField(max_length=200) description = models.CharField(max_length=2000, null=True, blank=True) And 2 serializers: class System_serializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField class Meta: model = Systems fields = ('id', 'name', 'description') def create(self, validated_data): return Systems.objects.create(**validated_data) def update(self, system, validated_data): system.name = validated_data.get('name', system.name) system.description = validated_data.get('description', system.description) system.save() return system second: class Team_serializer(serializers.ModelSerializer): id = serializers.ReadOnlyField system_id = System_serializer() class Meta: model = Teams fields = ('id', 'system_id', 'name', 'description') def create(self, validated_data): return Teams.objects.create(**validated_data) def update(self, team, validated_data): team.name = validated_data.get('name', team.name) team.description = validated_data.get('description', team.description) team.save() return team In 'team' entity I just want to have only 'System' ID, not the whole 'System' How can I use the System_serializer, to serialize 'system_id' in 'team' object? Thanks! -
Django channels deploy - error during handshake
I deployed a Django application to a VPS, everything seems to work except for the Django Channels part of the app. I'm trying to establish a connection from a template to my websocket consumer, but i keep getting the following error: (index):10 WebSocket connection to 'ws://mydomain/receiver' failed: Error during WebSocket handshake: Unexpected response code: 404 Here is how i deployed the app: /etc/nginx/sites-available/myproject server { listen 80; server_name 54.39.20.155; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /WaitingRoomVenv/WaitingRoom/WaitingRoom/static; } location / { include proxy_params; proxy_pass http://unix:/WaitingRoomVenv/WaitingRoomEnv.sock; } } /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/WaitingRoomVenv/WaitingRoom ExecStart=/WaitingRoomVenv/WaitingRoomEnv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/WaitingRoomVenv/WaitingRoomEnv.sock WR.wsgi:application [Install] WantedBy=multi-user.target And here is the Daphne service: [Unit] Description=daphne service to run Channels on WaitingRoom After=network.target After=nginx.service [Service] Type=simple RuntimeDirectory=daphne PIDFile=/run/daphne/pid User=root Group=www-data WorkingDirectory=/WaitingRoomVenv/WaitingRoom ExecStart=/WaitingRoomVenv/WaitingRoomEnv/bin/daphne -u /tmp/daphne.sock WR.asgi:application ExecStop=/WaitingRoomVenv/WaitingRoomEnv/bin/kill -s TERM $MAINPID [Install] WantedBy=multi-user.target Both these two services are running without any erros, but when i try to run Channels on any template, i get the error. Can anyone help me find what am i doing wrong? -
How to create video synchronous web app with Node.js?
I want to create a web app similar to GAZE. It's a video synchronous web app. Is node.js is good for building this web app? If yes then what library should I use? If no then which technology I should use? -
how to make calculations within loop in html table (django)
i have table in html: ab=[24,56,78] <table > <tr><th>ab</th> {% for d in ab %} <td>{{ d }}</td> {% endfor %} </tr> </table> ab is a list. How i can automatically multiple list ab by 100 within loop ? -
Python csv reader for row in reader - what does the the throwaway underscore represent in this code?
I'm reading data from a csv file. I get that 'row' is the variable that represents the loop I am going through, but what is the "_" that is being thrown away here? for row in csv_reader: _, Student.objects.get_or_create( first_name=row[0], last_name=row[1], email=row[2], organisation=row[3], enrolled=row[4], last_booking=row[5], credits_total=row[6], credits_balance=row[7], ) -
How do you view your PostgreSQL database and tables that are part of a Django app that has been uploaded to Heroku?
Built a Django app locally. Worked fine. Uploaded to Heroku which appeared to be successful. However "user" table is evidently corrupted. I cannot login or create users without errors on Django app on Heroku. I want to modify (specifically delete) rows in the "user" table of the PostgreSQL database on Heroku. How can I do that? I ran the following from the CLI without success: heroku run python manage.py makemigrations heroku run python manage.py migrate -
ASP.Net MVC SiteMapProvider analog for Django
I have created 3 Django web sites and hosted them on different machines under the same LAN sub-net. I want to create 4th web site with menu to have possibility to navigate trough all my sites transparently like in one web. In ASP.Net this is done using MVC SiteMap Provider Is there any techniques or SiteMap Provider analogs in Django? -
Trying to figure out how to create course creation system like Udemy
I want to create system, where you can create courses with sections, and section should contain videos like on Udemy. I tried to do that with ForeignKey, but it's not exactly what i want. I want to create system that will work in the following order: 1. You are creating Course and in form you are creating first section 2. After that you can add sections to each Course 3. And also you can add videos to each section How to implement all of that? I tried to that with in following way class SectionVideos(models.Model): video = models.FileField(upload_to='courses/section_videos') class CourseSections(models.Model): title = models.CharField(max_length=50) video = models.ForeignKey(SectionVideos,on_delete=models.CASCADE) class Course(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=150, null=True, blank=True) section = models.ForeignKey(CourseSections,related_name='course_sections',on_delete=models.CASCADE,null=True) description = models.TextField() image = models.ImageField(upload_to='courses/course_images',blank=True,null=True) cover = models.ImageField(upload_to='courses/course_covers',blank=True,null=True) tutor = models.ForeignKey(User,related_name='tutor_courses',on_delete=models.CASCADE,null=True) students = models.ForeignKey(User,related_name='course_students',blank=True,on_delete=models.CASCADE,null=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) category = models.ForeignKey(CourseCategories,on_delete=models.CASCADE) certificate = models.ImageField(upload_to='courses/course_certificates',blank=True,null=True) languages = LanguageField(blank=True) rank_score = models.FloatField(default=0.0) price = models.FloatField(default=0.0) discount_price = models.FloatField(blank=True, null=True) -
Django - How to stamp user score on Account.html page
I consider myself a beginner in Django and I'm stucked in a passage. My goal is to print on account.html each score that a user acquired after having done a quiz. So for example in account.html --> "Hello (user_name), your scores are: DataScience = 9/10 Do you have suggestions or guides/resources where I can look on? account/account.html {% extends 'base.html'%} {% block content %} <h1> Benvenuto nella Home {{request.user.username}}!</h1> <h2> I tuoi scores sono: </h2> {% for user in users %} {% for score in user.studentscores_set.all %} <p>{{ score.field_name }}</p> {% endfor %} {% endfor %} <!-- CHANGE PASSWORD --> <br><br> <br><br> <form class="form-signin" method='post'> {% csrf_token%} <!-- <img class="mb-4" src="https://getbootstrap.com/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72"> --> <h1 class="h3 mb-3 font-weight-normal">CHANGE PASSWORD </h1> <input type="email" name='email'id="inputEmail" class="form-control" placeholder="Email address" required autofocus> <input type="password" name='email' id="inputPassword" class="form-control" placeholder="Password" required> {% for field in account_form %} <p> {% for error in field.errors %} <p style='color:red;'> {{field.help_text}} </p> {% endfor %} {% if account_form.non_field_errors %} <div style="color: red"> <p>{{account_form.non_field_errors}}</p> </div> {% endif %} </p> {% endfor %} <button class="btn btn-lg btn-primary btn-block" type="submit">CHANGE PASSWORD</button> </form> <!-- <h2> Login</h2> <form method='post'> {% csrf_token%} {% for field in login_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} … -
(Beginner) Error when loading 'python manage.py runserver' on Visual Studio Code part of Django project
I'm fairly new to this and am currently learning Django on Visual Studio Code using a Mac. I'm getting a few error and was wondering if someone could help. When I try to run my project through virtualenv I get the following error in the Terminal: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/urls/resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", … -
How to use a variable from one function in the other function in Django Views
I have 2 functions: The 1 function checks the URL for scheme: def checkurl(self): if request.method == 'POST' and 'url' in request.POST: url = request.POST.get('url', '') if not url.startswith('http://') and not url.startswith('https://'): url = "https://" + url return url The 2 function should use the url variable. But it says "name 'url' is not defined". Here is the second function: def tests(request): ################################################## # URL Parse: netloc, scheme ################################################## x = datetime.datetime.now() time = x.strftime("%Y-%m-%d-%H-%M-%S") if request.method == 'POST' and 'url' in request.POST: headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}#headers # Set Width and Height width_get = request.POST.get('width', '') height_get = request.POST.get('height', '') if width_get is not None and width_get != '': width = width_get else: width = 1600 if height_get is not None and height_get != '': height = height_get else: height = 1000 if url is not None and url != '': url_parsed = urlparse(url) scheme = url_parsed.scheme netloc = url_parsed.netloc if netloc.startswith('www.'): netloc = netloc.replace('www.', '') image_path = "media/" + netloc + "-" + time + ".png" shot_path = "/media/" + netloc + "-" + time + ".png" path = "C:/WebDrivers/chromedriver.exe" driver = webdriver.Chrome(path) driver.get(url) driver.set_window_size(width, height) driver.save_screenshot(image_path) screenshot = image_path driver.quit() var_dict … -
How to dynamically display checkboxes in form?
I want to display checkbox options based on queries from the view. For instance, this is my current code: view: def new_role_task(response, id): ... query = Query.objects.filter(id=id) if response.method == 'POST': form = Form(response.POST) if form.is_valid(): .... return redirect(f'/...') else: form = Form() return render(response, ...html', {'form':form, ...}) form: FAVORITE_COLORS_CHOICES = [ ('blue', 'Blue'), ('green', 'Green'), ('black', 'Black'), ] class Form(forms.Form): checkbox_fields = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES, ) ... Instead of FAVORITE_COLORS_CHOICES, I want to use queries that I would make from the view itself that will be dynamic depending on the params passed to the page. For instance, I come from Rails and within rails, you can accomplish this on the front or backend by doing: Front: <%= collection_check_boxes(:post, :author_ids, Author.all, :id, :attribute) %> This would then display all records from the Author model. Or you can define Author like @authors = Author.where(ids: [1,2,3]) <%= collection_check_boxes(:post, :author_ids, @authors, :id, :attribute) %> This would then display all Authors from the query that match. I assume for Django, all I need to do is get my query into [('')] format and then somehow get that to override the form.py file? What is the method on accomplishing this? I guess there are … -
Failing to Upload JSON Postgresql Database Backup to New Django Heroku App via loaddata
I am upgrading an old app to a new app on Heroku (Python 3.7 Django 2.2). Locally, I was able to successfully upload json database backup fixture and it works great. I've created a new app with no problems, but when I upload the database backup fixture to the new Heroku app the process just ends after several seconds and the data is not uploaded. I am given no errors. This is my command: heroku run python manage.py loaddata db-back1.json The response: Running python manage.py loaddata db-back1.json on ⬢ app-name... up, run.6706 (Free) Shortly, after it just ends the process with no error. Notes and things I've tried: My json fixture file is 300mb, so it's quite large. It took several minutes to upload on my local instance. Do I need to upload to S3 first? I've upgraded the app to standard on heroku and and the url of the database has been updated correctly and is set to the right database, though the response keeps including (Free). To be clear, the Heroku app is working successfully, it just has no data. Further, I was able to get the app and dataload working successfully on my local version. This leads … -
I/O operation on closed file in django with 'ImageKit'
In my django project I am using ImageKit to size my profile images. I have a model with these fields: pasfoto = models.ImageField(upload_to='images/', blank=True) pasfoto_thumbnail = ImageSpecField(source='pasfoto', processors=[ResizeToFill(150, 200)], format='JPEG', options={'quality': 60}) ImageSpecField is imported from Imagekit. I am saving my images on amazon-S3 via Django-storages When I upload an image via the template (edit form) rendered via an UpdateView it shows the detail template after success. The pasfoto_thumbnail is used in this template, that is rendered via a class based DetailView in Django. In this case I see an error 'I/O operation on closed file'. But after a browser refresh is shows the right image. What is happening and how could I solve this issue? -----DEBUG MESSAGE ------- error message from django debug -
I want each item of these lists to be printed side by side in Django template
context = {'list1':list1,'list2':list2} return render(request,"template.html",context) this is the last two lines of my views.py file I want each item from list1 and list2 to be printed side by side in a table what I tried is {% for item1 in list1 %} {% for item2 in list2 %} <tr> <td>item1</td> <td>item2</td> </tr> {% endfor %} {% endfor %} but it is printing all values of list2 to just for single object of list1 -
Python csv reader for row in reader gives syntax error
New to Django/Python. I need to write an import script for a CSV file to seed some data (not using fixtures, did that already as that is JSON based and not CSV). This works: import csv from datetime import datetime from django.utils.timezone import make_aware from django.core.management.base import BaseCommand from chatterbox.models import Organisation, Course, Student class Command(BaseCommand): def handle(self, **options): CSV_PATH = './students_AEKI.csv' Student.objects.filter(organisation__name__exact="AEKI").delete() with open(CSV_PATH) as file: file.readline() # skip the header csv_reader = csv.reader(file, delimiter=',') org = Organisation.objects.filter(name='AEKI') for row in csv_reader: _, Student.objects.get_or_create( first_name=row[0], last_name=row[1], email=row[2], organisation=org[0], enrolled=row[4], last_booking=row[5], credits_total=row[6], credits_balance=row[7], ) This does NOT work: import csv from datetime import datetime from django.utils.timezone import make_aware from django.core.management.base import BaseCommand from chatterbox.models import Organisation, Course, Student class Command(BaseCommand): def handle(self, **options): CSV_PATH = './students_AEKI.csv' Student.objects.filter(organisation__name__exact="AEKI").delete() with open(CSV_PATH) as file: file.readline() # skip the header csv_reader = csv.reader(file, delimiter=',') org = Organisation.objects.filter(name='AEKI') for row in csv_reader: enrolled_utc = datetime.strptime(row[4], '%Y-%m-%d') last_booking_utc = datetime.strptime((row[5], '%Y-%m-%d') _, Student.objects.get_or_create( first_name=row[0], last_name=row[1], email=row[2], organisation=org[0], enrolled=enrolled_utc, last_booking=last_booking_utc, credits_total=row[6], credits_balance=row[7], ) Syntax error at the "_". I need to do some manipulation (eg like adding timezone to date fields) on data before creating it in the table. So what is wrong with the 2nd version? -
DRF reverse for 'user-create' not found
Got a view named MyUserCreate and in app/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'api/users^$', views.MyUserCreate.as_view(), name='user-create'), ] In app/tests.py self.create_url = reverse('user-create') Running python manage.py test Gives this error Traceback (most recent call last): File "C:\Users\tiago\Desktop\letsgo\COVID19-be\django_server\user\tests.py", line 13, in setUp self.create_url = reverse('user-create') File "C:\Users\tiago\Desktop\letsgo\venv\lib\site-packages\django\urls\base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\tiago\Desktop\letsgo\venv\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'user-create' not found. 'user-create' is not a valid view function or pattern name. What can I do to solve it? -
How to compare the fields taken through a form to those of a model created in django?
I have created a Customer model in my models and registered it on admin.py. Then I made a login form and took field values using get method.Now I want to iterate through all the objects of customer created and find the one with those two matching fields.I have made a login function in the views.py. This is my model:class Customer(models.Model): FirstName = models.CharField(max_length=100, default="") LastName = models.CharField(max_length=100, default="") address = models.CharField(max_length=500, default="") EmailId = models.CharField(max_length=120, default="") PhoneNo = models.CharField(max_length=12, default="") Password = models.CharField(max_length=120, default="") And this is my function: def login(request): if request.method=="POST": FirstName= request.POST.get('FirstName', '') Password = request.POST.get('Password', '') for customer in Customer.objects.all(): if FirstName==customer.FirstName and Password==customer.Password: return redirect ( 'customer-home') return render(request, 'customer/login.html') I'm not getting the desired results. -
Django Add new record error duplicate key value violates unique constraint "" Django Id doesn't sync with database
I developed a Django Application and it was working correctly, until I did a data migration to the database created by django migration, I migrated the data using an sql script and Pgadmin. Now I have the database full with records but when I am trying to add new record using django form I got the below error duplicate key value violates unique constraint "learningcenters_partnerorganization_pkey" DETAIL: Key (id)=(1) already exists. taking into consideration that the available id for this table is 10. Model: class SLPAcademicRound(models.Model): name = models.CharField(max_length=45, unique=True, verbose_name=_('Academic Round Name')) code = models.CharField(max_length=5, unique=True, verbose_name=_('Code')) cycle = models.ForeignKey( SLPCycle, blank=False, null=True, verbose_name=_('SLP Cycle/SLP Cycle'), on_delete=models.CASCADE, ) learning_center = models.ForeignKey( LearningCenter, blank=False, null=True, verbose_name=_('Learning Center'), on_delete=models.CASCADE, ) round_date_start = models.DateField( blank=True, null=True, verbose_name=_('SLP Round Start Date') ) round_date_end = models.DateField( blank=True, null=True, verbose_name=_('SLP Round End Date') ) current_round = models.BooleanField( blank=True, null=True, verbose_name=_('Current Round') ) View: class AddSLPAcademicRoundView(LoginRequiredMixin, GroupRequiredMixin, CreateView): template_name = 'bootstrap4/common_form.html' form_class = SLPAcademicRoundForm queryset= SLPAcademicRound.objects.all() group_required = ["LearningCenterManager"] def get_absolute_url(self): return reverse("slp:slp_academic_round_list") def form_valid(self, form): print((form.cleaned_data)) form.save(self.request) return super(AddSLPAcademicRoundView, self).form_valid(form) def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs(*args, **kwargs) kwargs['user'] = self.request.user return kwargs