Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I automatically generate slug for user OneToOneField url
I am building a django application that requires users to sign in and have profiles that other users should be able to view but I am stuck at generating unique slug urls for each user. I want a user to be redirected to myexample.com/elon-musk instead of my-example.com/profile so that every user profile page can be unique.Any ideas on how I can go about it? Thanks In advance. class ContractorProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name= 'profile',) image = models.ImageField(default='default.jpg', upload_to='profile_pics') first_name = models.CharField(max_length=20, blank=True) last_name = models.CharField(max_length=20, blank=True) slug = models.SlugField(null=True, blank=True) def save(self, *args, **kwargs): if slug is None: slug = slugify(self.user) while self.__class__.objects.filter(slug=slug).exists(): slug = "%s-%s" % (slug,str(uuid.uuid4())[:5]) self.slug = slug super(ContractorProfile, self).save(*args, **kwargs) @login_required def dynamic_lookup_view(request, user): obj = ContractorProfile.objects.get(user=user) return render (request, "CsignTest/profile.html", {"obj": obj}) ```urls.py re_path(r'^profile/(?P<user>\w+)/$', CsignTest_views.dynamic_lookup_view, name='user-prof'), -
Convert djongo EmbeddedModelField
Hi I am new to Python's Django framework and ORM. I have this problem that I can not solve. I have collection in mongo called users Looks something like this: { _id: username: email: password: user_type: } I want to have 2 types of user (1 = customer, 2= supplier), both able to log into application. After some research I found that all users should be stored in one collection. So i decided to use user_type and two additional fields: { customer_data: // object that will be filled if user is customer supplier_data: // object that will be filled if user is supplier } I followed tutorial at: Djongo docs page, but I still get same error: Don't know how to convert the Django field user.User.supplier_data (<class 'djongo.models.fields.EmbeddedModelField'>) My User model: class User(AbstractBaseUser): _id = models.ObjectIdField() password = models.CharField(max_length=128) # Other fields supplier_data = models.EmbeddedModelField(model_container=SupplierData, default={}, null=True) SupplierData model: class SupplierData(models.Model): phone = models.CharField(max_length=100) website = models.URLField() description = models.TextField() rating = models.DecimalField(default=0.0, decimal_places=1, max_digits=5) class Meta: abstract = True models is from djongo library (from djongo import models) I could use another collections with customer and supplier data with relation to users collection, but supplier will have more nested … -
Why is Django converting aware timestamp received from API request
My Django app receives POST API request with one of fields in body containing aware timestamp. If I log it's value right after deserialization I'm seeing the same time stamp but in different timezone. Here's example of submitted request body: { "event_timestamp": "2019-11-08T15:00:00+02:00", ... } Yet if I try to log the value of this field right after it passes deserialization I'm seeing 2019-11-08 14:00:00+01:00 TZ is enabled and configurred to CEST time zone: USE_TZ = True TIME_ZONE = 'Europe/Vienna' I could make an assumption that Django is automatically converting received timestamp into defined timezone for entire project, but the result of such a conversion would have given me the same result: 2019-11-08T15:00:00+02:00 represented as CEST timezone is 2019-11-08T15:00:00+02:00 I understand that such conversions are normal process of Django handling aware datetime objects, but why does it convert a value to a timezone which is neither set as default for the project itself nor has any relation to received timestamp? Is there a way of managing default way of such convertions to timezone I manually define in settings.py or disable them all together? -
django form error didn't return an HttpResponse object when entering an error in the sign up form
Everything works perfect except if you fill in the form incorrectly. For example 2 different passwords. Before you all start going this is a duplicate to this: didn't return an HttpResponse object. Please do not. My view does not have this issue. I have tried everything I have seen in every other post and it does not work. Also I'm pretty sure that this code used to work and for some reason now It doesn't. Any help, very much appreciated. This is the error.. raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)) ValueError: The view main.views.home didn't return an HttpResponse object. This is the view if request.method =='POST': form = MyRegistrationForm(request.POST) if form.is_valid(): form.save() username= request.POST.get('username','') email= request.POST.get('email','') subject = 'Hi {0} Welcome to blabla'.format(username) msg="Hi {0},".format(username) msg=msg+settings.WELCOME_EMAIL message = msg recipients = ['info@blabla.com'] if email: recipients.append(email) send_mail(subject, message, 'info@blabla.com', recipients, fail_silently=False) return HttpResponseRedirect('thank-you') else: form = MyRegistrationForm() return render(request, 'reg.html', {'form': form}) The template is very big with lots of other stuff going on so I am not including it all here except what I think is relevant. <div>{{ form.non_field_errors }}<br/> <div class="myerr"><h4><strong>{{ form.username.errors }}<br/> {{ form.email.errors }}<br/> {{ form.password1.errors }}<br/> {{ form.password2.errors }}<br/></strong></h4> </div> … -
My Django formset isn't saving object images
I created an upload form for users allowing them to create a model object. Everything else works, but the image field doesn't store the loaded images. I use the Crispy FormHelper in the views.py, but HTML source code shows that the elements (enctype, layout_class, field_class etc...) aren't loading. I think this is where the problem is. Here's what the rendered form looks like: For context, the form should look like this: <form class="form-horizontal" method="post" > ... </form> I've walked through the code and the tutorial I used line by line, but I can't find where the problem lies. views.py class CarCreate(generic.CreateView): model = Car slug_field = 'id' slug_url_kwarg = 'car_create' template_name = 'showroom/car_create.html' form_class = CreateCarForm success_url = None def get_context_data(self, **kwargs): data = super(CarCreate, self).get_context_data(**kwargs) self.request.POST: data['images'] = CarImageFormSet(self.request.POST, self.request.FILES) else: data['images'] = CarImageFormSet() return data def form_valid(self, form): context = self.get_context_data() images = context['images'] with transaction.atomic(): form.instance.seller = self.request.user self.object = form.save() if images.is_valid(): images.instance = self.object images.save() return super(CarCreate, self).form_valid(form) def get_success_url(self): # return reverse_lazy('showroom:cars', kwargs={'slug': self.object.id}) # Throws an error return reverse_lazy('showroom:cars') forms.py class CreateCarForm(ModelForm): class Meta: model = Car exclude = ['seller', 'id'] def __init__(self, *args, **kwargs): super(CreateCarForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = … -
Search multiple fields with django
/api/customer/list?search=john When I search for "john" in the "customerName" field, all records come. /api/customer/list?customerName=john When I search this way, only John's record comes. But when I search in the "customerName and customerSurname" fields, there are no records or missing records. How do I search for two fields using "search"? class CustomerListAPIView(ListAPIView): serializer_class = CustomerCreateSerializer permission_classes = [IsOwner] filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filter_fields = ['customerName'] def get_queryset(self): queryset = Customer.objects.filter(user=self.request.user) print(queryset) return queryset HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 10, "customerName": "john", "customerSurname": "down", "customerIdentityNo": "2261", "customerGender": "M", "customerPhone": "34", "customerBirth": "2019-10-11", "customerDescription": "description", "customerStatus": false, "createdDate": "2019-10-01T08:33:15.769174Z", "modifiedDate": "2019-10-18T09:09:01.547840Z", "modifiedByUser": 1, "created_userKey": "0245abb9-2837-4f37-ae02-9be1b88887ef", "customerKey": "ea83b54e-8352-47c8-b26e-7ce747275cfe" }, { "id": 27, "customerName": "warren", "customerSurname": "buffet", "customerIdentityNo": "22611611650", "customerGender": "M", "customerPhone": "888888", "customerBirth": "2019-10-10", "customerDescription": "", "customerStatus": false, "createdDate": "2019-10-20T07:06:28.353817Z", "modifiedDate": "2019-10-20T07:06:28.353831Z", "modifiedByUser": null, "created_userKey": "0245abb9-2837-4f37-ae02-9be1b88887ef", "customerKey": "a049714c-da11-4608-8ceb-eaf4ba030c6b" }, { "id": 28, "customerName": "bill", "customerSurname": "gates", "customerIdentityNo": "22611611650", "customerGender": "M", "customerPhone": "745444", "customerBirth": "2019-10-17", "customerDescription": "", "customerStatus": false, "createdDate": "2019-10-20T07:12:53.066400Z", "modifiedDate": "2019-10-20T07:12:53.066458Z", "modifiedByUser": null, "created_userKey": "0245abb9-2837-4f37-ae02-9be1b88887ef", "customerKey": "c9194b03-6b1a-42d6-b38a-ed5a7bf40df8" }, { "id": 29, "customerName": "john", "customerSurname": "snowden", "customerIdentityNo": "22611611650", "customerGender": "M", "customerPhone": "24455", "customerBirth": "2019-10-16", "customerDescription": "", "customerStatus": false, "createdDate": "2019-10-20T07:14:26.048885Z", "modifiedDate": "2019-10-20T07:14:26.048899Z", "modifiedByUser": null, "created_userKey": "0245abb9-2837-4f37-ae02-9be1b88887ef", … -
Django rest Framework - Expected a list of items but got type "QuerySet"
I try to serialize query set. But Im getting {'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "QuerySet".', code='not_a_list')]} error. How to solve this error. def post(self, request): data = request.data user_name = data.get('username') signup_filtered_data = Signup.objects.filter(username= user_name).values() print(signup_filtered_data) serializer = SignupSerializer(data= signup_filtered_data, many=True) serializer.is_valid() print(serializer.errors) signup_jason_data = json.dumps(serializer.data) return HttpResponse(signup_jason_data) models.py class Signup(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=50, unique= True) phone_number = models.CharField(max_length=12, unique= True) username = models.CharField(max_length=50, unique= True) password = models.CharField(max_length=50, blank=True, null=True) serializers.py class SignupSerializer(serializers.ModelSerializer): class Meta: model = Signup fields = '__all__' -
KeyError at /log_data "None of [Index(['abc' , 'qwe' ], dtype='object')] are in the [columns]"
Getting KeyError at/log With this code, I want to Check Username entered by user In HTML with Username in CSV. Am Working On Django. def log_data(request): if 'uname' in request.POST: username=request.POST['uname'] else: username = False if 'pass' in request.POST: pw=request.POST['pass'] else: pw=False data = pd.read_csv('login.csv') for i in data: if ((data[data.USERNAME])==username ): #if((data['USERNAME']==username) and (int(data['PASSWORD'])==int(pw))): f=1 Error is at if ((data[data.USERNAME])==username ): #if((data['USERNAME']==username) and (int(data['PASSWORD'])==int(pw))): etc.. -
Django Images In Media Not Displaying Despite Correct Settings
I'm trying to upload an image from a form and display it on another template, however the images in media cannot be found. Model class Upload(models.Model): image = models.ImageField(upload_to='images/') View class HomePageView(CreateView): model = Upload form_class = UploadForm template_name = 'home.html' success_url = reverse_lazy('rank') class RankView(ListView): model = Rank template_name = 'rank.html' Settings MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' Urls urlpatterns = [ path('', include('avatars.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Templates <img src="{{upload.image.url}}"> Inspecting the code in browser, the img url is 'unknown' -
Unable to Access Other Apps in Django
I am writing a beginner Django app. I am currently able to the first app that I created. However, I am not able to figure out how to access the other two apps. swiss (project) |_ app_picker (default app) |_ eft |_ servermon I am currently able to access the app_picker by typing 127.0.0.1:8000/app_picker/. But when I type in 127.0.0.1:8000/eft or 172.0.0.1:8000/servermon the page is not found. What am I failing to understand with my Django config? Installed Apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app_picker', 'etf', 'servermon', ] Project URLS from django.contrib import admin from django.urls import path from django.views.generic import RedirectView from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('app_picker/', include('app_picker.urls')), path('etf/', include('etf.urls')), path('servermon/', include('servermon.urls')), path('', RedirectView.as_view(url='app_picker/', permanent=True)), ] #Add Django site authentication urls (for login, logout, password management) urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), ] app_picker URLs from django.conf import settings from django.conf.urls.static import static from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] eft URLs from django.conf import settings from django.conf.urls.static import static from django.urls import path from . import views urlpatterns = [ path('eft/', views.base, name='eft_base'), ] eft Views from django.shortcuts import render # Create your … -
How to access django models from a scheduled script?
TL;DR: I have an app that I want to run a routine every day at midnight (for that I'm using APScheduler). In the middle of this routine it's supposed to access data from a few django models. The logic is Django is running > run apps.py > run scheduler.py > run routine.py > access models.py. Exceptions raised at the bottom of the post. - Here comes the details: My directory is this: myproject/ - manage.py + myproject/ -- settings.py -- wsgi.py -- ... + myapp/ -+ static/ -+ templates/ -- admin.py -- apps.py -- models.py -- views.py -- scheduler.py #<<<<<<<<<< -- routine.py #<<<<<<<<<< -- ... myapp/models.py class MyModel(models.Model): field1 = models.DateField(auto_now=True) field2 = models.DecimalField(max_digits=19, decimal_places=16) ... myapp/apps.py from django.apps import AppConfig from .scheduler import ScheduledRoutine class MyAppConfig(AppConfig): name = 'myapp' def ready(self): routine = ScheduledRoutine() routine.start() myapp/scheduler.py from .routine import MyRoutine #from ..routine import MyRoutine # See error nr3 <<<<<<<<< from apscheduler.schedulers.background import BackgroundScheduler class ScheduledRoutine(object): def start(self): self.scheduler = BackgroundScheduler() startdate = datetime.now() #For brevity assume datetime object self.scheduler.add_job(self.routine, 'interval', days=1, start_date=startdate) self.scheduler.start() def routine(self): data = MyRoutine() myapp/routine.py import os os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings" import django django.setup() from .models import MyModel #from myapp.models import MyModel # See error nr3 … -
Django - Taking values from POST
I'm passing some data to my template ("appointments.html") which looks like this: Appointments today Appointment ID : 84218332 Scheduled Time: 2019-10-18T01:00:00 Arrived Appointment ID : 84218332 Scheduled Time: 2019-10-18T22:05:00 Arrived <h1>Appointments today</h1> {% for p in appointment %} <tr> <td>Appointment ID : {{ p.patient }} Scheduled Time: {{p.scheduled_time}}</td> <td> <form action="arrived" method="post"> {% csrf_token %} <input type="hidden" name="appid" value="{{ p.id }}"> <input type="submit" value="Arrived" class="btn btn-primary"> </form> </td> </tr> {% endfor %} I want to call another view in views.py by clicking on "Arrived" button which gets back the p.id which is passed as a value to further use it for other purposes. urls.py : url(r'^appointment/arrived/$', views.arrived, name='arrived') views.py def arrived(request): if request.method == 'POST': appointment_id = request.POST.get("appid", "") print(appointment_id) ERROR : You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/appointment/arrived/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. How do I fix this and what am I missing exactly? -
How to load template that it has own css like bs3 to another page?
I have a form that it has Bootstrap 4 CSS classes. I want add jquery image upload code in my form but this codes have Bootstrap 3 CSS classes. I put my jquery block to image_block.html with {% load 'image_block.html %} tag. But I load image_block.html to my form.html file BS3 classes squash my BS4 classes and page is destroyed! image_block.html: <!DOCTYPE HTML> {% load upload_tags %} <head> <!-- Force latest IE rendering engine or ChromeFrame if installed --> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <![endif]--> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap styles --> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"> <!-- Generic page styles --> <link rel="stylesheet" href="/static/jquery-upload/css/style.css"> <!-- blueimp Gallery styles --> <link rel="stylesheet" href="/static/jquery-upload/css/blueimp-gallery.min.css"> <!-- CSS to style the file input field as button and adjust the Bootstrap progress bars --> <link rel="stylesheet" href="/static/jquery-upload/css/jquery.fileupload-ui.css"> <!-- CSS adjustments for browsers with JavaScript disabled --> <noscript><link rel="stylesheet" href="/staticjquery-upload//css/jquery.fileupload-ui-noscript.css"></noscript> <!-- Shim to make HTML5 elements usable in older Internet Explorer versions --> <!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]--> </head> {% block upload %} <div class="container"> <!-- The file upload form used as target for the file upload widget --> <form id="fileupload" method="post" action="." enctype="multipart/form-data">{% csrf_token %} <!-- Redirect browsers with JavaScript disabled to the … -
How to use Django settings.MEDIA_ROOT as string file path?
Modules being used: OpenCV and Django Task: I am trying to process a video during upload by reading the video file and saving the first frame of the video to use as thumbnail on an HTML page. Problem: The function cv2.imwrite, which saves an image, is where the code stops working. I have added a bunch of print() statements to show exactly what is going on. I would like to note that if I use a file path in the string form such as: cv2.imwrite('/media/test2_thumbnail.jpg', frame) the process works. OpenCV Code: def save_video_thumbnail(video, video_name): cap = cv2.VideoCapture(video) ret, frame = cap.read() if ret: print(f'It is {ret} that it is reading the frame') print('Saving file to:', settings.MEDIA_URL + video_name + "_thumbnail.jpg") thumbnail = cv2.imwrite(settings.MEDIA_URL + video_name + "_thumbnail.jpg", frame) return thumbnail Django Code: def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) form.instance.sender = self.request.user if form.is_valid(): form.save() video_name = form.instance.name video_file_path = str(settings.MEDIA_ROOT) + "/" + str(form.instance.video_file) print(f'start with file: {video_file_path}') thumbnail = save_video_thumbnail(video_file_path, video_name) print(f'It is {thumbnail} that it is saving the thumbnail.') Output: start with file: /home/david/PycharmProjects/clearpath/media/videos/IMG_0088_PwgOcpW.MOV It is True that it is reading the frame Saving file to: /media/test2_thumbnail.jpg It is False that it is saving the … -
How to link rows from one table to rows of another table in Django?
I have to four tables: class Instrument(models.Model): name = models.CharField(max_length=100, null=True, blank=True) instrumentation = models.ManyToManyField(Instrumentation, verbose_name=_('instrumentation'), related_name='instrument', blank=True) class Instrumentation(models.Model): name = models.CharField(max_length=100, null=True, blank=True) Entries to the table are: row 1: name = violin, instrumentation = piano trio row 2: name = piano, instrumentation = piano trio row 3: name = cello, instrumentation = piano trio Here are the other two tables: class Ensemble(models.Model): name = models.CharField(max_length=200, null=True, blank=True) class EnsembleMember(models.Model): ensemble = models.ForeignKey(Ensemble, verbose_name=_('ensemble'), related_name='ensemble_member', on_delete=models.PROTECT) member = models.ForeignKey(Person, verbose_name=_('member'), null=True, blank=True, on_delete=models.PROTECT) row 1: name = person 1 (violin), ensemble = Beau Arts Trio row 2: name = person 2 (pianist), ensemble = Beau Arts Trio row 3: name = person 3 (cellist), ensemble = Beau Arts Trio How do I link Instrument with EnsembleMember? ForeignKey or ManyToManyField? An Instrument to map to many different Ensemble Member. row 1 in Instrument to row 1 in Ensemble Member row 2 in Instrument to row 2 in Ensemble Member row 3 in Instrument to row 3 in Ensemble Member And have drop down options in admin.py -
Heroku (DjangoRF/React App) react router works but urls don't work while refreshing or writing manually
I've got APP working on Heroku. It has DRF API backend and ReactJS frontend. React routing works properly but when I refresh page or write URL manually it throws django 404 URL not found error. During the development I didn't have that problem. It has became a problem after pushing App to Heroku. -
how to get amp template in django
i've been trying to get my site with django in back-end and AMP on the front-end (without a html), i've created some sites with fully amp but now i'm problems with the 'base.amp.html' and another issues. i've tried to use the app 'django-amp-tools' and get some errors in the app, tried to create without it and getting erros on the validation just to bring the extends 'base.amp.html'. base.amp.html: {% load staticfiles %} {% load static %} {% get_media_prefix as MEDIA_PREFIX %} <!doctype html> <html amp lang="en"> <head> <meta charset="utf-8"> <script async src="https://cdn.ampproject.org/v0.js"></script> <title>{% block title %}dealership{% endblock %}</title> <link rel="canonical" href="https://amp.dev/pt_br/documentation/guides-and-tutorials/start/create/basic_markup/"> <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"> <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "NewsArticle", "headline": "Open-source framework for publishing content", "datePublished": "2015-10-07T12:02:41Z", "image": [ "logo.jpg" ] } </script> <style amp-boilerplate> body { -webkit-animation: -amp-start 8s steps(1, end) 0s 1 normal both; -moz-animation: -amp-start 8s steps(1, end) 0s 1 normal both; -ms-animation: -amp-start 8s steps(1, end) 0s 1 normal both; animation: -amp-start 8s steps(1, end) 0s 1 normal both } @-webkit-keyframes -amp-start { from { visibility: hidden } to { visibility: visible } } @-moz-keyframes -amp-start { from { visibility: hidden } to { visibility: visible } } @-ms-keyframes -amp-start { from { visibility: … -
can i use jQuery in Django framework
i'm writing a Django Full website and trying to change the element using jQuery OR JavaScript but i couldn't i want to change the total ''' <tr> <td>{{i.itemname}}</td> <td>{{i.description}}</td> <td id="quantity">{{i.quantity}}</td> <td id="price">{{i.price}}</td> <td id="total"></td> </tr> ''' ''' var quantity = document.getElementById('#quantity') var price = document.getElementById('#price') q=Number(quantity) p=Number(price) total = q*p document.getElementById("#total").innerHTML = total; ''' -
Is there a way to restrict outbound traffic on a Django function?
I have a function in my Django app and I'd like to ensure there is no outbound network traffic from it while still being able to return a response. For example, blocking the POST request to an external site in this function: def secureFunction(val): request.POST('www.example.com', data={'val':val}) return val * 2 Currently, I break my app into APIs and use AWS security groups to accomplish this. Is there a way I can put a wrapper on Django functions to block outbound traffic, but still return a response? For example something like: @block_traffic def secureFunction(val): request.POST('www.example.com', data={'val':val}) # blocked return val * 2 I want to be able to apply outbound traffic blocking to specific functions. -
Filtering data in real time in django forms
I have two problems strictly. The first is the problem with the field type in forms.py. Because I'm trying to use a foreign key as a value in the check box and I have the error that the "int () must be a string, a byte-like object or a number, not" ModelChoiceField "and I don't know what to do with it. The second main problem is data filtering in the interface in real time. What I mean? I have a user model like: # user/models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) country= models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) year = models.IntegerField(choices=YEARS, default=1) image = models.ImageField(default='default.jpg', upload_to='profile_pics') And in forms I want to see only those cities that are in the selected country. For example, we have record like: London, United Kingdom; York, United Kingdom; Berlin, Germany; and if the user chooses Germany, he should only see Berlin in the area with the cities. I hope you know what I want to achieve and someone will be able to help me. # forms.py: class ProfileUpdateForm(forms.ModelForm): country =forms.ModelChoiceField(queryset=Country.objects.all()) city = forms.ModelChoiceField(queryset=City.objects.filter(country=country)) class Meta: model = Profile fields = ['website','country', 'city', 'year', 'image'] # city/models.py class Country(models.Model): name = models.CharField(max_length=100) … -
Geocoding with GeoPy and ImportExport in Django
I am bringing a data set from a .CSV file of addresses into a model in Django through the ImportExport plugin, and at the point of saving this the model runs a geocoding process with GeoPy. 90% of the time it works but there are a few entries that are coming up with the following error: ... in save _, latlon = geocoder.geocode(address) TypeError: cannot unpack non-iterable NoneType object I am guessing that the geocoding is not finding an address but I'm not sure why it doesn't just leave the field empty. Apologies if this question is a a simple misunderstanding, I am a very new starter to this level of programming, I've looked up relevant sections in Django Docs, GeoPy docs and google maps geocoding docs but don't seem to find any hint as to how to fix it. below is the a more full trace back error output: Traceback (most recent call last): File "C:\Users\henry\webvenv\aavenv\lib\site-packages\import_export\resources.py", line 522, in import_row self.save_instance(instance, using_transactions, dry_run) File "C:\Users\henry\webvenv\aavenv\lib\site-packages\import_export\resources.py", line 315, in save_instance instance.save() File "C:\Users\henry\webvenv\project\architects\models.py", line 51, in save _, latlon = geocoder.geocode(address) TypeError: cannot unpack non-iterable NoneType object Below is the app/model.py which is being populated by the .CSV file and … -
Filter images by foreign key
I have an Image model and a Category model. I want to display only images of the corresponding category in my category_detail view. models.py class Category(models.Model): category_title = models.CharField(max_length=200) category_image = models.ImageField(upload_to="category") category_description = models.TextField() slug = models.SlugField(max_length=200, unique=True, default=1) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.category_title class Image(models.Model): category = models.ForeignKey(Category, on_delete="CASCADE") image = models.ImageField() caption = models.CharField(max_length=250) class Meta: verbose_name_plural = "Images" def __str__(self): return str(self.image) views.py def category_detail_view(request, slug): category = get_object_or_404(Category, slug=slug) context = { "gallery": Image.objects.filter(Category), } return render(request, 'main/category_detail.html', context) category_detail.html {% for image in gallery %} <div class="col-md-4"> <a href="{{ image.url }}"> <img src="{{ image.url }}" class="img-responsive img-thumbnail" width="304" height="236"/> </a> </div> {% endfor %} -
The most reliable way to grab an IP-address?
I noticed that it is fairly tricky to grab an IP-address with Django, It almost seem that JavaScript can grab an IP more reliably than Django but the problem with JS is that it can be disabled easily by the user. What is your take on the situation? I can't decide which tech to use. Thanks. -
TypeError: Cannot read property 'length' of undefined in Django and ReactJs
TypeError: Cannot read property 'length' of undefined thats whats says compiller when i run my Django and ReactJs ecommerce app .What i need to do with this ? error place is shown as in cart.js 53 | text={${cart !== null ? cart.order_items.length : 0}} ^ 54 | pointing error place is shown as in Layout.js 33 | dispatch(cartSuccess(res.data)); ^ 34 | }) In action/ cart.js export const fetchCart = () => { return dispatch => { dispatch(cartStart()); authAxios .get(orderSummaryURL) .then(res => { dispatch(cartSuccess(res.data)); }) .catch(err => { dispatch(cartFail(err)); }); }; }; In Layout.js <Menu.Menu inverted position="right"> <Dropdown icon="filter" loading={loading} text={`${cart !== null ? cart.order_items.length : 0}`} pointing className="link item" > <Dropdown.Menu> <Dropdown.Item>List Item</Dropdown.Item> <Dropdown.Item>List Item</Dropdown.Item> <Dropdown.Divider /> <Dropdown.Header>Header Item</Dropdown.Header> <Dropdown.Item> <i className="dropdown icon" /> <span className="text">Submenu</span> <Dropdown.Menu> <Dropdown.Item>List Item</Dropdown.Item> <Dropdown.Item>List Item</Dropdown.Item> </Dropdown.Menu> </Dropdown.Item> <Dropdown.Item>List Item</Dropdown.Item> </Dropdown.Menu> </Dropdown> </Menu.Menu> -
Context Error while using Django-tables2 in my Project
I am attempting to implement Django-tables2 into my project. I am able to render the object_list, but when I alter the template to render_table table, it fails. I am seeing this error upon rending my template: Exception Type: AttributeError Exception Value: context Here are my following files Views.py class DeviceTable_New(SingleTableView): table_class = DeviceTable template_name = "device_app/device_list.html" paginator_class = LazyPaginator filterset_class = DeviceFilter Tables.py class DeviceTable(tables.Table): class Meta: model = Device template_name = "device_app/device_list.html" fields = ("id", "type", "processed","donated_to_recipient") urls.py path('device_list/',views.DeviceTable_New.as_view(),name='device_list'), Template (Not the full page. There is proprietary information on this page.) <div class='col-md-8'> <div class="jumbotron"> <h1>Devices</h1> <hr> <p><a class='button' href="{% url 'device_app:device_create'%}">Create Device</a</p> {% render_table table %} </div> </div>