Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Form validation based on public key/foreign key
I have an Event model and a Registration model (one event can have multiple registrations -> ForeignKey). At event/<pk>/register I want to present a Form where you can register for the certain event. So, I have to do Form validation in my forms.py. However, I need access to the public key of the URL. But I do not know how I get the public key? The other way would be to include the pk to the Form. Problem here is that when you surf at event/5/register the field for the event MUST be 5 and should not be editable. But I could not find a solution to initially set the Event in the Form for the Registration creation. Additionally, it must not be editable. I'm pretty sure that's quite a common problem. What is the solution? -
Django with PIL - '_io.BytesIO' object has no attribute 'name'
I'm using PIL to resize an uploaded photo before saving. Note that I'm using formsets to upload the pictures. I'm using BytesIO to open the file. At the last step, I get the error - '_io.BytesIO' object has no attribute 'name'. Why is this? def fsbo_create_listing(request): PhotoFormSet = formset_factory(OwnerListingPhotoForm, extra=15) if request.method == 'POST': form = OwnerListingForm(request.POST) photo_formset = PhotoFormSet(request.POST, request.FILES) if form.is_valid() and photo_formset.is_valid(): form.instance.user = request.user form.save() for i in photo_formset: if i.instance.pk and i.instance.photo == '': i.instance.delete() elif i.cleaned_data: temp = i.save(commit=False) temp.listing = form.instance temp.save() # Where the error happens def clean_photo(self): picture = self.cleaned_data.get('photo') # I had to import ImageFieldFile. If picture is already uploaded, picture would still be retrieved as ImageFieldFile. The following line checks the variable type of `picture` to determine whether the cleaning should proceed. if type(picture) != ImageFieldFile: image_field = self.cleaned_data.get('photo') image_file = BytesIO(image_field.read()) image = Image.open(image_file) image = ImageOps.fit(image, (512,512,), Image.ANTIALIAS) image_file = BytesIO() image.save(image_file, 'JPEG', quality=90) image_field.file = image_file #if picture._size > 2*1024*1024: #raise ValidationError("Image file too large. Max size is 2MB.") return picture class OwnerListingPhoto(models.Model): listing = models.ForeignKey(OwnerListing, on_delete=models.CASCADE, related_name='owner_listing_photo') photo = models.ImageField(upload_to=owner_listing_folder_name) -
Show the data points in tabular format in Html from Django
My goal is to print the data points of the DataFrame in Django to Html page, along with the index values. My views.py def view_data(request): data_cols = list(data.columns.values) # to retrieve the column names context_data_sample = { 'data': data_, #data_ contains the data in DataFrame 'columns': data_cols #contains the columns of the data frame } return render(request, 'polls/home.html', context_data_sample) HTML code {% for i in data %} <tr> <td>{{ i.columns }}</td> </tr> {% endfor %} Although I mentioned above that I would like to print with the index values I am stuck with projecting just the name of the variable and nothing else, for instance, if I have Passenger column it is showing the Passenger and nothing else. Could anyone help me in projecting my dataset with the index values for respective rows? Thanks in advance. -
Django ORM: Group by and SQL Agregation
I know that exists any same topics there, but that are not described my situation :( I have a model below: class SecurityPrice (models.Model): security = models.ForeignKey(Security, on_delete = models.CASCADE) created = models.DateTimeField() price = models.FloatField() class Meta: ordering = ('-created',) def __unicode__(self): return u'%s - %s - %s' % (self.created, self.security.ticker, self.price) or in sqlite: CREATE TABLE IF NOT EXISTS "restful_api_securityprice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "created" datetime NOT NULL, "price" real NOT NULL, "security_id" integer NOT NULL REFERENCES "restful_api_security" ("id")); And I want to select last prices for each security paper In raw SQL I may do it with such SQL-request: SELECT MAX(created), security_id, price as created FROM restful_api_securityprice GROUP BY security_id; Below Some Examples for understand my needs: All records from table sqlite> SELECT * FROM restful_api_securityprice; 1|2018-01-07 23:13:02|920.0|1 2|2018-01-07 23:13:43|137.12|2 3|2018-01-07 23:13:58|147.3|3 4|2018-01-09 00:46:29|920.0|1 5|2018-01-09 00:47:27|137.12|2 6|2018-01-09 00:48:08|147.3|3 A what I to need sqlite> SELECT MAX(created), security_id, price as created FROM restful_api_securityprice GROUP BY security_id; 2018-01-09 00:46:29|1|920.0 2018-01-09 00:47:27|2|137.12 2018-01-09 00:48:08|3|147.3 In raw SQL it's ok. But how I can do the same in Django ORM API without include raw sql? -
Django Foreign key that could contain objects of different classes
is there a way to be able to use a foreign key to reference objects of diffrent classes for example, this is what i'm doing : Class discussion(models.Model): id_discussion = models.CharField(db_column='id_Discussion', primary_key=True, max_length=100) id_worker = models.ForeignKey('Worker', models.CASCADE, db_column='id_user', blank=True, null=True) id_director = models.ForeignKey('Director', models.CASCADE, db_column='id_user', blank=True, null=True) Class Message(models.Model): #some other fields id_sender = models.CharField(db_column='id_Sender', max_length=100, blank=True, null=True) id_receiver = models.CharField(db_column='id_Receiver', max_length=100, blank=True, null=True) id_discussion = models.ForeignKey('discussion', models.CASCADE, db_column='id_Discussion', blank=True, null=True) I want to turn id_receiver and id_sender into foreign keys, my problem is that the sender could be an object of class "Worker" or of class "Director". -
Data from 1:n relation in Django into a flat file
I've spent quite some time googling, but none of the findings seem to fit my situation. I am ramping up a little data warehouse where I store all Facebook Posts of my pages and I do performance snapshots (impressions, clicks, shares, comments...) of every post every 20 minutes for the first week, so that I can build some prediction models for fresh posts in a later project on this dataset. This means that there is a 1:n relation between Post and Performance-Snapshot and every post has around 500 performance snapshots. For a start I just have to create a CSV-API for an external visualisation tool, so I need a flat file format for every post in a given time range together with it's final (i.e. latest) performance snapshot in the same line. And the problem is that I can't find a way to build the list of all posts and their latest performance snapshot in a single shot as I can do with JOINS in direct SQL. My slightly simplified models: class FBPost(models.Model): post_id = models.CharField(max_length=64, unique=True) type = models.CharField(max_length=32) message = models.TextField() description = models.TextField() created_time = models.DateTimeField() permalink_url = models.TextField(blank=True) class Meta: get_latest_by = 'created_time' class FBPostPerformance(models.Model): post_id … -
null=True,blank=True but still error may not be null is raised everytime during post
my model: Assets(modes.Model): assset_code=models.CharField(max_length=12,null=True,blank=True) In my serializers.py: asset_code=serializers.CharField(max_length=12,allow_blank=True,required=False) When I post data, it still says this field may not be null. It lets me pass only if I put data. While I am at it, whats the correct way to make JSONField() optional in serializers too? -
How does Django handle multiple requests?
How does Django handles multiple requests in production environment? Suppose we have one of web server: Apache, Nginx, gunicorn etc. So do those servers for any request from web browser start new process to serve that request? If it's true, doesn't it cause huge overhead? If it's not true, then how the same view (let it be def hello(request) view bound to /hello url) serve several requests at the same time. I've seen answers for question "... handle multiple users" -
How to match any url using path() method django
I have a project called gigi and app called account. Inside gigi/urls.py i have the following code urlpatterns = [ path('account/',include('account.urls')), ] Inside account/urls.py urlpatterns = [ path('', views.dashboard, name="dashboard"), ] I want to include authentication urls from django.contrib.auth.urls using include('django.contrib.auth.urls')) How can i include it so that any url that doesn't match '' inside account.urls be get looked up inside auth urls -
Django Attribute Error: Type Object has no attribute 'all'
I am running into this error at my Django 2.0.2 (Python 3.6.4) project: AttributeError at /upload/ type object 'Tag' has no attribute 'all' The idea is to have tasks and to add one or more tags to each task. The task models reference to the tag class is tags = models.ManyToManyField(Tag, blank=True) and works fine in the admin interface. Now when I call my upload form the error above shows up. Here is the upload form class UploadForm(forms.Form): title= forms.CharField(label='Tasktitle', max_length=255) data= forms.FileField(label='Data') tags = forms.ModelMultipleChoiceField(Tag) The upload view is def upload(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): newTask = Task(titel=request.POST['title'], tags=request.POST['tags'], data=request.FILES['data']) newTask.save() return HttpResponseRedirect('success/') else: form = UploadForm() return render(request, 'upload/upload.html', {'form': form}) I tied to adjust the different parameters, but I can't figure out where the call for an 'all' attribute comes from. If you need more information or clarification just add a comment. Thank you very much. -
PyCharm VENV doesn't launch
I was working in PyCharm on a Django project when I decided to move my project folder to a different location. After I moved the project and opened it, PyCharm stopped automatically launching the virtual environment on startup. On PyCharm launch I get this error in the terminal: bash: source: /Users/Alex/Documents/Projects/MyProject: is a directory I tried reselecting the interpreter, changing the path in the activate files of the venv, but nothing seems to work. I even tried moving the project to the original location, but it still doesn't launch venv. The new address of my project is /Users/Alex/Documents/Projects/MyProject-API/venv/... All other projects that stayed where they were created have venv running when I open them. I also know that I can launch venv manually, but I'm trying to figure out the reason of this frustrating problem. The PyCharm setting all seem to be in order. Do I need to change the script and indicate a new path to my venv somewhere? Any help would be appreciated -
Django best practice: Should I split non-app specific models into my project folder?
I am going to extend the django user models - is it best practice to create a new models.py in my project directory: I.e: project application migrations static models.py (all my application specific models) project forms.py urls.py views.py *** project models.py ? *** I want to add email confirmation to my user sign up. So basically just extend the user model. I am thinking this may not be best practice to do in my application models, but for this case it is only going to be one model so would not really matter. However if I want to extend more non-application specific models then it might be better to do this in a separate file? Does anyone do anything similar and have any tips? Thanks -
Django filter by date like "201803"
Srry for my english. I try create some filter list like ?date=201803 - its meen get all data 2018 years 03 month. This is my model: class TestModel(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) date = models.DateTimeField(blank=False) text = models.TextField(max_length=256, blank=False) This is my view: class TestView(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = TestSerializer queryset = TestModel.objects.all() filter_backends = (DjangoFilterBackend,) filter_fields = ('date',) but if i can view some date if do like this: ?date=2005-03-12T21:48:00Z field date = models.DateTimeField(blank=False) must be DateTimeField How can do request like this: ?date=201803 ? -
How to run a python file from remote link by posting request from android application
I'm developing a mobile app that will use a python back-end for posting to MySql database.Normally I was using php link for the post purposes and tried it with python as well. protected void TrySignUp() { HttpURLConnection connection; OutputStreamWriter request = null; URL url = null; String response = null; String parameters = "username=" + mUserNameString + "&password=" + mPasswordString.hashCode()+"&email="+mEmailString+"$pic_link="+""; try { url = new URL("https://www.pythonanywhere.com/user/menimadim/files/home/menimadim/backend.py"); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestMethod("POST"); request = new OutputStreamWriter(connection.getOutputStream()); request.write(parameters); request.flush(); request.close(); String line = ""; InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader reader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } // Response from server after login process will be stored in response variable. response = sb.toString(); // You can perform UI operations here Toast.makeText(this, "Message from Server: \n" + response, Toast.LENGTH_LONG).show(); isr.close(); reader.close(); } catch (IOException e) { // Error Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } } My question is: How can I run the python script from remote link as an API with Android. Any suggestion would be welcomed such as free server for beneficial usage. Please consider that I'm new python developer... -
Django: Show existing data in ModelForm of another field
In my model CustomModel there is a field called file: file = models.OneToOneField('File', on_delete=models.PROTECT, editable=False, blank=True, null=True) The File model looks like this: class File(models.Model): file = models.FileField( upload_to=get_filepath, max_length=45, validators=[ FileExtensionValidator(allowed_extensions=['pdf', 'jpg', 'png']), file_size, ] ) original_name = models.CharField(max_length=45) extension = models.CharField(max_length=3) In my forms.py there is this: class CustomModelForm(forms.ModelForm): upload = forms.FileField(max_length=45, required=False, validators=[ FileExtensionValidator(allowed_extensions=['pdf', 'jpg', 'png']), file_size, ],) My problem: When people edit the CustomModel then they can find all existing data. Only for the upload field that is not possible. My goal is to show the people, when they edit CustomModel, the content of CustomModel.file. However, in my CustomModelForm there I cannot show this field, but only the upload field. I need to show for the upload field the contet of CustomModel.file if available. I just don't know how to do this. -
Innosetup Runhidden flag is not working
I have wrapped up my django project using pyinstaller and later used Innosetup to make installer. Since django command prompt running background looks ugly, I used runhidden flag in Innosetup.But when i click on desktop icon application starts running by hiding command prompt, and when i run once more time without closing previous opened app command prompt become visible. I want to make command prompt hidden always. For more details have a look on my ISS script: [Run] Filename: "{app}\{#MyAppExeName}"; Description: "Start Crumbs For Tableau"; Flags: waituntilidle postinstall runhidden skipifsilent -
django.db.utils.IntegrityError: UNIQUE constraint failed: ProgrammerProfile_posts.author_id
So I am trying to make this website and I get this error while I was making changes to my models django.db.utils.IntegrityError: UNIQUE constraint failed: ProgrammerProfile_posts.author_id models.py- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class Person(models.Model): id = models.IntegerField(primary_key=True) Name = models.CharField(max_length=255) age = models.IntegerField() Description = models.TextField() ProfilePic = models.FileField() def __str__(self): return self.Name class Posts(models.Model): id = models.IntegerField(primary_key=True) Name = models.CharField(max_length=255) post = models.TextField() author = models.ForeignKey('Person', on_delete=models.CASCADE) def __str__(self): return self.Name -
AWS Kubernetes RDS connection
I'm having some trouble with my AWS Kubernetes instance. I'm trying to get my django instances to connect to the RDS service via the DB endpoint. DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': os.environ['NAME'], 'USER': os.environ['USER'], 'PASSWORD': os.environ['PASSWORD'], 'HOST': os.environ['HOST'], 'PORT': os.environ['PORT'] } } The host string would resemble this service.key.region.rds.amazonaws.com and is being passed to the container via env in the deploy.yml containers: - name: service env: - name: HOST value: service.key.region.rds.amazonaws.com This set up works locally in kubernetes but not when I put it in the cluster I have on AWS. It returns the following error instead: django.db.utils.OperationalError: could not translate host name Any suggestions or am I missing something in how AWS likes handling things? -
Django TypeError, drop
I want to signed in user to be able to invite users to a 'team', where the teams they can select from are only those they are a part of. I keep getting the same error (init() missing 1 required positional argument: 'user') when I try and output a list of all teams in model UserTeams where the userID = current logged in user. My view: def invite(request): if request.method == 'POST': form = InvitePlayerForm(request.POST) if form.is_valid(): userteam = form.save(commit=False) userteam.save() else: form = InvitePlayerForm() query = UserTeams.objects.all() return render(request, 'teammanager/invite.html', { "invite": query, "form": form }) My Form: class InvitePlayerForm(forms.ModelForm): class Meta: model = UserTeams fields = ['userID','teamID'] def __init__(self,user,*args,**kwargs): super (InvitePlayerForm,self ).__init__(user,*args,**kwargs) self.fields['teamID'].queryset = Team.objects.filter(id__in = UserTeams.objects.filter(userID = user)) My UserTeams model: class UserTeams(models.Model): userID = models.ForeignKey(User,on_delete=models.CASCADE) teamID = models.ForeignKey(Team,on_delete=models.CASCADE) My HTML: <html> <body> <h4>Invite players to your team</h4> <form method="post"> {% csrf_token %} {{ form.as_p }} <input class="btn btn-success" type="submit" value="Add Player"></button> </form> -
Object list into chart labels not working
I have the next view, where I get three lists. 1-dates list 2-questions made by users in a time range. 3-answers of users in the same time range. views.py data_list_question = [] data_list_answer = [] timeline = [] for n in range(24,0,-4): t1 = timedelta(weeks=n) t2 = timedelta(weeks=n-4) c = today-t1 timeline.append(c) a = int(question.objects.filter(published_date__gt=(today-t1), published_date__lt=(today-t2)).count()) data_list_question.append(a) b = answer.objects.filter(published_date__gt=(today-t1), published_date__lt=(today-t2)).count() data_list_answer.append(b) Then I use this values in a scipt in the template like next: chart.html <script type="text/javascript"> $( document ).ready(function() { var ctx = document.getElementById("lineChartstats"); var lineChart = new Chart(ctx, { type: 'line', data: { labels: {{ timeline|date:"j b" }}, datasets: [{ label: "Questions", backgroundColor: "rgba(38, 185, 154, 0.31)", borderColor: "rgba(38, 185, 154, 0.7)", pointBorderColor: "rgba(38, 185, 154, 0.7)", pointBackgroundColor: "rgba(38, 185, 154, 0.7)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(220,220,220,1)", pointBorderWidth: 1, data: {{ data_list_question}} }, { label: "Answers", backgroundColor: "rgba(3, 88, 106, 0.3)", borderColor: "rgba(3, 88, 106, 0.70)", pointBorderColor: "rgba(3, 88, 106, 0.70)", pointBackgroundColor: "rgba(3, 88, 106, 0.70)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(151,187,205,1)", pointBorderWidth: 1, data: {{ data_list_answer }} }] }, }); }); </script> The problem is that the data for each dataset works, however the labels 'timeline' does not work. I do not know how to solve this problem. Thanks … -
Form displays error where there shouldn't be
I have a form which is actually built from 2 forms: UserForm and StudentForm which extends the User model. With the form actually there is no problem whatsoever, but when I try to handle it manually, then I get this error: "This field is required." I filled in all fields but it still appears. I think is related to the fact that I compare my student_ID field with the one from database, and if they don't match, an error like "Wrong student ID." should pop up. And indeed it pops up if values don't match but also the error from above in both cases. Here is my form: class StudentForm(forms.ModelForm): email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'placeholder': "E-mail Address", 'class': 'email'})) name = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': "Name", 'class': 'name'})) surname = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': "Surname", 'class': 'surname'})) student_ID = forms.CharField(required=True, max_length=14, min_length=14, widget=forms.PasswordInput(attrs={'placeholder': "Student ID", 'class': 'std_id'})) photo = forms.ImageField(required=True, widget=forms.FileInput(attrs={'class': 'profile_pic'})) phone = forms.CharField(max_length=15, required=True, validators=[RegexValidator(regex='^[0-9+]+$', message='Not a valid phone number.')], widget=forms.TextInput(attrs={'placeholder': "Phone Number", 'class': 'phone'})) def clean_student_ID(self): id = self.cleaned_data['student_ID'] try: StudentData.objects.get(student_ID=id) except: raise forms.ValidationError("Wrong student ID.") return id class Meta: model = Student fields = ('email', 'name', 'surname', 'phone', 'student_ID', 'photo') -
generate temporary URLs in Django 2 python 3
hi there is one same quetion in stackoverflow with this link: How to generate temporary URLs in Django but the accepted answer code is for python 2 and i converted it to python3 vertion: import hashlib, zlib import pickle as pickle import urllib.request, urllib.parse, urllib.error my_secret = "michnorts" def encode_data(data): """Turn `data` into a hash and an encoded string, suitable for use with `decode_data`.""" text = zlib.compress(pickle.dumps(data, 0)).encode('base64').replace('\n', '') m = hashlib.md5(my_secret + text).hexdigest()[:12] return m, text def decode_data(hash, enc): """The inverse of `encode_data`.""" text = urllib.parse.unquote(enc) m = hashlib.md5(my_secret + text).hexdigest()[:12] if m != hash: raise Exception("Bad hash!") data = pickle.loads(zlib.decompress(text.decode('base64'))) return data hash, enc = encode_data(['Hello', 'Goodbye']) print(hash, enc) print(decode_data(hash, enc)) but it have error : text = zlib.compress(pickle.dumps(data, 0)).encode('base64').replace('\n', '') AttributeError: 'bytes' object has no attribute 'encode' how should i fix this? -
Error while connecting to SQL server through Django
In settings file, I have given SQL SERVER Database connection values like this. DATABASES = { 'default': { 'NAME': 'AdventureWorks2014', 'ENGINE': 'sqlserver_ado', 'HOST': '127.0.0.1', 'USER': '', 'PASSWORD': '', } } Versions: Django v:1.11 Python v: 2.7 django-mssql v: 1.8 pip v:9.0 Development Platform: Visual Studio After the database connection values changes, I have used the command python manage.py makemigrations Here I got the error is , Executing manage.py makemigrations Traceback (most recent call last): File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\manage.py", line 17, in execute_from_command_line(sys.argv) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\core\management__init__.py", line 364, in execute_from_command_line utility.execute() File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\core\management__init__.py", line 338, in execute django.setup() File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\Lib\importlib__init__.py", line 37, in import_module import(name) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\contrib\auth\models.py", line 4, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\contrib\auth\base_user.py", line 52, in class AbstractBaseUser(models.Model): File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\models\base.py", line 124, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\models\base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db__init__.py", line 33, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\utils.py", line 212, in getitem conn = backend.DatabaseWrapper(db, alias) … -
Django Image Upload - Image file not saving
I'm writing a project where you can add photos to a website from a disk or other sites. In jquery I wrote a book marklet where I can add pictures from other site. But I have problem with uploading images from the disc. I wrote model, modelform, views and html file. When I choose a img file in the form all looks OK. I'm moved to image list web page, but there is not file what I whant to upload. Image file not saving. I don't know what I did wrong. Below is my code: models.py class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) url = models.URLField(blank=True) image = models.ImageField(upload_to='images/%Y/%m/%d') description = models.TextField(blank=True) created = models.DateField(auto_now_add=True, db_index=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked', blank=True) total_likes = models.PositiveIntegerField(db_index=True, default=0) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Image, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('images:detail', args=[self.id, self.slug]) class Meta: ordering = ["-image"] forms.py class ImageCreateForm(forms.ModelForm): class Meta: model = Image fields = ('title', 'url', 'description') widgets = { 'url': forms.HiddenInput, } def clean_url(self): url = self.cleaned_data['url'] valid_extensions = ['jpg', 'jpeg'] extension = url.rsplit('.', 1)[1].lower() if extension not in valid_extensions: raise forms.ValidationError('Podany adres URL … -
Whether Django urls.py unittest should be apart from DRF ModelViewSet?
I'm testing in my project some Django REST Framework ModelViewSet views and while I was reading Book - TDD web dev with Python, available at GitHub, I ran into a simple design question -I guess- that would be whether I should use django.urls.resolve or get the same info, for instance, calling: response = self.client.options(reverse_lazy('namespace:view_func_or_pattern_name') from DRF APITestCase and get results of resolver_match in response as I could get with django.urls.resolve. I imagine that it's just a matter of choosing to split tests of urls.py and views.py, as I have seen at this question. Or what else would it be?