Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I force chrome to get the geolocation from GPS module connected to a USB port instead of getting it from router IP?
I'm working on a certain project that uses RasberryPi debian 7 google chrome to open get some work done, the thing is, the server (I made it with django) asks the rasberry pi about its location. RasberryPi's google chrome gets the location from the wifi IP location service. How can I change it to get the location from a GPS module I connected to RasberryPi USB port? I configured the GPS module and it's ready the location well and everythin works fine, now I only need to force chrome to get its location from that GPS module. -
How to count how many clients are in a django channels Group
I would like to know how to count the number of clients in a Django Channels Group in order to restrict the number of connected clients for example. I tried to look in the code of Group object but I had no success. Here my code: import re import json from channels import Group from channels.sessions import channel_session from login import login @channel_session def ws_connect(message): print "Connected" if Group("guis").count() > 10: # NOT POSSIBLE Group("guis").add(message.reply_channel) message.reply_channel.send({'accept': True}) else: message.reply_channel.send({'accept': True}) -
Migration from MySQL to postgresql using Django and Docker - relation "authtoken_token" does not exist
I am trying to migrate my Django project using MySQL database to postgresql with Docker. When I use MySQL everything works fine. I have all in ORM so when I use MySQL I have to create only database and do python manage.py makemigrations and then python manage.py migrate and I get ready database with all relations. As I have mentioned I'm trying to use postgresql database. Server seems to work fine using docker-compose up, but when I send for instance GET request I get: ProgrammingError at /data relation "authtoken_token" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "authtoken... My settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } My docker-compose.yml: version: '3' services: db: image: postgres web: build: . command: python3 PRI/backend/pri/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Dockerfile: FROM python:3.6.1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip3 install -r requirements.txt ADD . /code/ -
Template file path
I'm trying to open and read this html file with in my django project, however i'm getting this [Errno 2] No such file or directory: 'test.html'. html = 'test.html' open_html = open(html, 'r') soup = BeautifulSoup(open_html, "html5lib") open_html.close() But the template path seems to work fine when rendered template = 'test.html' context = { } return render(request, template, context) TEMPLATES = [ 'DIRS': [os.path.join(BASE_DIR, "templates")], ] I know my templates are suppose to go into my apps folders, however i like to keep them in one folder when developing and debugging. -
Django Rest Framework Authentication Issues
I am a newbie in Django. I had created REST API using DRF. My Django has 3 apps. So now I want to apply authentication. I have seen much help but I am not to apply the authentication properly. I also want that the model should be attached to the user. So that one user can't see another user entries. Can anyone help me in telling how to implement this a little detailed? Thanks in advance. Will be a great help if someone answers. -
Cannot run django-simple-blog due to missing table `simpleblog_post`
I tried to run django-simple-blog with Django 1.11. I started only with this app and set the setting as described in https://github.com/drager/django-simple-blog. I added 'django.contrib.humanize' in INSTALLED_APP to deal with the template error at "load humanize" and a new line SITE_ID = 1. However I got these error message OperationalError at /blog/ no such table: simpleblog_post Running the ./manage.py migrate and ./mange.py makemigrations does not create a new table for simpleblog_post in my database. I can login in the admin site, however I cannot save a new post since the site needs this table. How can I fix this issue? -
How to save IP of user after submitting the django custom form
I wrote my own form for editing of profile and need to save ip of user, who edit profile, but not really understand how to do this. I know, that ip we can get from request.META['REMORE_ADDR'] but where to put this and how to save to my db... Will be very glad if you could help. models.py class Profile(models.Model): user = models.OneToOneField(User, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField() biography = models.TextField() contacts = models.CharField(max_length=200) ip_address = models.GenericIPAddressField(null=True) forms.py class UserEditProfile(forms.ModelForm): first_name = forms.CharField( max_length=30) last_name = forms.CharField( max_length=30) date_of_birth = forms.DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES)) biography = forms.Textarea() contacts = forms.CharField() def __init__(self, *args, **kw): super(UserEditProfile, self).__init__(*args, **kw) self.fields['first_name'].initial = self.instance.first_name self.fields['last_name'].initial = self.instance.last_name self.fields['date_of_birth'].initial = self.instance.date_of_birth self.fields['biography'].initial = self.instance.biography self.fields['contacts'].initial = self.instance.contacts self.fields.keyOrder = [ 'first_name', 'last_name', 'date_of_birth', 'biography', 'contacts' ] def save(self, *args, **kw): super(UserEditProfile, self).save(*args, **kw) self.instance.first_name = self.cleaned_data.get('first_name') self.instance.last_name = self.cleaned_data.get('last_name') self.instance.date_of_birth = self.cleaned_data.get('date_of_birth') self.instance.biography = self.cleaned_data.get('biography') self.instance.contacts = self.cleaned_data.get('contacts') self.instance.save() class Meta: model = Profile fields = ( 'first_name', 'last_name', 'date_of_birth', 'biography', 'contacts' ) exclude = ['user', 'ip_address'] view.py def edit_profile(request): user = Profile.objects.get(id=request.user.id) if request.method == "POST": form = UserEditProfile(request.POST, instance=user) if form.is_valid(): form.save(commit=False) return redirect('profile') else: form = UserEditProfile(instance=user) args = {'form': form} … -
Django save/ store queryset to be used in different views
So I'm not really sure how to call this, and thus not really able to find a solution... Let's say I have two views created, "CheckInsListView" and "CheckOutsListView". These are being filtered on the status = "CI" or status = "CO". Next would be that I'd like to show the results for a user given date, so I'd make a form "DateSelection" and use a "get_queryset" to match the date and show the results. Now the problem is, when I switch views, the user given date get's lost. Would there be a way to keep the date saved/ stored somwhere? So the user can check the "Check-ins" and "Check-outs" for a particular date without selecting the date twice... #views.py class CheckInsListView(generic.ListView, FormMixin): form_class = DateSelection model = Orders paginate_by = 10 queryset = Orders.objects.filter(status='CI') template_name = 'check-ins.html' class CheckOutsListView(generic.ListView, FormMixin): form_class = DateSelection model = Orders paginate_by = 10 queryset = Orders.objects.filter(status='CO') template_name = 'check-outs.html' Thanks for the help! -
Multiple field foreign key in django
I have two models in django with definitions below. CreativeStatus model : class CreativeStatus(models.Model): creative_id = models.CharField(max_length=500, primary_key=True) advertiser_id = models.CharField(max_length=100, primary_key=True) exposure_level = models.CharField(max_length=125) modified_on = models.DateTimeField() modified_by = models.CharField(max_length=100) class Creative(models.Model): id = models.AutoField(primary_key=True) advertiser_id = models.ForeignKey(RtbdCreativeStatus, on_delete=models.CASCADE) creative_id = models.ForeignKey(RtbdCreativeStatus, on_delete=models.CASCADE) country_id = models.IntegerField() adm = models.CharField(max_length=255, null=True, blank=True) sample_url = models.CharField(max_length=500) landing_page = models.CharField(max_length=500, null=True, blank=True) html = models.CharField(max_length=500) creative_attributes = models.CommaSeparatedIntegerField(max_length=150, null=True, blank=True) advertiser_domains = models.CharField(max_length=500) description = models.CharField(max_length=500, null=True, blank=True) created_on = models.DateTimeField(auto_now=True, auto_now_add=True) creative_type = models.CharField(max_length=50, null=True, blank=True) demand_source_type_id = models.IntegerField() revalidate = models.BooleanField(default=False) (creative_id, advertiser_id ) combination is unique in my CreativeStatus table . I want that combination to be my foreign key for Creative table. I tried adding it but i get this error . 1)How do i achieve this join with two key combination as my foreign key . 2)What should be my query to fetch all the creatives with their status from CreativeStatus table . -
Django ForeignKey Big lsit when try to adding
since short time im code in python and i have problem: I have models: class Employee(models.Model): BadgeBarcode = models.CharField(max_length=40) ManagerName = models.CharField(max_length=40) EmployeeName = models.CharField(max_length=40) UserLogin = models.CharField(max_length=40) ShiftPattern = models.CharField(max_length=40) def Add(self): self.save() def __str__(self): return self.EmployeeName class Permission(models.Model): Permission_Name = models.CharField(max_length=40) Priority = models.IntegerField(unique=True) def Add(self): self.save() def __str__(self): return self.Permission_Name class EmployeePermission(models.Model): Employee = models.ForeignKey(Employee) Permission = models.ForeignKey(Permission) Have = models.BooleanField() def Add(self): self.save() def __str__(self): return self.Employee So as you can see i want connect Model Employee and Permission and its all working fine..but i have like 7k records of employees and when i want add new permission for employee, list of employees is to big and page is working like s... its any way to fix that or change list for search button or something? -
How to Include Add, Edit, and Delete Buttons for OneToMany Foreign Key Relation Admin Form?
I am trying to get the add, delete, and edit buttons to display for my one-to-many relationship. So far, the add button only shows up, but the edit or delete button is not there... How can I get the delete and edit button to show up? I require that all three show up. Thanks. Here is the source code (simplified...): class ClassName(models.Model): name = models.CharField(max_length = 256) def __unicode__(self): return self.name class Class(models.Model): rel_name = models.ForeignKey(ClassName) For my computer, with Python 2.7.13 x86 with Django 1.6, the Plus sign only shows up (for adding a new ClassName)... -
How to eliminate inefficiency of django query in a loop?
How can the following code be made more efficient (e.g., how to replace the loop with a query)? def get_question(datetime_now, questions_queryset, user): best_schedule = None best_question = None # HOW TO ELIMINATE THE FOLLOWING LOOP AND REPLACE WITH A QUERY? for question in questions_queryset: try: schedule = (Schedule.objects .filter(question=question, user=user) .latest(field_name='datetime_added') except ObjectDoesNotExist: schedule = None if (schedule and (schedule.date_show_next >= datetime_now) and ((not best_schedule) or (schedule.datetime_added >= best_schedule.datetime_added))): best_schedule = schedule best_question = question return best_question models.py from django.contrib.auth.models import User from django.db.models import DateTimeField, ForeignKey, Model, TextField class Question(Model): question = TextField() class Schedule(Model): datetime_added = DateTimeField(auto_now_add=True) datetime_show_next = DateTimeField(null=True, default=None) question = ForeignKey(Question) user = ForeignKey(User, null=True) -
Easy-thumbnails unwanted image rotation
I faced with such thing using easy-thumbnails: users upload different photos on my website and sometimes these photos are not right oriented. For example, user uploaded a photo. And when the photo is thumbnailed, it displays good, but if I try to display origin image - it is rotated. And it is rotated wrong. Is there a solution to process image but not to resize in easy-thumbnails Or I googled such solution: run images with jhead before upload <img> unwanted photo rotation Of course, I can`t say users to run the image with this program, but I need to integrate it into my django app. As for me, It would be better to make thumbnail without cropping, but, as I understand, crop attribute is mandatory in easy-thumbnails. What do you suggest? Thanks a lot! -
django table save (weekly schedule)
I'm making a fitness website using django, python. I want to put a weekly schedule calendar for fitness trainer. After clicking one member and selecting one table box, the information of member is inserted in table. here's my page But, I wonder how the table can be maintained when I reload the website. So, I think I should save the data in table to DB. But I don't know how I save the table to DB. Any advice will be very helpful to me! Thank you -
Django - run a function every x seconds
I'm working on a Django app. I have an API endpoint, which if requested, must carry out a function that must be repeated a few times (until a certain condition is true). How I'm dealing with it right now is - def shut_down(request): # Do some stuff while True: result = some_fn() if result: break time.sleep(2) return True While I know that this is a terrible approach and that I shouldn't be blocking for 2 seconds, I can't figure out how to get around it. This works, after say a wait of 4 seconds. But I'd like something that keeps the loop running in the background, and stop once some_fn returns True. (Also, it is certain that some_fn will return True) -
Can't load static files after cloning a Django project
I know this question has been asked a lot but I really can't figure out why my static files won't be loaded. I cloned a project from a friend(no idea if that has anything to do with it) and when try to link to the static files I keep getting the 404 error in the debug console on Chrome. header in my HTML {% load staticfiles %} {% load static %} <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <!--http://ianlunn.github.io/Hover/--> <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link href="{% static 'css/hover.css' %}" rel="stylesheet" media="all"> <link href="css/hover.css" rel="stylesheet" media="all"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <link rel="stylesheet" href="{% static 'css/bootstrap-theme.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap-override.css' %}"> </head> import os import datetime # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DJANGO_DIR = os.path.dirname(BASE_DIR) PROJECT_DIR = os.path.dirname(os.path.dirname(DJANGO_DIR)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '($$t71e-ofj&h!2qh(7dwpq*ixft5y0#h&&t%*tesriebrn%ro' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "django.contrib.sites", #3rd Party APPS 'rest_framework', 'rest_framework_jwt', 'cuser', #https://github.com/tmm/django-username-email "pinax.stripe", #Custom … -
jango.db.utils.OperationalError: no such table: bookmarks_mytag
I am getting django.db.utils.OperationalError: no such table: bookmarks_mytag trying to install a django project. The repo is at http://bitbucket.org/codyc54321/bookwormbud.git We did touch db.sqlite3 python manage.py migrate and it blows up: (bookwormbuddy) john@john-Precision-3510:~/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7f7adbb5e140> Traceback (most recent call last): File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookwormbud/urls.py", line 24, in <module> url(r'^', include('bookmarks.urls', namespace='bookmarks')), File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/urls.py", line 4, in <module> from bookmarks import … -
django html inicial text in form
I have a django form with a forms.Textarea that contains html. If I want the user to see the text he has written whenever he wants to edit the html, how can I fill the <textarea> without django showing all the <p>s and the <brs? I am using TinyMCE in the fron, just a javascript library for rich text editing. How can I fill this field with django initial values? -
How to get the template path in the view django
So i'm trying to get the template path in in my view, is there a dynamic way of doing this because at the moment i am hard coding the path. html = 'C:/Users/user/Desktop/project/src/templates/project.html' -
How to filter queryset with exclude and ForeignKey
I have two models class Entry(models.Model): properties = here class ReadedEntries(models.Model): entry = models.ForeignKey(Entry, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) How can I get the no readed entries from a user? I try: not_looked_videos = Entry.objects.exclude(ReadedEntries.objects.filter(user=request.user)) but I get: ValueError: need more than 0 values to unpack -
Autofill loginuser in admin on field in model DJANGO
I'm trying to get the current login user in admin, i need to put the user in a field called 'doctor' in the model Medicard_rd. This is my model: class Medicard_rd(models.Model): Titulo = models.CharField(max_length=40, default='') hospital = models.CharField(max_length=30, default='') area = models.CharField(max_length=30) paciente = models.ForeignKey('auth.User', related_name= 'paciente', default = '') doctor = models.ForeignKey('auth.User', editable=False, null=True, blank=True, default='') fecha_creacion = models.DateTimeField(default=timezone.now) Telefono = models.CharField(max_length=10, default='') Imagen = models.FileField(upload_to='%Y/%m/%d', blank = True, default='') def publish(self): self.fecha_creacion = timezone.now() self.save() propia de Django save(). def __str__(self): return self.Titulo + " " + " " + self.paciente.username I want to autofill the field doctor. I try this in the admin.py: class PostAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if not change: obj.doctor = request.user obj.save() But this doesn't work. I got this in the database when i save the model: Database Medicard_rd table -
Django - "Relation Does Not Exist" on Fresh Migrations
I'm trying to deploy my app, but when running migrate.py for the first time, I get an error explaining that a "relation does not exist". Of course it wouldn't, because I haven't been able to migrate yet! Looking through the traceback, it seems to be getting tripped up in my managers.py file, but I can't understand why my managers would be getting in the way? pyto(genius) 00:24 ~/genius (master)$ python manage.py migrate Traceback (most recent call last): File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "Inventory_purchase" does not exist LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_comm and_line utility.execute() File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 342, in execute self.check() File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 62, in _run_check s issues.extend(super(Command, self)._run_checks(**kwargs)) File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) res = instance.__dict__[self.name] = self.func(instance) File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File … -
Migration from MySQL to postgresql using Django and Docker - relation "authtoken_token" does not exist.
I am trying to migrate my Django project using MySQL database to postgresql with Docker. When I use MySQL everything works fine. I have all in ORM so when I use MySQL I have to create only database and do python manage.py makemigrations and then python manage.py migrate and I get ready database with all relations. As I have mentioned I'm trying to use postgresql database. Server seems to work fine using docker-compose up, but when I send for instance GET request I get: ProgrammingError at /data relation "authtoken_token" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "authtoken... My settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } My docker-compose.yml: version: '3' services: db: image: postgres web: build: . command: python3 PRI/backend/pri/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Dockerfile: FROM python:3.6.1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip3 install -r requirements.txt ADD . /code/ -
Django ContentFile get_available_name() got an unexpected keyword argument 'max_length'
When I try to save an image object to an ImageField I get the following error: get_available_name() got an unexpected keyword argument 'max_length' The code looks like this: imagen_url = form.cleaned_data['imagen_url'] respuesta = requests.get(imagen_url) imagen = Image.open(StringIO(respuesta.content)) stringio_obj = StringIO() imagen.save(stringio_obj, format="JPEG") final_image = stringio_obj.getvalue() carta.creador = request.user carta.ultima_revision = datetime.today() carta.save() print("carta_id: %s" % carta.id) # Works correctly till here archivo_imagen = ContentFile(final_image, "0_" + carta.nombre) # Guarda la original con un 0 adelante carta.imagen_base.save("0_" + carta.nombre, archivo_imagen, save=True) When I try ty to save the ContentFile object to the model`s ImageField, it doesn't work. It used to work in a lower version of Django, but since I shifted to django 1.10, it stopped working. The model is simple, it looks like this: def ubicar_img_base(instance, filename): nombre_archivo = "0_" + slugify(instance.nombre) + ".jpeg" path = "/".join([instance.grupo.nombre, nombre_archivo]) return path class CartaMagicPy(models.Model): imagen_base = models.ImageField(null=True, upload_to=ubicar_img_base) Any advice will help -
Django: Specific model's links redirect to a non-admin view instead of the default page listing that model's information
I'm working on an app which supports user image uploads. Uploading images to a model works fine; I have a working Upload view which renders a form that handles these uploads. I want to be able to see and manage the model's fields from the admin interface, which leads to my question specified in the title. Using another model (Topic) as an example, what I expect is for this admin page to show up when I click its link on the admin site. But when I click the link for the model ImageUpload, the non-admin Upload view shows up instead. The second link shows that an admin-site url is rendering what I expect to be a non-admin-site page. Some of what I have currently: views.py: from django.views.generic.edit import CreateView from django.urls import reverse_lazy from django.utils.decorators import method_decorator class Upload( CreateView ): form_class = forms.ImageUploadForm success_url = reverse_lazy( 'test_app:index' ) template_name = 'test_app/upload/index.html' @method_decorator( login_required ) def dispatch( self, request, *args, **kwargs ): return super( Upload, self ).dispatch( request, *args, **kwargs ) models.py: class ImageUpload( models.Model ): title = models.CharField( max_length = 50 ) image = models.ImageField( upload_to = 'user_img/' ) def __str__( self ): return str( self.id ) project urls.py: …