Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to display information from a connected table if not null?
I built a table with a MySQL backend in Django that lets me store generator charts that would be useful in worldbuilding and character building, like you might find on reddit.com/r/d100. My table can account for 110 potential roll entries, but I anticipate that for some tables (such as d20 tables), a large number of the entries will not be used. Is there a way to display all of the used entries but skip the null entries? If not, I am prepared to hardcore each of the rolls to display on the webpage. I was anticipating having to plug in something like <tr> <th>Roll</th> <th>Result</th> </tr> {% if table.roll_1 is not None %} <tr> <td>1</td> <td>{{ table.roll_1 }} </tr> {% endif %} </table> This is my generator table model: class D100Generator(models.Model): d_100_id = models.AutoField(primary_key=True) field_of_interest = models.ForeignKey(FieldOfInterest, on_delete=models.CASCADE) subreddit_post_id = models.ForeignKey(Subreddit, on_delete=models.CASCADE, blank=True, null=True) module_id = models.ForeignKey(Module, on_delete=models.CASCADE, blank=True, null=True) generic_website_id = models.ForeignKey(GenericWebsite, on_delete=models.CASCADE, blank=True, null=True) table_name = models.CharField('table name', max_length=100) system = models.CharField(max_length=150) genre = models.CharField(max_length=250) chart_type = models.CharField('Die used', max_length=15) chart_instructions = models.TextField('Chart instructions & explanation') roll_1 = models.TextField('1', blank=True, null=True) roll_2 = models.TextField('2', blank=True, null=True) ... roll_109 = models.TextField('109', blank=True, null=True) roll_110 = models.TextField('110', blank=True, null=True) table_slug … -
How to Render Message Threads to Template in Django?
I'm trying to render a user's direct messages and group them into threads in the template. Each message has a "thread" field to indicate the thread. How would I render the messages to the template, grouped into their thread? Here is my model: class Thread(models.Model): transaction = models.OneToOneField( Transaction, on_delete=models.CASCADE, primary_key=True, ) create_time = models.DateTimeField(default=timezone.now, null=True, blank=True) class Message(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey(get_user_model(), related_name='sender', on_delete=models.CASCADE) reciever = models.ForeignKey(get_user_model(), related_name='reciever',on_delete=models.CASCADE) text = models.TextField(max_length=4000) create_time = models.DateTimeField(default=timezone.now, null=True, blank=True) Any help is appreciated. -
Docker is building but not showing data in browser
I'm new to using Docker and this is my first project with it. I followed a tutorial to implement on a project i'm working on. I created a backend using python and django and am trying to containerize it and then deploy it. The application is building and being containerized, but when i go to see if my data is showing up, but it returns an error right now. Please take a look at the code and let me know if i've made any mistakes. # Dockerfile # Pull base image FROM python:3.7 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies RUN pip install pipenv COPY Pipfile Pipfile.lock /code/ RUN pipenv install --system # Copy project COPY . /code/ version: '3.7' services: db: image: postgres:11.5-alpine volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - POSTGRES_USER=nostaldjauser - POSTGRES_PASSWORD=nostaldja - POSTGRESS_DB=nostaldja volumes: postgres_data: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'nostaldja', 'rest_framework', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'nostaldja', 'USER': 'nostaldjauser', 'PASSWORD': 'nostaldja', 'HOST': 'db', 'PORT': 'localhost' } } -
The value of list_display is not a callable, an attribute of 'newly created class'
when i run server i am facing error : (admin.E108) The value of 'list_display[1]' refers to 'Discount', which is not a callable, an attribute of 'OfferAdmin', or an attribute or method on 'products.Offer'. I tried following piece of code in a file named admin.py from django.contrib import admin from .models import Product, Offer class OfferAdmin(admin.ModelAdmin): list_display = ('code', 'Discount') class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'stock') admin.site.register(Offer, OfferAdmin) admin.site.register(Product, ProductAdmin) befor adding class OfferAdmin code was working fine. However after adding it. this is showing error -
form_add with pre-filled fields
I have a models with 3 classes: Visite, Inclusion, BilanBiologique and ExamenBiologique Inclusion is linked to Visite (OneToOne) BilanBiologique is linked to Visite (ForeignKey) ExamenBiologique is linked to BilanBiologique (ForeignKey) ExamenBiologique is a subform of BilanBiologique I use Django admin form I try to customize my Inclusion admin form to have a link that redirect user to BilanBiologique AND I would like the "vis" field (which is the ForeignKey) to be pre-filled with the corresponding value (I can retrieve this value from Inclusion) I manage to display a link from Inclusion to BilanBiologique using a method "examen" in Inclusion class I have think about using GET method but to be honest I am lost... I have no idea how to proceed... models.py class Visite(models.Model): vis_ide = models.AutoField(primary_key=True) pat = models.ForeignKey(Participante, verbose_name='Participante', related_name='visites', on_delete=models.CASCADE) vis_dat = models.DateField("Date de consultation") def __str__(self): return f"{self.pat.pat_ide_prn_cse} / {self.vis_dat}" class BilanBiologique(models.Model): bio_ide = models.AutoField(primary_key=True) vis = models.ForeignKey(Visite, verbose_name='Visite', on_delete=models.CASCADE) bio_dat = models.DateField("Date de prélèvement") def __str__(self): return f"{self.bio_ide}" @property def date_visite(self): return self.vis.vis_dat date_visite.fget.short_description = 'Date de la visite' @property def participante(self): return self.vis.pat.pat_ide_prn_cse participante.fget.short_description = 'Participante' class ExamenBiologique(models.Model): bio_exa_ide = models.AutoField(primary_key=True) bio = models.ForeignKey(BilanBiologique, verbose_name='Bilans', related_name='examens',on_delete=models.CASCADE) bio_exa_cod = models.IntegerField("Type d'examen") bio_exa_res_num = models.FloatField("Résultat numérique", … -
How can I restream an h264 live stream with Python?
I have several IP cameras that produce h264 live streams. The cameras are located at a remote location with a metered internet connection. I have a Django/Python website that users can login to, and watch the cameras. I need to do this: If no clients are watching Cam 2 or Cam 3, the metered connection isn't being used to transfer those streams at all If at least one client is watching Cam 1, my server connects to Cam 1's h264 stream, and grabs the data, restreaming it to the client If 3 clients are all watching Cam 1, I'm restreaming the h264 stream from my HQ, rather than having all 3 streams coming directly from the metered connection Right now, I have this working using this project: https://datarhei.github.io/restreamer/ It works, but it's a little complex, as my Django code has to automatically start and stop docker containers that restream each video stream. This also introduces delay - when the first client hits "Cam 1" on the website, there's a good 10-15 seconds before they can watch the video, as docker is starting a new restreamer container, and restreamer is connecting to the source stream. The second client that wants to … -
Multiple Parameters on Django Validator
I have problems with the parameters, when The validator is written used this way: cantidadusada = models.DecimalField(max_digits=50, decimal_places=3,validators=[insumo_existencias]) It automatically gets the value of the respective field in the validator.py def insumo_existencias(value): #Por alguna razon, me esta devolviendo un string insumo = models.Insumo.objects.get(id=1) if (insumo.cantidadexistencias < value): raise ValidationError( _('Error no hay existencias suficientes'), ) So, I just have to call it value and thats it, but I want to pass another parameter,but when the function has another parameter it does not longer get the value of the field. I tried this: cantidadusada = models.DecimalField(max_digits=50, decimal_places=3,validators=[insumo_existencias(cantidadusada,idinsumo)]) It is not working. Obviosuly the validator function was changed to acept to parameters -
Protect a GET and POST endpoint?
I'm trying to protect a GET and a POST endpoint on my backend. The user is not logged in, but I want to prevent ppl from accessing the API endpoint unless they're using my app. I'm using React and axios to make the request, with Django and Python accepting the request. I'm trying to use a CSRF decorator: class ClassView(View): @method_decorator(csrf_protect) def get(self, request): # Protected endpoint. @method_decorator(csrf_protect) def post(self, request): # Protected endpoint. This doesn't work because I can still go directly to the API endpoint and make requests. I've also tried @requires_csrf_token and @csrf_protect without success. -
Django - Sending Form Data View and Back to template
I'm trying to capture data from my form and send it to my view so I can do some business logic there. I have a "booking" website project, I want the user to pick start and end dates( i have a jquery date picker in my template), and on form submit send it to my view (and the db). My view then compares the dates to the prices stored in the database so it knows the price for each day, and on redirect after form submit, data is shown in the website. Hope that makes sense. Here is my view: def apartment_view(request, apartment_id): reservation = Reservation.objects.filter(apartment__pk=apartment_id) apartment = get_object_or_404(Apartment, pk=apartment_id) unavailable = [] for start, end in apartment.reservations.values_list('start_date', 'end_date'): while start <= end: unavailable.append(start.strftime('%-d-%m-%Y')) start += datetime.timedelta(days=1) form = ReservationForm() if request.method == 'GET': form = ReservationForm() date = request.GET.get('reservation.start_date') print(date) elif request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid(): reservation = form.save(commit=False) reservation.apartment = apartment reservation.save() form.save() return HttpResponseRedirect(reverse('booking:apartment', kwargs={'apartment_id': apartment.pk})) context = {} context['form'] = form context['apartment'] = apartment context['unavailable_dates'] = json.dumps(unavailable) my form: class ReservationForm(forms.ModelForm): class Meta: model = Reservation fields = [ 'start_date', 'end_date', 'name', ] widgets = { 'start_date': TextInput(attrs={'id': 'datepicker'}), 'end_date': TextInput(attrs={'id': 'datepicker2'}), } … -
Django- how to merge this the StudentsEnrollmentRecord and ScheduleOfPayment in admin-site
\models class ScheduleOfPayment(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Display_Sequence = models.IntegerField(blank=True, null=True) Month_Name = models.ForeignKey(MonthName, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Day = models.CharField(max_length=500, blank=True, null=True) Amount = models.FloatField(null=True, blank=True) Remark = models.CharField(max_length=500,blank=True, null=True) def __str__(self): suser = '{0.Education_Levels}' return suser.format(self) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='paymenttype', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE,null=True) Remarks = models.TextField(max_length=500,null=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) \admin.py class InLinescheduleofpayment(admin.TabularInline): model = ScheduleOfPayment extra = 0 @admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecord(admin.ModelAdmin): inlines = [InLinescheduleofpayment] list_display = ('Student_Users', 'School_Year','Courses','Section','Payment_Type','Education_Levels','Discount_Type','Remarks') ordering = ('Education_Levels',) list_filter = ('Student_Users',) I just want to merge the StudentsEnrollmentRecord and ScheduleOfPayment using the foreign key of ScheduleOfPayment(Education_Levels) and StudentsEnrollmentRecord(Education_Levels), but i dont know if i am doing it right.. can you guys help me with solutions? please -
run django multiple application on different ports
How to run multiple apps in different port in django? i am using gunicorn. i want to run the multiple applications on same domain. my Procfile: web: gunicorn DCMS_API.wsgi:application i have app1 and app2 in DCMS_API. How do i host the multiple applications on same domain name as i am new to django, i am facing issue while hosting the application. my django project is uploaded with different domain names apps name getting added in the domain name. -
How to place css and html files in single directory in django
I am working on a django web application where users login to the application and create web pages. Each page can have different themes, just like a wordpress themes. Problem: I am able to create themes(templates) and dynamically load them depending upon the user choice. My problem is all the css and html files of a single theme are not located in single folder. css files are in 'static' directory and html are in 'templates' directory. I want to segregate these files. I want to create a single directory called 'Themes' in which mutliptle directories will be there for each theme like 'theme A' and 'theme B'. In each theme directory again there will be 'css' and 'js' directories. How to implement thesevand load them? -
How to save an ImageField class object in a Django session?
I couldn't save an ImageField class object in a Django session. The type of object which I like to save in a session is below. <class 'django.db.models.fields.files.ImageFieldFile'> The reason I want to do this is that I want to save the data until the ultimate registration so that this posted image data will not disappear when transitioning from the form to the confirmation page. I tried below. views.py class ProductRegister(LoginRequiredMixin, CreateView): template_name = 'app/product_register.html' form_class = ProductRegisterForm def form_valid(self, form): ctx = {'form': form} temporary_product_object = form.save(commit=False) self.request.session['product_image'] = temporary_product_object.product_image but error occurred. error message TypeError at /app/product_register/35 Object of type ImageFieldFile is not JSON serializable Here is models.py for reference. models.py product_image = models.ImageField( upload_to='images/', blank=True, null=True, ) Any feedback is greatly appreciated. Thank you in advance. -
Pagination Django Rest Framework POST
I'm trying to send a POST request through an endpoint with generic APIVIEW class. The response rendered through this post request needs to be paginated using the limit and offset which again need to be passed in the same POST request body. How can same be implemented using the LimitOffsetPagination. I have seen seen various examples of pagination in GET requests but no luck on POST request. -
TypeError: 'ForeignKey' object is not callable
class ContactInfo(models.Model): TYPES_CHOICES = ( ('Phone', ('telephone')), ('whatsapp', ('whatsapp')), ('OTHER', ('Other')) ) type = models.CharField(_('Type'), max_length=20, choices=TYPES_CHOICES) number = models.CharField(max_length=10) def __str__(self): return self.type class Address(models.Model): TYPES_CHOICES = ( ('HOME', ('Home')), ('WORK', ('Work')), ('OTHER', ('Other')) ) type = models.CharField(_('Type'), max_length=20, choices=TYPES_CHOICES) departement = models.CharField(_('Departement'), max_length=50, blank=True) corporation = models.CharField(_('Corporation'), max_length=100, blank=True) building = models.CharField(_('Building'), max_length=20, blank=True) floor = models.CharField(_('Floor'), max_length=20, blank=True) door = models.CharField(_('Door'), max_length=20, blank=True) number = models.CharField(_('Number'), max_length=30, blank=True) street_line1 = models.CharField(_('Address 1'), max_length=100, blank=True) street_line2 = models.CharField(_('Address 2'), max_length=100, blank=True) zipcode = models.CharField(_('ZIP code'), max_length=5, blank=True) city = models.CharField(_('City'), max_length=100, blank=True) state = models.CharField(_('State'), max_length=100, blank=True) country = models.CharField(_('Country'), max_length=100, blank=True) contact = models.ForeignKey(ContactInfo, on_delete=models.CASCADE, null=True, related_name='contact_info') def __str__(self): return self.zipcode Im trying to run makemigrations, but im getting this error TypeError: 'ForeignKey' object is not callable, i dont know why even thougth i been using django for a while now, but maybe im missing something, any idea what im doign wrong? -
Django - use value from GET
I am newbie in Django and I try to understand better doing what should be very easy and simple... but unfortunetly I did not manage for example I want to get a value from a GET request I have a simple view (bellow) I type the url 127.0.0.1:8000/ecrf/index/?name='Slater' in my browser I can see using my terminal that i get the value 'Slater' from request.GET['name'] but it is not display (I only see 'Hello') views.py def IndexView(request): userconnected = request.GET['name'] print('GET',request.GET['name']) return HttpResponse('Hello', userconnected) urls.py urlpatterns = [ path('index/', views.IndexView), ] -
Sentry DjangoIntegration event_level
I'm using Sentry with Django like this: sentry_integration = DjangoIntegration() sentry_sdk.init( dsn="https://xxx@sentry.io/xxx", integrations=[sentry_integration] ) and with these settings for logging: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs', 'django.log'), }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, 'django.template': { 'handlers': ['file', 'console'], 'level': 'INFO', }, 'app': { 'handlers': ['file', 'console'], 'level': 'DEBUG', } }, } If I instiantiate and call a logger in my code, this gets sent to Sentry. import logging logger = logging.getLogger(__name__) logger.error("error!") However, now I'd like to also log .warning calls. The documentation says to do this: sentry_logging = LoggingIntegration(event_level=logging.WARNING) sentry_sdk.init( dsn="https://xxx@sentry.io/xxx", integrations=[sentry_logging] ) But the LoggingIntegration is used rather than the DjangoIntegration. I've tried to use DjangoIntegration in the code above but I get this error: TypeError: init() got an unexpected keyword argument 'event_level' Is this possible? -
Unable to create Model without fields in Django rest framework
I am trying to create a model in Django rest framework, without any field information as I'm using MongoDB which doesn't have any fixed fields twitterdashmodel.py----- class TwitterMaster(models.Model): I need a way out so that I can use model to make query functionality from function based views. I am novice to Django rest framework. Need a guidance/solution to it -
"<StudentProfile: None None None>": "StudentsSubmittedDocument.Students_Enrollment_Records" must be a "StudentsEnrollmentRecord" instance
\views id = request.POST.get('ids') studentname = StudentProfile(id=id) myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) student = StudentsEnrollmentRecord.Student_Users V_insert_data = StudentsEnrollmentRecord( Student_Users=studentname, Payment_Type=payment, Education_Levels=educationlevel,School_Year=schoolyear ) V_insert_data.save() insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = studentname, Document = myfile ) insert_doc.save() return render(request, 'Homepage/pending.html') \models class StudentProfile(models.Model): DoesNotExist = None objects = None Pending_Request = [ ('Pending_Request', 'Pending_Request'), ('Enrolled', 'Enrolled'), ] Image = models.ImageField(upload_to='images',null=True,blank=True) Username = models.CharField(max_length=500,null=True,blank=True) Password = models.CharField(max_length=500,null=True,blank=True) LRN = models.IntegerField(null=True,blank=True) Firstname = models.CharField(max_length=500,null=True,blank=True) Middle_Initial = models.CharField(max_length=500,null=True,blank=True) Lastname = models.CharField(max_length=500,null=True,blank=True) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) class StudentsSubmittedDocument(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Document_Requirements = models.IntegerField(null=True,blank=True) Document = models.FileField(upload_to='files',null=True,blank=True) **how to fix this error? i tried so many times to fix this but i cant, i dont know how to fix this error, i just want to save the StudentsEnrollmentRecord(Student_Users) to StudentsSubmittedDocument(Students_Enrollment_Records) by the way this is my error. ValueError at /newEnroll/ Cannot assign "": "StudentsSubmittedDocument.Students_Enrollment_Records" must be a "StudentsEnrollmentRecord" instance.** -
Saving data to models in Django with ForeignKey relationship
When I am parsing a page I can't save category and topic to DB in Django. What should I do? class Category(models.Model): category = models.CharField(max_length=50) slug = models.CharField(max_length=60, unique=True) class Topic(models.Model): topic = models.CharField(max_length=50) slug = models.CharField(max_length=60, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Page(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) ... I wrote it, but it doesn't work. Most likely add() cannot be used with models.ForeignKey, right? If yes, how to do? from django.template.defaultfilters import slugify ... page = { 'datetime': datetime, 'title':title, 'slug':slug, 'short_text':short_text, 'text':text, 'image':image_name, 'img_source':img_source, 'page_source':page_source, } try: page = Page.objects.create(**page) except Exception as e: print(e, type(e)) category = {'category':category, 'slug':slugify(category)} category, created = Topic.objects.get_or_create(**category) page.category.add(category) topic = {'topic':topic, 'slug':slugify(topic)} topic, created = Topic.objects.get_or_create(**topic) page.topic.add(topic) -
Django and Bokeh: How do I add my graph to a Class Detail View?
I can't seem to figure out how to add my graph to a Class Detail View? Is it not possible to do so? I add it to the detailView, and call it in my template with: {{ div | safe }} But it does not show? I've gotten it to work perfectly fine in a view and template separately. Here's the whole detailview I'm trying to implement it into. DetailView class MedarbejderDetailView(FormMixin, DetailView): template_name = 'evalsys/medarbejder/detail.html' model = Medarbejder form_class = OpretEvalForm def evalgraph(self): colors = ["#40e862", "#ff9d26", "#ff1424"] over = 0 møder = 0 under = 0 none = 0 counts = [] items = ["Overstiger forventning", "Møder forventning", "Under forventning", "Ingen bedømmelse"] eval_vudering = Evaluering.objects.values("vuderingsnavn__vuderingsnavn") source = ColumnDataSource(data=dict(items=items, counts=counts)) for i in eval_vudering: if "Overstiger forventning" in i.values(): over += 1 elif "Møder forventning" in i.values(): møder += 1 elif "Under forventning" in i.values(): under += 1 elif None in i.values(): none += 1 counts.extend([over, møder, under, none]) plot = figure(x_range=items, plot_height=500, plot_width=500, title="Opsumering af evalueringer", toolbar_location=None, tools="pan, wheel_zoom, box_zoom, reset, tap", tooltips="@items: @counts") plot.title.text_font_size = "20pt" plot.vbar(x="items", top="counts", width=0.9, source=source, legend="items", line_color='black', fill_color=factor_cmap("items", palette=colors, factors=items)) plot.legend.label_text_font_size = "13pt" script, div = components(plot) return render(self, 'evalsys/medarbejder/detail.html', {'script': script, … -
How to install GDAL Library in Docker Python image?
I'm using python3.7-slim-buster docker image for my django project. Now I want to use Geo features of django. But it seems I have to install GDAL. So, I do RUN apt-get install gdal and it raises exception "E: Unable to locate package gdal-bin". Here is my docker file: FROM python:3.7-slim-buster ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # DB vars ENV DB_USER_NAME ${DB_USER_NAME} ENV DB_NAME ${DB_NAME} ENV DB_HOST ${DB_HOST} ENV DB_PORT ${DB_PORT} ENV DB_PASSWORD ${DB_PASSWORD} ENV DJANGO_SECRET_KEY ${DJANGO_SECRET_KEY} RUN apt-get install -y gdal-bin python-gdal python3-gdal RUN ["adduser", "${USER_NAME}", "--disabled-password", "--ingroup", "www-data", "--quiet"] USER ${USER_NAME} ADD ${PROJECT_NAME}/ /home/${USER_NAME}/${PROJECT_NAME} WORKDIR /home/${USER_NAME}/${PROJECT_NAME} ENV PATH="/home/${USER_NAME}/.local/bin:\${PATH}:/usr/local/python3/bin" RUN pip install --user -r requirements.txt CMD python manage.py runserver 0.0.0.0:9000 #CMD gunicorn ${PROJECT_NAME}.wsgi:application --bind 0.0.0.0:8000 EXPOSE 8000 -
Replacing links to images with images with JQuery
I am not quite experienced in JQuery but basically I am trying to build an blog ish website using django. Now I want to add images to the post and I am using this method which works fine in pure html but it doesen't seem to work with django: <html ><head></head> <body> <p>Some text with http://example.com/image.png and image and <span> nested http://example.com/second.png</span> image and an <img src="https://drop.ndtv.com/albums/AUTO/porsche-taycan-turbo/6401200x900_1_640x480.jpg"> img <span>foo</span> tag</p> <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> jQuery(function () {jQuery('body').find('*').contents().filter(function() { return this.nodeType == 3; }).each(function(i, elem) { var matches = /(.*)(http:\/\/\S+(?:\.png|\.jpg|\.gif))(.*)/g.exec(elem.wholeText); if (matches) { var parent = elem.parentNode; var before = matches[1]; var replace = jQuery('<a />').attr('href', matches[2]).append(jQuery('<img />').attr('href', matches[2]))[0]; var after = matches[3]; parent.insertBefore(document.createTextNode(before), elem); parent.insertBefore(replace, elem); parent.insertBefore(document.createTextNode(after), elem); parent.removeChild(elem); } });}); </script> </body> </html> And this is my django template where I want to use it: {% extends "blog/base.html" %} {% block title %}{{ object.title }}{% endblock %} {% block content %} <article class="media content-section"> <img class="rounded-circle article-img " src="{{object.author.profile.image.url}}"><!--adding pfp beside blog posts--> <class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted|date:"F d, Y" }}</small> <small class="text-muted">{{ object.category }}</small> {% if object.author == user %} <div class="d-flex justify-content-end"> <div class="btn-group" role="group" aria-label="Basic example"> <a class="btn … -
Import .csv file to PostgreSQL and add an autoincrementing ID in the first column
i have downloaded a csv file for testing purposes and would like to upload all of the data to postgresql Database. However, i need to have an autoincrementing ID as the first column of the DB. Initially, i created the DB with SQL Query: CREATE TABLE pps3 ( id integer NOT NULL DEFAULT nextval('products_product_id_seq'::regclass), "brandname" character varying(25), "type1" integer, "type2" integer, "type3" integer, "Total" integer ) CSV data: "brandname","type1","type2","type3" "brand1","0","0","32" "brand1","0","12","0" I tried to move the data from the CSV with this code: import psycopg2 import datetime import csv import psycopg2 conn = psycopg2.connect("host=localhost dbname=my_django_db user=postgres") cur = conn.cursor() with open('PPS-Sep.csv', 'r') as f: reader = csv.reader(f) next(reader) # Skip the header row. for row in reader: cur.execute( "INSERT INTO pps3 VALUES (%s, %s, %s, %s)",row) conn.commit() This is working fine if I do not create the initial ID column. However, if I run it like that I get an error message that I am trying to insert the brandname to the ID. Any ideas on how to go around this? -
DJANGO createsuperuser not working...TypeError: create_superuser() missing 1 required positional argument: 'username'
I am trying to create a RESTful API using Django and DRF. I have a User model which extends AbstractUser. I'm neither able to create normal users nor a superuser. For some reason, It says "TypeError: create_superuser() missing 1 required positional argument: 'username'" Here's the models.py file: import uuid from django.db import models from django.conf import settings from django.dispatch import receiver from django.contrib.auth.models import AbstractUser from django.utils.encoding import python_2_unicode_compatible from django.db.models.signals import post_save from rest_framework.authtoken.models import Token from api.fileupload.models import File @python_2_unicode_compatible class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) profile_picture = models.ForeignKey(File, on_delete=models.DO_NOTHING, null=True, blank=True) email = models.EmailField('Email address', unique=True) name = models.CharField('Name', default='', max_length=255) phone_no = models.CharField('Phone Number', max_length=255, unique=True) company_name = models.CharField('Company Name', default='', max_length=255) address = models.CharField('Address', default='', max_length=255) address_coordinates = models.CharField('Address Coordinates', default='', max_length=255) country = models.CharField('Country', default='', max_length=255) pincode = models.CharField('Pincode', default='', max_length=255) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) The serializers.py file: from django.contrib.auth.password_validation import validate_password from rest_framework import serializers from .models import User from api.fileupload.serializers import FileSerializer class UserSerializer(serializers.ModelSerializer): profile_picture = FileSerializer() def create(self, validated_data): user = User.objects.create(**validated_data) return user def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.company_name = …