Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: 'abc' object is not subscriptable
I am trying to display a chart in my django app using this link Integrate graphs in Django Here is my Views.py def json_example(request): return render(request, 'classroom/teachers/json_example.html') def chart_data(request): dataset = DispatchPlan.objects.all() print("dataset is ", dataset) # port_display_name = dict() # for port_tuple in Passenger.PORT_CHOICES: # port_display_name[port_tuple[0]] = port_tuple[1] chart = { 'chart': {'type': 'pie'}, 'title': {'text': 'Titanic Survivors by Ticket Class'}, 'series': [{ 'name': 'Embarkation Port', 'data': list(map(lambda row: {'name': row['weight'], 'y': row['route_distance']}, dataset)) }] } return JsonResponse(chart) When I run the app it shows the following error: TypeError: 'DispatchPlan' object is not subscriptable in this line 'data': list(map(lambda row: {'name': row['weight'], 'y': row['route_distance']}, dataset)) I am guessing its because I am not mapping it correctly, How do I solve this ? -
Django : Integrity error while authenticating from Google. Duplicate entry shown
I am trying to login through google in my django application . I am getting some integrity error while trying to save the user. The error is - IntegrityError at /auth/complete/google-oauth2/ duplicate key value violates unique constraint "pd_user_master_user_id_key" DETAIL: Key (user_id)=(55) already exists This is the function i'm using to save a default profile of the user through it's ID in the User Profile Model. - def save_profile(backend, user, response, *args, **kwargs): profile = UserProfile(user_id=user.id) #print(request.user.id) profile.contact_no=1234567890 profile.department=1 profile.status=0 profile.save() return {"profile": profile} And this is the Pipeline as recommended - SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'pd.views.Users.save_profile', # <--- set the path to the function 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) In DB, a user is created in the auth_user table, but no object created in social_auth_usersocialauth table and no profile created for the same. Can anyone clear this out what is happening behind the scenes ? -
Django, filter foreign models in admin
I'm trying to view filters in admin of two Models related with foreign keys. class Distributor(): product = ForeignKey(Product) [...] class Products(): [...] So class Distributor product_id is related with Product field called id Now in admin.py class DistributorDropdown(DropdownFilter): title = _('Products') class DistributorAdmin(admin.ModelAdmin): list_filter = ( 'status', ('products_id', DistributorDropdown) ) admin.site.register(Distributor, DistributorAdmin) and, in filters.py: class DropdownFilter(AllValuesFieldListFilter): template = 'admin/dropdown_filter.html' -
Unable to use token authentication as the only authentication class in django-rest-knox
I am using django-rest-knox for user authentication and have knox.auth.TokenAuthentication as the only authentication class. According to documentation, when you use token authentication as the only authentication method then you have to override the inbuilt LoginView of knox. I have followed the same method but it does not seem to work out. views.py class LoginInterestedUserAPI(LoginView): def get_user_serializer_class(self): return LoginInterestedUserSerializer def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginInterestedUserAPI, self).post(request, format=None) serializers.py class LoginInterestedUserSerializer(serializers.ModelSerializer): class Meta: model = InterestedUser fields = ('email', 'password') def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Unable to log in with the provided credentials") urls.py ... urlpatterns = [ path('login', views.LoginInterestedUserAPI.as_view()), ] When I go to the url /api/login, I am not getting email and password field to enter my credentials and getting the following output:- "detail": "Authentication credentials were not provided." -
limit foreignkey's field choices in django admin
i have 4 simple model : model.py class State(models.Model): name = models.CharField(max_length=20) class County(models.Model): name = models.CharField(max_length=30) state = models.ForeignKey(State, on_delete=models.CASCADE) class District(models.Model): name = models.CharField(max_length=30,null=True, blank=True) county = models.ForeignKey(County,on_delete=models.CASCADE, null=True, blank=True) class Teacher(model.Model): name = models.CharField(max_length=20) state = models.ForeignKey(State, on_delete=models.CASCADE) county = models.ForeignKey(County,on_delete=models.CASCADE, null=True, blank=True) district = models.ForeignKey(District,on_delete=models.CASCADE, null=True, blank=True) admin.py: @admin.register(Teacher) class TeacherAdmin(admin.ModelAdmin): list_display = ['name','state','county','district,] my issue is in Teacher admin page for field county and district all the county and district display in drop down select box. what i want is just county and district of teacher's state display . thank you -
Django admin incorrect behaviour
We are using Django 1.11 as backend and managing tool for mobile application resources. One of my coleagues (on OS: Windows 7) recently started to have problems like: cannot add new one2many items in inlines (missing + sign) cannot lookup new item from raw_id_fields - this instead of popup window redirects to url in the same tab and shows blank page when clicked on "check all" box, only this very box is checked, not the rest of the records as expected I tried on my computer with the same (super)user, everything worked just fine. It seemed that he may have problems with javascript so we've tried run simple alert from js console and it worked. Turning off the antivirus did not help either. As this happens in all browsers it is clear that it is a problem of the computer, not django itself. But it worked a month ago so I would like to know what might be the cause and how to get rid of this behaviour. -
Werid behavior of django model save method. "(1048, "Column 'created_at' cannot be null")" on field that has auto_now_add=True
When I am trying to save (edit) my model based form, django shows (1048, "Column 'created_at' cannot be null"), but created_at has auto_now_add=True. Here's the code: View: def post(self, request, track_id): track_form = forms.AddTrack(request.POST, request.FILES) if track_form.is_valid(): record = track_form.save(commit=False) record.id = track_id record.author = request.user record.save() # Let's let template know that new track was created! #request.session['track_created'] = True return HttpResponseRedirect("/mytrack/15") else: return HttpResponseRedirect("/nothing/nothing/nothing/") Model: class Track(models.Model): title = models.CharField(max_length=40, null=True) description = models.CharField(max_length=500, null=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) miniature = models.ImageField(upload_to='images/track', default="defaults/default.png", validators=[validate_miniature_file_extension]) audio_or_video = models.FileField(upload_to='audio_and_video/', default="file_not_found", validators=[validate_track_file_extension]) favourite = models.BooleanField(default=False) def __str__(self): return self.title URL: path('track/<int:track_id>', track.as_view(), name='track'), -
django 2.2 "user-defined aggregate's 'finalize' method raised error"
//Django 2.2.2 //sqlite3 I am passing various statistical values to Django template with Django Aggregate. Avg, Count are working well. But Variance is not working and gives me OperationError. user-defined aggregate's 'finalize' method raised error Variance is working when I wrote in models method. But in views.py, not working. I do not know what the difference between these two is.. views.py def project_report(request, pk): project = get_object_or_404(ProjectModel.objects, pk=pk) subject = project.subject_for_project.filter(status='on', party_status='join').annotate(feel_avg=Avg('datamodel__feeling'), pain_avg=Avg('datamodel__pain'), side_count=Count(Case( When(datamodel__flag='side', then=1), output_field=IntegerField(), )), # this part is not working pain_variance=Variance('datamodel__pain') ) print(subject) context = { 'project':project, 'subject':subject, } return render(request, 'project/project_report.html, context) models.py class ProjectModel(models.Model): project_name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField(choices=STATUS, max_length=3, default='on') class SubjectModel(models.Model): random_num = models.CharField(max_length=100, blank=True, unique=True) project = models.ForeignKey(ProjectModel, on_delete=models.CASCADE, related_name='subject_for_project') created_by_admin_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) party_status = models.CharField(choices=(('join', 'Join'), ('break', 'Break')), default='join', max_length=5) status = models.CharField(choices=STATUS, max_length=3, default='on') class DataModel(models.Model): user_id = models.ForeignKey(SubjectModel, on_delete=models.CASCADE) drug = models.CharField(choices=DRUG, max_length=3, blank=True, null=True) side_effect = models.CharField(max_length=50, blank=True, null=True) side_effect_more = models.CharField(max_length=255, blank=True, null=True) feeling = models.PositiveSmallIntegerField(choices=FEELING, blank=True, null=True) pain = models.PositiveSmallIntegerField(blank=True, null=True) date = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) flag = models.CharField(choices=FLAG, max_length=6) According to the django 2.2 release notes, I read that the sqlite environment also … -
Django QuerySet values() include ForeignKey field
Django 2.2 provides a method values() on QuerySet to convert queryset to dictionary I'm using the same in my application as new_plan_quota = PlanQuota.objects.filter( **filter_query ).select_related('quota') new_plan_quota_values = list(new_plan_quota.values()) Which generates a json string containing all fields of PlanQuota model. How can I add fields of Quota model as well in the json? -
Exception in django-main-thread (manage.py runserver)
When I try to run server, I get this following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/josephshenouda/anaconda3/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Users/josephshenouda/anaconda3/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Users/josephshenouda/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/josephshenouda/anaconda3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/josephshenouda/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/Users/josephshenouda/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/Users/josephshenouda/anaconda3/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/josephshenouda/anaconda3/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/josephshenouda/anaconda3/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/josephshenouda/anaconda3/lib/python3.7/site-packages/django/urls/resolvers.py", line 399, in check messages.extend(check_resolver(pattern)) File "/Users/josephshenouda/anaconda3/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/josephshenouda/anaconda3/lib/python3.7/site-packages/django/urls/resolvers.py", line 399, in check messages.extend(check_resolver(pattern)) File "/Users/josephshenouda/anaconda3/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/josephshenouda/anaconda3/lib/python3.7/site-packages/django/urls/resolvers.py", line 325, in check warnings = self._check_pattern_name() File "/Users/josephshenouda/anaconda3/lib/python3.7/site- packages/django/urls/resolvers.py", line 333, in _check_pattern_name if self.pattern.name is not None and ":" in self.pattern.name: TypeError: argument of type 'function' is not iterable I never had any problems before, I'm wondering if I accidentally changed something. Thanks. -
am trying to make form using foreign, can i have some suggest using django
class DemoForm(forms.ModelForm): class Meta: model=SimpleDemo fields=['First_name','Last_name'] class PostForm(forms.ModelForm): class Meta: model=Post fields = ['Enter_Message',] -
request.user in DRF Views vs Django Views
I'm trying to get the authenticated user in the APIs. Here's the code:- DRF View class API(CsrfExemptMixin, generics.CreateAPIView): authentication_classes = [] serializer_class = SomeSerializer def post(self, request): print(request.user.id) # None DRF View from django.views import View class API(CsrfExemptMixin, View): authentication_classes = [] def post(self, request): print(request.user.id) # prints id of the user. Why am I getting different responses in the 2 different scenarios? Following are my settings. AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', # Needed to login by email 'modules.profile.backend.EmailBackend' ) REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'EXCEPTION_HANDLER': 'modules.utils.exception_handler.custom_exception_handler', 'PAGE_SIZE': 10, } -
Connecting Microsoft sql server with Django App
I want to connect the Microsoft SQL server with my Django application. In Microsoft SQL management studio I am creating one database then I am creating Login with a password and then I am creating user using this Login option. In my settings file of Django application, I am providing my database name and user name and password of Login that I have created. I think I am doing something wrong. Whenever I am trying to connect then it is showing user and password credentials in not correct. There is no option of giving the password to the user. While creating Login I am providing a password. I have just started using Microsoft SQL server. In postgres, I use to create one user and database and give privileges of the database to that user then I use to pass credentials in my settings.py of Django app. I am trying to connect Microsoft SQL server with Django. DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'ankur_database', 'USER': 'ankur_user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'unicode_results': True, }, } What I should provide in the password and should I provide 'localhost' in HOST. … -
Are there any links that could help me build a Chatbot using Django in Python
I'm trying to build a Chatbot using Django in python. Are there any suggestions or documentation that can help me. I need to start from scratch since i have never worked with Django before. -
How to format float values in django template?
I want to format float values in my django template like this: 125000 => 125k 125,000,000 => 125M Do I have to use any custom template tag for this or django already has one? Any idea? -
How to display parameter from URL to template in class based views in Django
View below prints list of all posts done by certain user. User was a parameter taken from the URL and is working fine. How do I extract **kwarg -> 'username' and display it on the template as a variable? Things commented out in the code have been tried. views.py class AuthorPostIndexView(ListView): model = Person template_name ='authorpostindex.html' context_object_name = 'author_post' #1) #date=request.GET.get('username','') -> wrong as varibales in classes #is not possible? #-> this works fine: def get_queryset(self): username = self.kwargs['username'] queryset = Person.objects.get(username=username).post.all() return queryset, (username,'') #-> attempts to extract username kwarg: #2) # def get_context_data(self, **kwargs): # context = super(AuthorPostIndexView, self).get_context_data(**kwargs) # context['username'] = self.username # return context #3) # @property # def username(self): # return self.kwargs['username'] expected result template.html <h1>{{username}}</h1> -> username from the URL should be displayed Error messages: 1)'request' is not defined (shell) 2) 'AuthorPostIndexView' object has no attribute 'username' (template) 3) Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post\/(?P[0-9]+)$'] (template) -
How to get REMOTE_USER working with Django in Pycharm and Firefox for Windows Authentication?
I'm setting up a django app which uses windows authentication (LDAP) to populate users in the database. It works but doesn't sign in automatically. I've followed a bunch of guides but no luck. Can't see REMOTE_USER in the request on my django server. Already tried: https://thycotic.force.com/support/s/article/Configuring-Firefox-for-Integrated-Windows-Authentication - under network.negotiate-auth.delegation-uris I set it to: 'http://127.0.0.1:8000/, ldap://xx.example.com' Was unsure if it's supposed to be web app server (local) or the ldap server. Ended up setting all the URI fields in about:config to this to try cover all cases. In django I followed this https://docs.djangoproject.com/en/2.2/howto/auth-remote-user/ - Set MIDDLEWARE and AUTHENTICATION_BACKENDS 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.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend', 'home.authentication.earlston_ad', I'd expect request.META['REMOTE_USER'] to exist and have users LDAP info. But this field doesn't exist. -
How can i fix 'Manager isn't accessible via Weekstaat instances'?
I am trying to change status to 'ingedient'. When I click the 'indienen' button this error appears: Manager isn't accessible via Weekstaat instances. How can I fix this error?------------ this is my index.html <form action="{% url 'weekstaat-indienen' Weekstaat.id %}" method=POST> {% csrf_token %} <button id="approve-btn" type="submit">Approve</button> </form> </td> <td class="text-center"> <button type="button" class="read-Contract btn btn-sm btn-primary" data-id="{% url 'read_Weekstaat' Weekstaat.id %}"> <span class="fa fa-eye"></span> </button> <button type="button" class="update-Contract btn btn-sm btn-primary" data-id="{% url 'update_Weekstaat' Weekstaat.id %}"> <span class="fa fa-pencil"></span> </button> </td> </tr> {% endfor %} </tbody> </table> {% else %} <p class="text-primary">U heeft nog geen Weekstaat</p> {% endif %} </div> </div> </div> </div> </div> <script type="text/javascript"> function bevestigIndienen(){ if(confirm('U staat op het punt een weekstaat in te dienen. Weet u het zeker?') != true){ document.getElementById('formulierIndienen').action = ''; window.location.href = "{% url 'home' %}"; } } this is my view.py def indienen(request, id): global Weekstaat Weekstaat = Weekstaat.objects.get(pk=id) Weekstaat.Status = 'Ingedient' Weekstaat.save() return redirect('../../weekstaat') this is my model.py class Weekstaat(models.Model): id = models.AutoField(primary_key=True, null=False, blank=False) status = models.CharField(max_length=11, choices=STATUS_CHOICES, default='Niet ingediend',) jaar = models.ForeignKey(Jaar, default=datetime.now().year, null=False, blank=False,on_delete=models.CASCADE) week = models.ForeignKey(Week, default=date.today().isocalendar()[1], null=False, blank=False,on_delete=models.CASCADE) werknemer = models.ForeignKey(User, related_name='weekstaat_werknemer', null=False, blank=False, default=1,on_delete=models.CASCADE) maandag = models.FloatField(null=True, blank=True, default=0) dinsdag = models.FloatField(null=True, blank=True, default=0) woensdag … -
Ajax getting error parse error and Unexpected token < in JSON at position 0?
please look into below code AJAX FUNCTION <script> $(document).ready(function() { $("#id_module").on('change', function(){ var mod1 = $(this).val(); alert(mod1); $.ajax({ url: 'submodule/'+ mod1, type:'GET', dataType:'json', success: function(response){ alert(JSON.stringify(response)); submod=response['submod']; alert(submod); $('#submodule').empty(); $("#submodule").prepend($('<option>', { value: '', text: '-- Select Sub Module Type --' })); $.each(submod, function(ind){ $("#submodule").append($('<option>', { value: submod[ind]['sub_module'], text: submod[ind]['sub_module'] })); }); $('#submodule').selectpicker("refresh"); } }); }); }); </script> My Django -- URL: from django.urls import re_path from django.conf import settings from django.conf.urls.static import static from E_Ticketing import views urlpatterns = [re_path(r'^eForm/report$',views.reports{'template_name':'reports.html'},name='report'),re_path(r'^eForm/resolution$',views.resolutionForm{'template_name':'Resolution_Form.html'},name='resolution'), re_path(r'^eForm/assign$',views.assignForm,{'template_name':'assign_form.html'},name='assign'), re_path(r'^eForm',views.eticket, {'template_name':'e_ticket_form.html'},name='eticket'), re_path(r'^eForm/submodule/(?P<n_moduleid>\d+)$',views.submodule,name='submodule'), re_path(r'^eForm/fillemp/(?P<n_empid>\d+)$',views.fillemp,name='fillemp'), ] if settings.DEBUG: urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) My Django --Views: def submodule(request,n_moduleid): try: if request.method=='GET': submod=[] submod=TblTxEticketdetails.objects.using('ETicketing').values('sub_module').filter(Q(module_id=n_moduleid)).distinct() else: messages.error(request, 'Error Occurred!!!') data = {'submod': list(submod)} return JsonResponse(data, safe=False) except Exception as e: messages.error(request, "Error Occured!!!") i have gone through all of my code and i couldn't find where my code is wrong. while running, alert box appears but it does not go to ajax function. i need little help please!!! i am getting error in this way text status: parsererror eForm:1676 error: SyntaxError:Unexpected token < in JSON at position 0 -
NetworkError when attempting to fetch resource
I am trying to send patch request but it is sending me "TypeError: NetworkError when attempting to fetch resource." this error only in firefox . it works fine in Google Chrome. I have already tried adding permission to menifest.json but it still gives me the error -
How to send password reset email embedded with images?
My requirement is to send the reset password email (the email that has reset link) with header & footer images embedded in that email along with custom email body message. I'm able to successfully customize other parts of forgot-reset password sections of django except sending custom email with embedded images. I have created custom registration process and in its view function, I was able to send verification link email with embedded images using MIMEMultipart & MIMEImage. But I'm unable to find the exact function where in forgot password section the email function should be overriden. Could anyone please guide me in correct direction? The link that I referred for my customization work is given below. https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html Thanks in advance! -
Use differents configs in CKEDITOR with Django
In my Django back end, I have a full toolbar. However, I want to propose Ckeditor to my users with a minimum of functionnalities. The problem is, I don't know how to this. I tried to override my config : <script type="text/javascript"> CKEDITOR.replace( 'default', { toolbar : 'Basic', }); </script> But nothing happened, even after removing my browser cache. This is my Django settings : CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 500, 'width': 1500, }, } -
Django CSRF verification failed with csrf_except decorator
I have a view function: @csrf_exempt def login(request): # Get data from client data = json.loads(request.body.decode('utf-8')) email = data.get('email') password = data.get('password') user = authenticate(username=email, password=password) When I request a post method from that function, I get an error: I also have another view function for registration: @csrf_exempt def register(request): # Get data from client data = json.loads(request.body.decode('utf-8')) first_name = data.get('first_name') last_name = data.get('last_name') address = data.get('address') city = data.get('city') state = data.get('state') postal_code = data.get('postal_code') contact_number = data.get('contact_number') birthday = data.get('birthday') email = data.get('email') password = data.get('password') But when I call that register with post method, I don't get any error, why am I getting the error only in login view? -
Allow user to make post, but just once
I just confusing how to combine CreateView with some rule that do auto redirect authenticated user to existing object they have made before(not success_url, because it will redirect if you try to access CreateView URL again). it similar like if you have made 1 tweet, then sometime after that, you try to access CreateView url it will auto redirect you to your first tweet only, except you have been delete that first tweet. -
How to fix showing an image through ImageField from a model object (Django)?
I'm creating a website for an e-sports team where I want the administrators to have the option in backoffice (django admin) to add their collaborating partners. The model is gonna have an image, a link and a description. I know this question is being asked a lot - but trust me I've looked and tried for hours, there must be some minor issue that's been interrupting me. I can get all the objects to show, with working links and descriptions, but the image wont show up. I sat all day yesterday trying to fix stuff. I've tried changing the MEDIA_ROOT and MEDIA_URL as well as using different strategies that I've scouted on the internet and here on StackOverflow. But I can't get it to work. **# My model (models.py)** class Partner(models.Model): """ Adds a partner with specific information """ ... partner_image = models.ImageField(upload_to='partners/', blank=True, null=True) **# Urls (urls.py)** from django.urls import path from django.conf import settings from django.contrib.staticfiles.urls import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ path('', views.index, name='index'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() **# Appropriate settings (settings.py)** BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' **# Pages (views.py)** def index(request): …