Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Technology stack for handling CSV files online
just starting here and learning how to code. I have found an interesting project to start me on the coding journey but not too sure about choice of technology. These are the user description steps to the project: User uploads a pre-formatted file to the cloud/online database repository/whatever you want to call it Based on a set of pre-determined rules (chosen by the user and/or determined beforehand by developer) this file is analysed and respective comments are generated The user downloads a text file with the generated comments Happy to take advice on any pros and cons of different technology stacks. Timeframe for the project is 12 months (including learning a new language if necessary). -
FileUploadParser doesn't get the file name
I just want to create a REST API that receives a file, process it and return some information. My problem is that I am following this example: http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser And I can't make it work using Postman or curl, I think I am missing something. The parser always gives me these two errors: FileUpload parse error - none of upload handlers can handle the stream Missing filename. Request should include a Content-Disposition header with a filename parameter. This is the code: views.py: class FileUploadView(APIView): parser_classes = (FileUploadParser,) def post(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204) def put(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204) urls.py urlpatterns = [ url(r'predict/(?P<filename>[^/]+)$', app.views.FileUploadView.as_view()) ] settings.py """ Django settings for GenderAPI project. Generated by 'django-admin startproject' using Django 1.9.1. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import posixpath LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', … -
Django deep admin.TabularInline
if there is relation like: django can show it in one admin page by TabularInline: admin.py from django.contrib import admin from myapp2 import models # Register your models here. class TabularInlineB(admin.TabularInline): model=models.B class AdminA(admin.ModelAdmin): inlines=[TabularInlineB, ] admin.site.register(models.A, AdminA) models.py from django.db import models # Create your models here. class A(models.Model): name=models.CharField(max_length=10) class B(models.Model): name=models.CharField(max_length=10) a=models.ForeignKey(A) .the output is like: but if we add another ForeignKey relation to B like below, then How I can show all models in one page? admin.py from django.contrib import admin from myapp2 import models class TabularInlineC(admin.TabularInline): model=models.C class TabularInlineB(admin.TabularInline): model=models.B inlines=[TabularInlineC, ] class AdminA(admin.ModelAdmin): inlines=[TabularInlineB, ] admin.site.register(models.A, AdminA) .models.py from django.db import models # Create your models here. class A(models.Model): name=models.CharField(max_length=10) class B(models.Model): name=models.CharField(max_length=10) a=models.ForeignKey(A) class C(models.Model): b=models.ForeignKey(B) name=models.CharField(max_length=10) the output dose not show C: -
Django programming - how to redirect to original url
I have a website www.example.com with many pages. On each page I put one special unique button, which link to unique URL www.example.com/task1. Once click this button, Django urls patten will pass it to dedicated function task1 for me. My question is how to refresh original URL after completion of the task1, I find request.path only could transfer /task1. Any idea to get back the URL which the button allocated. Please refer to my task1 function. def task1(request): ''' do task1 job ''' return render(request, request.path) # above return could not render the original URL which I clicked from. -
Using Redshift's native 'AT TIMEZONE' through django query?
So I have this query which goes like query = MyModel.objects.filter(some_filter).filter(eventTime__date__gte=start_date).filter(eventTime__date__lte=end_date).... The redshift table I am connecting to has eventTime as UTC. It offers me to query in native SQL like select eventtime AT TIME ZONE 'MST' from mymodel limit 1; How can I use that AT TIME ZONE 'MST' in django query format? -
'collections.OrderedDict' object has no attribute 'pk' - django rest framework
I have a model and I want to write an update() method for it in order to update. The below snippet is my model: class Klass(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=500) university = models.CharField(max_length=50,blank=True, null=True) teacher = models.ForeignKey(Profile, related_name='teacher', on_delete=models.CASCADE) and the below snippet is corresponding Serializer: class KlassSerializer(ModelSerializer): teacher = ProfileSerializer() url = HyperlinkedIdentityField(view_name='mainp-api:detail', lookup_field='pk') klass_settings = KlassSettingsSerializer() class Meta: model = Klass fields = ('url', 'id', 'title', 'description', 'university','teacher') def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.description = validated_data.get('description', instance.description) instance.university = validated_data.get('university', instance.university) instance.save() return instance And for update, I use below snippet: class KlassAPIView(APIView): def put(self, request, pk=None): if pk == None: return Response({'message': 'You must specify class ID'}, status=HTTP_400_BAD_REQUEST) klass = Klass.objects.get(pk=pk) if request.user.profile.type != 't': raise PermissionDenied(detail={'message': 'You aren't teacher of this class, so you can't edit information.'}) serializer = KlassSerializer(data=request.data, context={'request': request}) serializer.initial_data['teacher'] = request.user.profile.__dict__ if serializer.is_valid(): serializer.update(instance=klass, validated_data=serializer.data) # Retrieve teacher and store return Response({'data': serializer.data}, status=HTTP_200_OK) else: return Response({'data': serializer.errors}, status=HTTP_400_BAD_REQUEST) but when I send data with PUT method, it returns below error: AttributeError at /api/class/49/ 'collections.OrderedDict' object has no attribute 'pk' and the error occurs in serializer.update(instance=klass, validated_data=serializer.data) line. -
Restart postgres connection in django
I have very strange situation here. Problem: I describe original problem inside this post, but to sum up: After using the project for a while, makemigrations stop working for me. (Yes I have set everything ok, setting are ok,.. please see my comments on previous post) I decided that I can't figure this out, so I would start fresh. (thats why git is for :D ) So, I delete my django project, I create new virtual environment, and I also create new database and new user in postgres. I update new database parameter inside my config file and try to run initial makemigrations but with no luch. It is still say that no new migrations are available. I am desperate because I can't work on the project, so any solution would do :D (virtual_environment) MacBook-Pro-2:MY_PROJECT marko$ python manage.py makemigrations connectors environment=local I will use local settings. No changes detected in app 'connectors' All my migrations (virtual_environment) MacBook-Pro-2:MY_PROJECT marko$ python manage.py showmigrations environment=local I will use local settings. admin [X] 0001_initial [X] 0002_logentry_remove_auto_add auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length connectors (no migrations) contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial … -
How to query translatable fields with graphene
Assuming a model that has translated fields like below, how can we query these with django-graphene? from parler.models import TranslatableModel, TranslatedFields class Article(TranslatableModel): #regular fields publishing_date = models.DateTimeField(_('publishing date'), default=now) # translated fields translations = TranslatedFields( title=models.CharField(_('title'), max_length=234), slug=models.SlugField( verbose_name=_('slug'), max_length=255, db_index=True, blank=True, ), meta_title=models.CharField( max_length=255, verbose_name=_('meta title'), blank=True, default=''), meta_description=models.TextField( verbose_name=_('meta description'), blank=True, default=''), meta_keywords=models.TextField( verbose_name=_('meta keywords'), blank=True, default=''), ) For registering "unknown" fields I do something like: @convert_django_field.register(TaggableManager) def convert_tagfield_to_string(field, registry=None): return graphene.String(description=field.help_text, required=not field.null) ... but this won't work here. Any ideas? -
How to actualize Django Template with get_context_data
I need your help in order to know How I can actualize my Django template from get_context_data. I have this class in my view : class IdentitySocieteResumeView(LoginRequiredMixin,TemplateView) : template_name = 'Identity_Societe_Resume.html' model = Societe def get_context_data(self, **kwargs) : context_data = super(IdentitySocieteResumeView, self).get_context_data(**kwargs) id = self.kwargs['id'] societe = get_object_or_404(Societe, pk=id) obj = Societe.objects.filter(Nom=societe.Nom, SIRET=societe.SIRET, SIREN=societe.SIREN, Ville=societe.Ville) if obj: sc_obj = obj[0] NIU = lib.Individu_Recherche.NIUGeneratorSociete(ModelBase=societe) societe.NumeroIdentification = NIU societe.save() context_data['queryset'] = obj return context_data And this important function in lib.Individu_Recherche : def NIUGeneratorSociete(ModelBase) : create_year_temp = str(ModelBase.Creation.year) create_year_temp2 = str(create_year_temp.split(" ")) create_year = create_year_temp2[4] + create_year_temp2[5] ''' A process which let to generate NumeroIdentification ''' NumeroIdentification = force_text('%s-%s%s-%s-%s-%s' % ('E', create_year, create_month, create_city, key, create_country_id)) return NumeroIdentification I'm sure my template is loaded before to execute this function and I get in my template NumeroIdentification = None but in my database this field is well-filled. My question is : How I can display my variable NumeroIdentification with the good value in my template (value stored in my database) instead of None ? If I press Cmd + R (MacOS Actualize), NumeroIdentification won't be None but a different value. I would like to get this value in my template the first time. It's … -
How create 2 step registration on python django without asking password fields at any step
Hello I am new at Django developing. I am trying to create 2 step registration for my django app. Here my code: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterFpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email adress.') first_name = forms.CharField(max_length=30, help_text='Example:Tosko') last_name = forms.CharField(max_length=30, help_text='Example:Yosko') gender = forms.CharField(max_length=10, help_text='Male/Female') class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'gender', ) class RegisterSpForm(UserCreationForm): country = forms.CharField(max_length=100, help_text='Example:Ukraine') city = forms.CharField(max_length=100, help_text='Example:Kiev') address = forms.CharField(max_length=200, help_text='Example:Marshala Timoshenko street') mobile_phone = forms.CharField(max_length=10, help_text='Example:0631231515') class Meta: model = User fields = ['country', 'city', 'address', 'mobile_phone',] RegistrationFpForm its a First step and RegistrationSpForm is Second Step views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth import login, logout, authenticate from .forms import RegisterFpForm, RegisterSpForm def logout_vw(request): """Logout link""" logout(request) return HttpResponseRedirect(reverse('testreg:index')) def register(request): """Register new user""" if request.method != 'POST': form = RegisterFpForm() else: form = RegisterFpForm(data=request.POST) if form.is_valid(): new_user = form.save() return HttpResponseRedirect(reverse('users:register_next')) context = {'form': form} return render(request, 'users/register_f.html', context) def register_next(request): """Continue register new user""" if request.method != 'POST': form = RegisterSpForm() else: form = RegisterSpForm(data=request.POST) if form.is_valid(): new_user = … -
Why is a unique required CharField not giving a IntegrityError when empty?
With the following model: class Client(models.Model): name = models.CharField(max_length=50, unique=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) modified_at = models.DateTimeField(auto_now=True, editable=False) This test fails: def test_no_name_error(self): '''Ensure an Error is raised when creating a client with no name ''' with self.assertRaises(IntegrityError): client = Client.objects.create() The test fails with: FAIL: test_no_name_error (projects.tests.test_models.ClientModelTests) Ensure an Error is raised when creating a client with no name ---------------------------------------------------------------------- client = Client.objects.create() AssertionError: IntegrityError not raised I am using mysql -
Custom django field type, with modified column look up in SELECT part
I would like to implement a custom Django field type. Namely a TranslatedField that is backed by native json/jsonb using postgres. But I would also like it to not have to return all translations for a particular query. Something like this: class TranslatedField(JSONField): pass class MyModel(models.Model): name = TranslatedField() And then used in an example: >>> MyModel.objects.create(name={'en': 'Duck', 'fr': 'Canard'}) >>> set_language('fr') # Imagine this function sets a global variable >>> en_fr = MyModel.objects.get(id=1) >>> en_fr.name >>> 'Canard' Which is fine, I can do that by returning the whole 'name' json from the database. But I would prefer if django issued actual SQL like this that did the lookup in postgres and saved me some bytes across the network: SELECT 'name'->'fr' FROM 'mymodel'; Does Django have any hooks that let me dynamically change the 'SELECT' part of the query? -
Change default GeoModelAdmin to OSMGeoAdmin
I tried to just naively to add it to admin.py like I normally would. from django.contrib.gis import admin from project.models import ProjectMap admin.site.register(ProjectMap, admin.OSMGeoAdmin) But it stil just show the default satellite image GeoModelAdmin. Here is the basic models i'm working with. class ProjectPage(Page): date = models.DateField("Post date", null=True) body = RichTextField(blank=True) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None search_fields = Page.search_fields + [ index.SearchField('body'), ] content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('date'), ], heading="Project information"), MultiFieldPanel([ FieldPanel('body', classname="full"), ], heading='Project'), InlinePanel('gallery_images', label="Gallery images"), InlinePanel('project_map', label="Project location") ] class ProjectMap(Orderable): page = ParentalKey(ProjectPage, related_name='project_map') city = models.CharField(blank=True, max_length=250) address = models.CharField(blank=True, max_length=250) country = models.CharField(blank=True, max_length=250) location = PointField(blank=True, null=True) content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('city'), FieldPanel('address'), FieldPanel('country'), FieldPanel('location'), ], heading="Location") ] Can I specify something like this in? content_panels = Page.content_panels + [ FieldPanel('location'), ] Or how do one go about this? I can't find it in the documentation. -
Upload and save multiple images using a csv with Django
I am trying to save multiple images to my DB (reference to their path) and upload them to my server via a csv containing the paths and attributes of the images (location where the image was took) but I don't know how and I couldn't find documentation for this particular feature. imagelist.csv imgpath,destination G:/Images/sunsetparis.jpg,Paris France G:/Images/image1.jpg,Berlin Germany G:/Images/_DS001.jpg,Tokyo Japan G:/Images/_DS002.jpg,Sydney Australia G:/Images/image2.png,Rio Brazil I want to parse this list and upload the images and save the names and destination to a DB forms class CSVForm(forms.Form): file = forms.FileField()# to upload the csv I used pandas to read the csv but I am stuck at this point, don't know how to save the images and the attributes views def CSVFormView(request): form = CSVForm() if request.method == "POST": form = CSVForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] data = file.read() df = pd.read_csv(io.BytesIO(data)) for index, row in df.iteritems(): print(row) ### don't know how to proceed from here Can you please lend a helping hand? Thank you -
Django: annotate Count with filter
I have "post" objects and a "post like" object with how many likes a post has received by which user: class Post(models.Model): text = models.CharField(max_length=500, default ='') user = models.ForeignKey(User) class PostLike(models.Model): user = models.ForeignKey(User) post = models.ForeignKey(Post) I can select how many likes a post has received like this: Post.objects.all().annotate(likes=Count('postlike')) This roughly translates to: SELECT p.*, Count(l.id) AS likes FROM post p, postlike l WHERE p.id = l.post_id GROUP BY (p.id) It works. Now, how I can filter the Count aggregation by the current user? I'd like to retrieve not all the likes of the post, but all the likes by the logged user. The resulting SQL should be like: SELECT p.*, Count(l.id) AS likes FROM post p, postlike l WHERE p.id = l.post_id AND l.user_id = 42 GROUP BY (p.id) -
I want an async response from view and show it as api response came
I have one view that calls 7 APIs and in the view, it loads all the 7 response and send to the templates but the problem is its first waits for all API to respond and then send the response to template and what I want is if one API responded then go to template and show the result second loads show the result like that so the waiting time is not as much as 7 APIs. here is my code : class Analyze(View): def post(self, request): if 'get_report' in request.POST: # Get site detail site_id = self.request.session.get('client_site_id') site = Site.objects.filter(id=site_id).first() # If couldn't find site than take the user to first step if not site: return redirect('analyze-site') self.context['get_report_form'] = GetReportForm(request.POST) # If valid email than generate & send PDF to user if self.context['get_report_form'].is_valid(): # Attach the email with site report site.email = self.context['get_report_form'].cleaned_data['email'] site.save() # generate the report is_generated, report_path, report_message, error = generate_site_report(site) if is_generated: # Send report via email is_email_sent, email_report_message, error = email_site_report(site) if is_email_sent: self.context['get_report_success'] = email_report_message # Clear the get report form self.context['get_report_form'] = GetReportForm() else: logger.error('Failed to email report of site - {id} due to {error}'.format(id=site.id, error=error)) self.context['get_report_error'] = email_report_message else: logger.error('Failed to … -
Django pass datetime via ajax
views.py cases = Case.objects.filter(Customer = customer) for item in cases: localtime = datetime_handler(item.CreatedDate) data.append({'id':item.id, 'CaseNumber':item.CaseNumber,'Title':item.Title.Description, 'Category': item.CaseCategory.Description, 'CreatedDate':localtime,'Users':item.Users.first_name+' '+item.Users.last_name, 'AssignedUser':item.AssignedUser.first_name+' '+item.AssignedUser.last_name, 'Status':item.Status.Description }) response_data = {'itemlist': data} return HttpResponse(json.dumps(response_data)) def datetime_handler(x): if isinstance(x, datetime.datetime): return x.isoformat() raise TypeError("Unknown type") json.dumps(data, default=datetime_handler) ajax $.ajax({ type: 'POST', url: 'GetCustomerCases', dataType: 'json', data: { TcNO: TcNO, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, success: function (data) { console.log(data); for (var i = 0; i < data.itemlist.length; i++) { $('#CustomerCases tbody').append('<tr>' + '<td>' + "<a href= /Case/" + data.itemlist[i]['id']+ '>'+ data.itemlist[i]['CaseNumber'] + '</a></td>' + '<td>' + data.itemlist[i]['Title'] + '</td>' + '<td>' + data.itemlist[i]['Category'] + '</td>' + '<td>' + data.itemlist[i]['CreatedDate']+ '</td>' + '<td>' + data.itemlist[i]['Users'] + '</td>' + '<td>' + data.itemlist[i]['AssignedUser'] + '</td>' + '<td>' + data.itemlist[i]['Status'] + '</td>' + '<td>' + data.itemlist[i]['CreatedDate'] + '</td>' + '</tr>'); } }, }); I'm able to get my cases object via ajax but this datetime field looks like "2017-10-17T10:27:46.862951+00:00" in html. Simply how can i convert to "10 october 2017 10:27 am". Also is there any way to use django template tags like {{ |timesince }} in javascript append. -
How to Restart Celery Wroker ran by Supervisord
I am running celery on production using supervisord. My supervisor configuration is below. [program:celeryd] command=%(ENV_PROJECT_PATH)s/scripts/celery_worker.sh stdout_logfile=%(ENV_PROJECT_PATH)s/celeryd.log stderr_logfile=%(ENV_PROJECT_PATH)s/celeryd.log autostart=true autorestart=true startsecs=10 stopwaitsecs=1000 priority=1000 My command to run celery worker is celery_path=$(which celery) $celery_path -A Project_Name worker --loglevel=info I want to ask, how to restart celery worker when my codebase changes in production? -
Django: Connect to external database with changing host/port
I need to connect django to an external database. Sometimes the host of the database is changed (lets say old host dies and I need to connect to a new host dynamically). I have monkey patched mysql_query to come up with following re-try logic (taken from https://stackoverflow.com/a/34275180/8793815) try: query_mysql() catch DatabaseError as e: new_host = get_new_db_host() update_django_database_setting(new_host) //settings.DATABASE re_initialize_django_db_and_or_connections() //**Not sure how to do this** query_mysql() I need to do this to make sure all the queries are served even when DB changes. I cannot start/stop django to do this. Database host changes are dynamic and not known apriori. (Context about how DB host can change. The DB I am trying to connect is a cluster of Master-Slave databases. Hosts change when DBAs are doing maintenance by promoting Slave to Master or adding new slaves) -
Migrating development database onto Heroku with Django
I am having trouble migrating my development database onto Heroku. This is for a personal project written in Django. settings.py db_from_env = dj_database_url.config() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } DATABASES['default'].update(db_from_env) I've migrated the database locally and pushed the migration onto Heroku already. Then, I ran the heroku run python manage.py migrate command to migrate the database on Heroku. I had accidentally ran makemigrations on Heroku, but have restarted my dynos since. Currently, my database on Heroku is not populated at all. -
Django on Production for POST request throws Server Error(500) on compute engine
I have deployed my Django 1.10 with python 3.6 Project on Google compute engine when I have changed Debug = True in my settings.py to Debug = False it throws Server Error (500) on one of my post requests.Even other post requests like signup are working fine. How can i solve this issue as i'm using Django 1.10.5, Python 3.6 on Compute Engine. Help me, please! Thanks in Advance! Here's my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'brainresearchtagging.com'] # INTERNAL_IPS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'users', 'article', 'import_export', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'brain.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'brain.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASS', … -
Django create a view to generate a receipt
I want to create a small app that creates a kind off receipt record in to a db table, from two other tables. very much like a receipt from a grocery store where a cashier makes a sell and the ticket contains multiple items, calculates a total and subtotal and return values to the database. I currently have 3 tables: the Ticket table where i would like to insert the values of all calculations and ticket info, the services table that acts like an inventory of services available. this has the service name and price for each service and my responsible table that has a list of "cashiers" or people that will make the sale and their percentage for their commissions, i have the views to create , edit and delete cashier's and services. What I don't have is a way to create the ticket. I am completely lost. can you guys point me in to the correct path on what to look for. i am learning to program son i don't have a lot of knowledge in this if its even possible. i don't need the system to print i just want to have all record stored this way … -
Dajngo custom user error
I have a custom user model that extends an AbstractBaseUser, as well as my own user manager (GenericUserManager): class GenericUserManager(BaseUserManager): def create_user(self, username, email, password, key_expires): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError("users must have a username") if not password: raise ValueError('users must have password') user = self.model( username=username, email=self.normalize_email(email), key_expires=key_expires, ) user.set_password(password) user.save(using=self._db) return user def get_by_natural_key(self, username): return self.get(username=username) class BaseRegistrationUser(AbstractBaseUser): username = models.CharField(max_length=150, unique=True) email = models.EmailField( verbose_name='email address', max_length=255, unique=False, ) activation_key = models.CharField(max_length=90) key_expires = models.DateTimeField() is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(('date joined'), default=datetime.datetime.now) is_merchant_or_customer = models.CharField(max_length=20, null=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['username, email'] def __str__(self): return self.username ... def natural_key(self): return (self.email,) ... class Customer(BaseRegistrationUser): first_name = models.CharField(max_length=150, default="", null=True) last_name = models.CharField(max_length=150, default="", null=True) slug = models.SlugField(max_length=175, default="", null=True) objects = GenericUserManager() ... These work fine for registration purposes, however, whenever I attempt to log a 'customer' user I get the following error: File "C:\Users\OEM\Documents\repos\repo\ecommerce\myapp\views.py" in get_profile 126. user = authenticate(username=username, password=password) File "C:\Users\OEM\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\contrib\auth\__init__.py" in authenticate 70. user = _authenticate_with_backend(backend, backend_path, request, credentials) File "C:\Users\OEM\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\contrib\auth\__init__.py" in _authenticate_with_backend 115. return backend.authenticate(*args, **credentials) File "C:\Users\OEM\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\contrib\auth\backends.py" in authenticate 18. user = … -
How can I set the field unique in django?
I have a model class: class PysicalServer(models.Model): serial_number = models.CharField(max_length=64) # I want to add the unique name = models.CharField(max_length=16) I know use the primary_key can set unique, but the serial_number is not my id field, I can not use the primary_key, is there other property I can set field unique? -
Accessing Images in Static Folder
I've placed some images in /static/some_directory and Django cannot find them. But when the same images are placed in /static/images, Django is able to find them. My settings.py has the following: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' # Added to make "static" directory path relative to BASE_DIR STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) What do I need to add to make this work? Any help would be appreciated. Thanks.